Mozilla LDAP SDK Programmer's Guide/Comparing Attribute Values With LDAP Java SDK

From MozillaWiki
Jump to: navigation, search

This section explains how to compare the value of an attribute in an entry against a specified value.

Specifying the Attribute and Value With LDAP Java SDK

Use an LDAPAttribute object to specify the name of the attribute to check. Also use the object to specify the value to use in the comparison.

LDAPAttribute attr = new LDAPAttribute("mail", "bjensen@example.com");

Performing the Comparison With LDAP Java SDK

To perform the comparison, use the compare method of the LDAPConnection object. Specify the distinguished name of the entry that you want to compare. The method returns true if the attribute contains the specified value.

try {
    LDAPConnection ld = new LDAPConnection();
    ld.connect("localhost", LDAPv3.DEFAULT_PORT); 
    LDAPAttribute attr = new LDAPAttribute("mail", "bjensen@example.com");
    if (ld.compare("uid=bjensen,ou=People,dc=example,dc=com", attr)) {
        System.out.println("Found a match.");
    }
} catch (LDAPException e) {
    System.err.println("Error:" + e.toString());
}

Example Attribute Value Comparison With LDAP Java SDK

The following example compares values for the objectclass attribute with values on Barbara Jensen's entry.

import netscape.ldap.*;
import java.util.*;
 
public class Compare {
    public static void main(String[] args) {
            try {
                UserArgs userArgs = new UserArgs("Compare", args, false);
                LDAPConnection ld = new LDAPConnection();
                ld.connect(userArgs.getHost(), userArgs.getPort());
 
                /* Entry to compare */
                String ENTRYDN = "uid=bjensen,ou=People,dc=example,dc=com";
 
                /* Compare the value "person" and the attr. "objectclass" */
                LDAPAttribute attr =
                    new LDAPAttribute("objectclass", "person");
                boolean ok = ld.compare(ENTRYDN, attr);
                reportResults(ok, attr);
 
                /* Compare the value "xyzzy" and the attr. objectclass */
                attr = new LDAPAttribute("objectclass", "xyzzy");
                ok = ld.compare(ENTRYDN, attr);
                reportResults(ok, attr);
 
                ld.disconnect();
            } catch(LDAPException e) {
                System.out.println("Error: " + e.toString());
            }
        }
 
    private static void reportResults(boolean ok, LDAPAttribute attr) {
        String result;
        if (ok) {
            result = new String();
        } else {
            result = new String("not ");
        }
        Enumeration en = attr.getStringValues();
        if (en != null) {
            String val = (String)en.nextElement();
            System.out.println(
                "The value *" + val + "* is " + result +
                "contained in the " + attr.getName() + " attribute.");
        }
    }
}