Mozilla LDAP SDK Programmer's Guide/Getting Started With LDAP Java SDK

From MozillaWiki
Jump to: navigation, search

This section shows how to develop a first LDAP client with the LDAP Java SDK.

Understanding the LDAP Java Classes

LDAP Java SDK includes the LDAP Java classes, which you use to build LDAP clients. The LDAP Java classes allow you to write client applications that connect to LDAP servers. The classes also allow you to perform standard LDAP operations. For example, you can search for entries. You can also add, update, or delete entries.

The classes are organized in the following packages.

  • com.netscape.sasl: Contains the interfaces and classes that you can use to enable your client to authenticate by using a SASL mechanism.
  • com.netscape.sasl.mechanisms: Contains an implementation of the EXTERNAL SASL mechanism driver.
  • netscape.ldap: Contains the main LDAP Java classes, including classes that allow you to connect to an LDAP server, manipulate entries and attributes, and retrieve search results.
  • netscape.ldap.ber.stream: Contains the LDAP Java classes that implement the Basic Encoding Rules (BER) for transfer syntax. For more information about BER, see ISO-IEC 8825 at http://www.iso.ch/.
  • netscape.ldap.controls: Contains the LDAP Java classes that implement specific LDAP v3 controls. The implementations include controls to request server-side sorting and persistent searches.
  • netscape.ldap.factory: Contains classes that allow you to create an SSL socket connection to a server.
  • netscape.ldap.util: Contains utility classes, such as classes to parse LDIF data and filters that allow regular expression matching.

Clients typically execute methods in LDAP Java SDK synchronously.

All LDAP operations block until the operations are completed, except for the search method, which can return information before all the results have been received.

An asynchronous interface is also provided for circumstances that require low-level interaction with an LDAP server. The asynchronous interface is discussed more fully in Writing Asynchronous Clients With LDAP Java SDK.

Understanding the Sample Java Client

The sample client in this chapter retrieves the full name (cn), last name (sn), email address (mail), and telephone number (telephoneNumber) of Barbara Jensen. You can find the program in the file in the class="directory" directory.

The client does the following:

  1. Creates a new LDAPConnection object, which represents the connection to the LDAP server.
  2. Connects to the server.
  3. Searches for a single entry, identified by the DN using the following search criteria:
    • The base DN, the starting point for the search, is uid=bjensen,ou=People,dc=example,dc=com.
    • The search scope is LDAPConnection.SCOPE_BASE, meaning only the base DN.
    • The search filter is "objectclass=*", meaning the filter matches any entry.
      As the scope narrows the search to a single entry, the search filter does not need to be more specific.
      To invoke a search on a single entry with these parameters is equivalent to using the LDAPConnection.read method.
  4. Iterates through the enumerated search results to retrieve and print the values of the cn, sn, mail, and telephoneNumber attributes.
    This iteration also allows the client to obtain multiple values for a single attribute.
  5. Disconnects from the server.

Before you compile the sample client, make sure that the file is in your CLASSPATH.

Sample Java Code

import netscape.ldap.*;
import netscape.ldap.util.*;
import java.util.*;

public class GetAttrs {
    public static void main( String[] args ) {
        try {
            UserArgs userArgs = new UserArgs("GetAttrs", args, false);
            LDAPConnection ld = new LDAPConnection();
            ld.connect(userArgs.getHost(), userArgs.getPort());

            String ENTRYDN = "uid=bjensen, ou=People, dc=example,dc=com";
            String[] attrNames = {
                "cn",               // Get canonical name(s) (full name)
                "sn",               // Get surname(s) (last name)
                "mail",             // Get email address(es)
                "telephonenumber"}; // Get telephone number(s)
            LDAPSearchResults res =
                ld.search(ENTRYDN, ld.SCOPE_BASE, "(objectclass=*)",
                    attrNames, false );

            /* Loop on results until finished; only one entry here */
            while (res.hasMoreElements()) {
                LDAPEntry findEntry = null;
                try {
                    findEntry = res.next();
                } catch (LDAPReferralException e) {
                    System.out.println("Search reference: ");
                    LDAPUrl refUrls[] = e.getURLs();
                    for (int i=0; i  refUrls.length; i++) {
                        System.out.println("\t" + refUrls[i].getUrl());
                    }
                    continue;
                } catch (LDAPException e) {
                    System.out.println("Error: " + e.toString());
                    continue;
                }

                /* Get the attributes of the entry */
                LDAPAttributeSet findAttrs = findEntry.getAttributeSet();
                Enumeration enumAttrs = findAttrs.getAttributes();

                /* Loop on attributes */
                while (enumAttrs.hasMoreElements()) {
                    LDAPAttribute anAttr =
                        (LDAPAttribute)enumAttrs.nextElement();
                    String attrName = anAttr.getName();
                    if (attrName.equals("cn")) {
                        System.out.println("Full name:");
                    } else if (attrName.equals("sn")) {
                        System.out.println("Last name (surname):");
                    } else if (attrName.equals("mail")) {
                        System.out.println("Email address:");
                    } else if (attrName.equals("telephonenumber")) {
                        System.out.println("Telephone number:");
                    }
                    /* Loop on values for this attribute */
                    Enumeration enumVals = anAttr.getStringValues();
                    if (enumVals != null) {
                        while (enumVals.hasMoreElements()) {
                            String aVal = (String)enumVals.nextElement();
                            System.out.println("\t" + aVal);
                        }
                    }
                }
            }

            ld.disconnect();
        }
        catch(LDAPException e) {
            System.out.println("Error: " + e.toString());
        }
    }
}