An approach to LDAP with Java

Discussion in 'Java' started by thiruganeshkumar@gma, Jun 22, 2007.

  1. thiruganeshkumar@gma

    thiruganeshkumar@gma New Member

    Joined:
    Jun 22, 2007
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0

    LDAP - The Lightweight Directory Access Protocol



    This directory access protocol which can either act as a gateway to other service or provide service itself. LDAP follows standardized way of managing directory information solutions of X.500.

    The Lightweight Directory Access Protocol, better known as LDAP, is based on the X.500 standard, but significantly simpler and more readily adapted to meet custom needs.

    X.500

    The X.500 directory service is a global directory service. Its components cooperate to manage information about objects such as countries, organizations, people, machines, and so on in a worldwide scope. It provides the capability to look up information by name and to browse and search for information.

    Advantages
    • Global namespace
    • A plat form and data independent way of describing our directory information.
    Why LDAP , Even X.500 Service is available

    The X.500 service is available but this has several disadvantages while implementing.

    Disadvantages
    • Runs on the OSI communications stack
    • Difficult in implementation, because based on OSI rather than internet protocols.

    The LDAP an Approach for Directory Service



    The LDAP is updated with removing some of confusing and clunkier parts of the X.500 protocol land moving the underlying network communications protocol from OSI to TCP/IP and revealed the light weight Directory Access Protocol.

    The original version of LDAP was created at the University of Michigan. LDAP version 3(LDAPV 3) has now made it possible to give us the power we need to finally synchronize all of our networking and directory information into manageable system.

    LDAP implementation



    The LDAP used in more secure purpose. For example a list of users can only read the values, list of users can only update etc.,. The entry can be securely maintained.

    LDAP is particularly useful for storing information that you wish to read from many locations, but update infrequently.

    For example in a company the LDAP may be used for the following purposes
    • Company Employee information like address, phone number, email etc.
    • Company vendor, service provides etc.,
    • Configuration information for distributed software packages
    • Public certificates and security keys
    The LDAP implemented when we receive the following requirements
    • Data to be available cross-platform
    • Data accessed with different application
    • Data may not frequently updated (not a transitional information)
    • Instead of using Flat file we can implement LDAP

    Advantages of LDAP for industries (Reasons for Choose LDAP)


    • Open solution

      It’s and open standard any one allowed to develop LDAP servers/clients, providing suggestions for future enhancements of existing implementations without paying any fee.
    • Severity

      LDAP uses the same object data format as X.500 where each object is made up of attributes that are indexed and referenced by a distinguished name. The name of each object is unique to fit into a global namespace that helps determine the relationship of the object and allows for the object to be references uniquely.

      "In a directory no object stands alone. Each object has a relationship to every other object in the directory service."

    • Standard API

      There are lot of peoples providing APIS for LDAP like Michigan API, Netscape LDAP SDK’s, Sun Java JNDI ( Java Naming & directory Interfaces ), Microsoft Achieve Directory Services Interfaces (AOSI), Per LOAP SOK etc.

    • Gateway Services

      Through LSAP it’s easy to make gateways like web, and have LDAP provide a gateway to other directory services. By providing gateway we make it very simple to use a this client to access directory information.

    • Vendor Supports

      There are so many vendors released their own LDAP serves Netscape, Novell, Sun, Microsoft.

    • LDAP Terminology

      It’s called an object or an object entry.

    • Entry

      An entry in an LDAP, we call as a record in LDAP server. Its akin to record in a traditional data base.

    • Attributes

      An entry is made up of attributes. It’s divided into names value pairs. It’s very similar to fields in database management system. An attribute will have only one name but it can have more than one value. The values may be text, Binary depends on the definition of and attribute.

      dn: The entry is uniquely identified by distinguished name (DN).

      RDN: Relative distinguished name, the dn is made up of components, which is called RDN.

    • Object classes

      Identifies what attributes are available to an entry. These are very akin to tables in data base management system. It’s differing from ‘tables’ in the way of there are extensible.

      For example object class that allows a set of attributes like last name, a first name, email etc, and if we want add extra attributes to this object class, we can declare anew object class that extends from earlier one. This new object class would have the ability to recognize the older object class attribute as well as the new ones we added.

    • Schema

      Each LDAP server have schema. The schema is a blueprint of the server and it specifies all of the object classes and attributes that are available to be searched and stored in LDAP server.

      The directory server is accessed like a tree and is referred to on a directory information tree (DIT). The directory server itself is called as a directory service agent (DSA).

      If an objectclass is not present in schema, then it’s not possible to add the object class.

      For Example OpenLDAP, the Schema imported in the file slapd.conf

      Include /usr/local/etc/openldap/schema/core.schema
      include /usr/local/etc/openldap/schema/cosine.schema
      include /usr/local/etc/openldap/schema/inetorgperson.schema

    LDAP a Detailed information



    The LDAP contains major three parts they are
    • Data format
      ( Defines how the directory information is stored and recalled)​
    • The Protocol
      ( Defines how clients and server in tract with each other)​
    • The API
      (Defines how programs in traction LDAP server , Novell LDAP API, sun’s JNDI etc)​

    The LDAP data format



    The LDAP data format is most difficult part. The data format in LDAP is in cross culture comparing with DBMS. Each entry in LDAP participates in a global naming schema called namespace.

    In LDAP, the top level is called the domain. There can be several domains in an LDAP implementation. This is because, like X.500, LDAP is designed to help provide a global directory service. Typically, the top-level domain will just be the root of the organization or organizations that a particular company manages.

    The branches are in the form of organizational units, which are usually departments in an organization, but can be any convenient sub-division of that organization. Each entry that is not a domain and not an organizational unit is called a leaf. It is wise to have people in an organization entries in both an organizational unit called People, as well *** under their department released organizational unit, since this can speed up searches.

    Each entry identified by unique dn.

    Domains, organizational units and every other type of information that is contained in the LDAP server must have a unique entry, and these entries must be a member of a particular object class.

    Schemas, Objects and LDAP



    Each LDAP server defines the object classes and the object hierarchy in a schema. Remember the schema is the blue print of the LDAP server. The schema defines the format of the records in the database.

    The entries in LDAP are in the form of Objects. The object paradigm was chosen because it allows any form of data to be stored in and LDAP server. Also, objects can be extended without having the completely redefined. To illustrate what I mean, let’s consider a database. In traditional database design which uses the familiar table, field model, you are fixed to a particular design once the database has been created. If you have a table of some kind and your want to add some fields to it, you would normally have to redesign and recreate the table from scratch. Under the object paradigm, however, if you have an object A and you want to use it to create Object B, you can just declare that you want to use all of the attributes available under object A and then add some new attributes to make Object B. Another neat off-shoot of this is that now all objects that are of type B are also objects of type A because Object B is derived from Object A.

    By using objects, it’s possible to store a wide variety of data, including for instance
    • The organization itself, such as where it is located.
    • People, like their names and passwords.
    • Particular machine attributes, including password management information, such as how many times a user can re-try to authenticate and how old the password can be before it expires.
    • Other computers on the Internet, similar to DNS.

    Attributes and Distinguished Names



    When building a distinguished name (DN) for a person object, you want to make the lead entry in the DN the user ID, because this entry is probably unique for the entire server. If you don’t have a user ID field, you may have to combine entries to make a unique entry. A possible combination would be one of common name and employee number.

    Here is an example DN for a person object:
    dn: cn=thiru,ou=people,o=ldapOrg,c=us

    The LDAP protocol



    A client starts an LDAP session by connecting to an LDAP server, by LDAP port [ default on TCP port 389 ]. The client then sends operation requests to the server, and the server sends responses in turn.

    Operations on LDAP protocol
    • Connects to the server.
    • Performs a series of operations with the server.
    • Disconnects from the server

    The LDAP API



    The LDAP API supports in C, C++ programming, Java and Perl. There are several wide verity of API vendors available in market example Sun Java JNDI API, Novell LDAP SDK, Michigan API, Netscape SDK etc.

    For this article I covered only Java programming API JNDI and Novell LDAP API.

    The LDAP - focus



    The primary focus of LDAP is to define directory data records in a standard format so that any user can access and store information locally. The way LDAP achive this is through object classes, which are made up of attributes. Every entry in and LDAP server defines the object classes if accepts and the way it handle, request to those object classes through a schema or data definition.

    The Lightweight Directory Access Protocol (LDAP) is cross-platform directory and set of protocols designed to access and maintain information directories. LDAP can be used for numerous purposes, like user and group management, system configuration management, or address management.

    LDAP servers will be read more rafter than written to.

    The rest of the article covered with the OpenLDAP 2.3.35 setup and running, Connecting LDAP server through Sun JNDI API and Novell LDAP SDK API for Java programming.

    OpenLDAP an Introduction and Setup



    OpenLDAP Software is an open source implementation of the Lightweight Directory Access Protocol.

    System Requirements

    The article example uses the following system

    Code:
    Operating System		Open Suse Linux 10.1
    OpenLDAP			OpenLDAP 2.3.35
    Java                                          java version “1.4.2_12”
    Editors			Linux vi  & eclipse 3.2 for java
    Setup OpenLDAP on Suse Linux

    1. Download the latest OpenLDAP from the OpenLDAP software download site
    2. unpack in a temporary location gunzip -c openldap-2.3.35.tgz
    3. Run the configure from the unpacked location
    4. Build the software by using “make depend” and “make” commands
    5. Test the build by “make test”
    6. Install the software using “su root -c 'make install'”

    Dependencies

    When we are running “configure” the openLDAP dependent with BerkeleyDB for database. If we got that error we need install BerkeleyDB in to Suse Linux. The BerkeleyDB download available here.

    After installing BerkeleyDB we need to configure the following system environment variables before running “configure”.

    Code:
    linux:/opt/openldap-2.3.32 # CPPFLAGS="-I/usr/local/BerkeleyDB.4.5/include"
    linux:/opt/openldap-2.3.32 # LDFLAGS="-L/usr/local/lib -L/usr/local/BerkeleyDB.4.5/lib -R/usr/local/BerkeleyDB.4.5/lib"
    linux:/opt/openldap-2.3.32 # LD_LIBRARY_PATH="/usr/local/BerkeleyDB.4.5/lib"
    linux:/opt/openldap-2.3.32 # export CPPFLAGS
    linux:/opt/openldap-2.3.32 # export LDFLAGS
    linux:/opt/openldap-2.3.32 # export LD_LIBRARY_PATH
    linux:/opt/openldap-2.3.32 # ./configure
    After compleating successful “configure” we need to check the slapd.conf file for the admin name, password and root dn. For this article I used the following structure

    Code:
    suffix		"o=ldapOrg,c=us"
    rootdn		"cn=Manager,o=ldapOrg,c=us"
    rootpw		secret
    we can start the LDAP server using the following command
    Code:
    su root -c /usr/local/libexec/slapd
    Test the LDAP by using ldapsearch command.
    LDAP Search command
    Code:
    linux:/home/ldaprd/samples/ldaparticle.ldif # ldapsearch -x -b '' -s base '(objectclass=*)'
    Code:
    namingContexts
    # extended LDIF
    #
    # LDAPv3
    # base <> with scope baseObject
    # filter: (objectclass=*)
    # requesting: namingContexts
    #
    #
    dn:
    namingContexts: o=ldapOrg,c=us
    # search result
    search: 2
    result: 0 Success
    # numResponses: 2
    # numEntries: 1
    Adding initial entries to LDAP directory

    1. Create an ldif file to add the initial entries
    2. add the ldif file to the LDAP through “ldapadd” command

    Sample LDIF file applied for this article

    In this example all lines commented , for test each face one by one. Please uncomment the portions to add.

    Code:
    #The following contents added for the BASE dn
    #This is example for o=ldapOrg,c=us
    
    # adding organization attributes
    #dn: o=ldapOrg,c=us
    #objectclass: organization
    #objectclass: top
    #o: ldapOrg
    
    #dn: o=ldapOrg,c=us
    #objectclass: country
    #objectclass: top
    #c: us
    
    #adding organizational units 1. Groups, 2. people
    #1.
    #dn: ou=groups,o=ldapOrg,c=us
    #objectclass: top
    #objectclass: organizationalUnit
    #ou: groups
    
    #2.
    #dn: ou=people,o=ldapOrg,c=us
    #objectclass: top
    #objectclass: organizationalUnit
    #ou: people
    
    #adding people
    #1.
    #dn: uid=Sam,ou=people,o=ldapOrg,c=us
    #cn: Sam Sample
    #sn: Cater
    #objectclass: top
    #objectclass: person
    #objectclass: organizationalPerson
    #objectclass: inetOrgPerson
    #ou: Dept
    LDAP add command

    ldapadd -x -D "cn=Manager,ou=article,o=ldap,c=us" -W -f article.ldif

    For more Information please refer http://www.openldap.org/doc/admin23/quickstart.html

    The LDAP An approach with JNDI



    The Java Naming and Directory Interface (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the Java programming language. It is defined to be independent of any specific directory service implementation.

    JNDI and LDAP Samples



    Getting the DirContext of LDAP Server

    The DirContext returned by InitialDirContext object by supplying the all context values in a Map object.

    Code:
    /**
     * This method used to get the DirContext through the JNDI API
     * @return DirContext
     * @throws NamingException
     */
    public DirContext getLDAPDirContext() throws NamingException{
    	final Hashtable envValues = new Hashtable();
    	// Assign the JNDI environment values in Map
    	envValues.put(Context.INITIAL_CONTEXT_FACTORY,LDAPConstants.INITIAL_CONTEXT_FACTORY);
    	envValues.put(Context.PROVIDER_URL, LDAPConstants.PROVIDER_URL);
    	envValues.put(Context.SECURITY_AUTHENTICATION,LDAPConstants.SECURITY_AUTHENTICATION);
    	envValues.put(Context.SECURITY_PRINCIPAL,LDAPConstants.LDAP_LOGIN_DN); // specify the username
    	envValues.put(Context.SECURITY_CREDENTIALS,LDAPConstants.LDAP_ADMIN_PASSWORD);           // specify the password
    	return new InitialDirContext(envValues);
    
    }
    Create an entry

    For creating an entry for people object I created and People.java class file which implements DirContext.

    Code:
    public People(String uid,String cn,String givenname,String sn,String ou,String mail) {
    	
    	myAttrs = new BasicAttributes(true);  //Basic Attributes
    	Attribute objectClass = new BasicAttribute("objectclass"); //Adding Object Classes
    	
    	objectClass.add("inetOrgPerson");
    	objectClass.add("organizationalPerson");
    	objectClass.add("person");
    	objectClass.add("top");
    
    	Attribute ouSet = new BasicAttribute("ou");
    	ouSet.add("people");
    	ouSet.add(ou);
    	
    	myAttrs.put(objectClass);
    	myAttrs.put(ouSet);
    	myAttrs.put("uid",uid);
    	myAttrs.put("cn",cn);
    	myAttrs.put("sn",sn);
    	myAttrs.put("givenname",givenname);
    	myAttrs.put("mail",mail);
    }
    Adding entry

    To add an entry the dn name must be unique, at the time of binding the cn name must match with the object cn name i.e people object attribute cn.

    By using bind() we can add an entry.
    Code:
    public static void main(String[] args) {
    	final JNDILDAPConnectionManager jndiManager = new JNDILDAPConnectionManagerImpl();
    	try{
    		final String groupDN ="ou=people,o=ldapOrg,c=us";
    		DirContext dirCtx = jndiManager.getLDAPDirContext();
    		People people = new People("Thiru","Thiru","Thiru Ganesh","Ramalingam","ou=people","thiru@jndiapi.com"); 
    		// The Common name must be equal in Attributes common Name
    		dirCtx.bind("cn=Thiru," + groupDN, people);
    		System.out.println("** Entry added **");
    		jndiManager.disConnectLDAPConnection(dirCtx);
    		
    	}catch(NamingException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    }
    Delete an entry

    The delete operation is easiest one, once get the DirContext we can supply the unique dn to destroySubcontext() method.

    Code:
    public static void main(String[] args) {
    	
    	final JNDILDAPConnectionManager jndiManager = new JNDILDAPConnectionManagerImpl();
    	final String groupDN = "cn=Thiru,ou=people,o=ldapOrg,c=us";
    	try{
    		DirContext dirCtx = jndiManager.getLDAPDirContext();
    		dirCtx.destroySubcontext(groupDN);
    		jndiManager.disConnectLDAPConnection(dirCtx);
    		System.out.println("** Entry deleated **");
    		
    	}catch(NamingException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    
    }
    Search an Entry

    The search entry is the important one which is mostly used in LDAP server, the search can be implemented with searchFilter (entry to find) and SearchBase (start search base) present in LDAP directory data.

    By creating the searchcontrol object with SeatchFilter and Searchbase we can directly search in the DirContext through search() method which returns Enumaration object.

    Code:
    public static void main(String[] args) {
    	final JNDILDAPConnectionManager jndiManager = new JNDILDAPConnectionManagerImpl();
    	final String searchFilter = "cn=Thiru";
    	final String searchBase = "o=ldapOrg,c=us";
    
    	try{
    		
    		DirContext dirCtx = jndiManager.getLDAPDirContext();
    		if (getSearchResult(dirCtx, searchFilter, searchBase)) {
    			System.out.println("** FOUND ** "); 
    		}else{
    			System.out.println("** NOT FOUND ** ");
    		}
    
    		jndiManager.disConnectLDAPConnection(dirCtx);
    		
    	}catch(NamingException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    }
    
    /**
     * This method is used to search an entry in LDAP using Novell API
     * @param dirContext
     * @param searchFilter
     * @param searchBase
     * @return {@link Boolean}
     * @throws NamingException
     */
    private static final boolean getSearchResult(final DirContext dirContext, 
    		final String searchFilter, 
    		final String searchBase) throws NamingException{
    	
    	boolean retVal = false;
    	
    	final SearchControls constraints = new SearchControls();
    	constraints.setSearchScope(LDAPConstants.SUBTREE_SCOPE);
    	
    	System.out.println("** Search Starts : "  + System.currentTimeMillis());
    	final NamingEnumeration searchResults = dirContext.search(searchBase,searchFilter,constraints);
    	System.out.println("** Search Ends : "  + System.currentTimeMillis());
    	
    	if(searchResults != null && searchResults.hasMore()){
    		retVal= true;
    		// For Example , displayed attribute values
    		final SearchResult searchResult = (SearchResult)searchResults.next();
    		displayAttributes(searchResult.getAttributes());
    	}
    
    	return retVal;
    }
    
    /**
     * This method used to display the Attribute Values
     * @param attributes
     * @throws NamingException
     */
    private static void displayAttributes(final Attributes attributes) throws NamingException{
    	
    	if (attributes == null) {
    		System.out.println("*** No attributes ***");
    	} 
    	else {
    		for (NamingEnumeration enums = attributes.getAll(); enums.hasMore();) {
    			final Attribute attribute = (Attribute)enums.next();
    			System.out.println("Id :" + attribute.getID());
    			for (NamingEnumeration namingEnu = attribute.getAll();namingEnu.hasMore();)
    				System.out.println("\t        = " + namingEnu.next());
    		}
    
    	}
    }
    The example shows the code snippets, please refer the complete set code for full implementation.

    The LDAP An easy approach with Novell LDAP SDK



    The Novell provides the LDAP API for getting LDAPConnection, adding vales, search, delete and LDAP server related information. To use Novell API we need the ldap.jar file from the Novell LDAP SDK. Its available in Novell download site.

    Getting LDAP Connection

    To get the LDAPConnection Novell provides LDAPConnection object which requires LDAP host , connection port. When we are going to bind to get the connection we need to supply the LDAP version, Login DN and admin password.

    Code:
    /**
     * This method used to get the LDAP Connection through the Novell API
     * @return LDAPConnection
     * @throws LDAPException
     */
    public LDAPConnection getLDAPConnection() throws LDAPException {
    	final LDAPConnection connection = new LDAPConnection();
    	connection.connect(LDAPConstants.LDAP_HOST, LDAPConstants.LDAP_CONNECTION_PORT);
    	
    	try {
    		connection.bind(LDAPConstants.LDAP_VERSION, LDAPConstants.LDAP_LOGIN_DN, LDAPConstants.LDAP_ADMIN_PASSWORD.getBytes("UTF8"));
    	} catch (UnsupportedEncodingException exception) {
    		exception.printStackTrace();
    		throw new LDAPException();
    	}
    	
    	return connection;
    }
    Getting the Server Schema values

    Each and every LDAP server contains the schema values which are supplied in slapd.conf file. To get the list of schema object the Novell LDAP API provides fetchSchema() method from the LDAPConnection which returns LDAPSchema object.

    Code:
    /**
     * This main method executes a sample program for Listing schema vales.
     * @param args
     */
    public static void main(String[] args) {
    	
    	NovellLDAPConnectionManager novellConnManager = new NovellLDAPConnectionManagerImpl();
    	LDAPSchema schema =null;
    	try{
    		//Get the LDAPConnection
    		LDAPConnection lConn = novellConnManager.getLDAPConnection();
    		//Fetch schema from the DN
    		schema = lConn.fetchSchema(lConn.getSchemaDN());
    		//Disconnect from LDAP
    		novellConnManager.disConnectLDAPConnection(lConn);
    	
    	}catch(LDAPException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    	
    	List schemaList = getSchemaList(schema.getObjectClassSchemas());
    	System.out.println("**** Schema List ****");
    	System.out.println(schemaList);
    
    }
    
    /**
     * This private method used to return List of Schema Objects 
     * @param objectClassSchema
     * @return List
     */
    private static final List getSchemaList(final Enumeration objectClassSchema) {
    	final List retVal = new ArrayList();
    	LDAPObjectClassSchema nextItem = null;
    	while (objectClassSchema.hasMoreElements()) {
    		nextItem = (LDAPObjectClassSchema)objectClassSchema.nextElement();
    		final String[] names = nextItem.getNames();
    		for (int i=0; i< names.length; i++)
    			retVal.add(names[i]);
    	}
    	return retVal;
    }
    Adding entry

    To add an entry in to LDAP directory we need to get the LDAPConnection object and prepare LDAPEntry object to add in to LDAPConnection. The LDAPentry created through LDAPAttributeSet.

    The dn must be unique value. In LDAPEntry.

    Code:
    /**
     * This method used to add en entry in to LDAP Server under people
     * @param args
     */
    public static void main(String[] args) {
    	final NovellLDAPConnectionManager novellConnManager = new NovellLDAPConnectionManagerImpl();
    	final String groupDN = "ou=people,o=ldapOrg,c=us";
    	try{
    		//Get the LDAPConnection
    		final LDAPConnection lConn = novellConnManager.getLDAPConnection();
    		lConn.add( getLDAPEntry(groupDN) );
    		novellConnManager.disConnectLDAPConnection(lConn);
    		System.out.println("** Entry added **");
    	}catch(LDAPException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    
    }
    
    /**
     * This method used to return an LDAP entry object.
     * @param group
     * @return {@link LDAPEntry}
     */
    private static final LDAPEntry getLDAPEntry(final String group){
    	
    	final LDAPAttributeSet attributeSet = new LDAPAttributeSet();
    	//new String("inetOrgPerson"))
    	attributeSet.add( new LDAPAttribute("objectclass", new String[]{"inetOrgPerson", "top", "organizationalPerson" ,"person"}) );                
    	//Common Name cn must match in DN's CN
    	attributeSet.add( new LDAPAttribute("cn",new String("Thiru")));                
    	attributeSet.add( new LDAPAttribute("givenname",new String[]{"Thiru", "Ganesh", "Thiru Ganesh" }));        
    	attributeSet.add( new LDAPAttribute("sn", new String("Ramalingam")));        
    	attributeSet.add( new LDAPAttribute("telephonenumber",new String("+91 9840281277")));                                                     
    	attributeSet.add( new LDAPAttribute("mail",new String("thiru@novellapi.com")));
    	attributeSet.add( new LDAPAttribute("userpassword",new String("article")));                                           
    	
    	final String  dn  = "cn=Thiru," + group;      
    	final LDAPEntry retValue = new LDAPEntry( dn, attributeSet ); 
    	
    	return retValue;
    
    }
    Delete an entry

    To delete an entry it is easy to call through LDAPConnection by supplying dn to delete.

    Code:
    /**
     * This method used to delete an entry by passing its DN
     * @param args
     */
    public static void main(String[] args) {
    
    	final NovellLDAPConnectionManager novellConnManager = new NovellLDAPConnectionManagerImpl();
    	final String groupDN = "cn=Thiru,ou=people,o=ldapOrg,c=us";
    	try{
    		//Get the LDAPConnection
    		final LDAPConnection lConn = novellConnManager.getLDAPConnection();
    		//Delete
    		lConn.delete( groupDN );
    		novellConnManager.disConnectLDAPConnection(lConn);
    		System.out.println("** Entry deleated **");
    	}catch(LDAPException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    }
    Search an Entry

    The search entry is the important one which is mostly used in LDAP server, the search can be implemented with searchFilter (entry to find) and SearchBase (start search base) present in LDAP directory data.

    To search an entry through this API, by using search method in LDAPConnection object, it returns the LDAPSearchResults object which contains the found information. If its null then no data found in LDAP.

    Code:
    /**
     * This method used to search an entry in LDAP Server.
     * @param args
     */
    public static void main(String[] args) {
    	
    	final NovellLDAPConnectionManager novellConnManager = new NovellLDAPConnectionManagerImpl();
    	final String searchFilter = "cn=Thiru";
    	final String searchBase = "o=ldapOrg,c=us";
    	try{
    		//Get the LDAPConnection
    		final LDAPConnection lConn = novellConnManager.getLDAPConnection();
    		
    		if (getSearchResult(lConn, searchFilter, searchBase)) {
    			System.out.println("** FOUND ** "); 
    		}else{
    			System.out.println("** NOT FOUND ** ");
    		}
    
    	}catch(LDAPException exception){
    		System.out.println("**** Error ****");
    		exception.printStackTrace();
    		System.exit(0);
    	}
    }
    
    /**
     * This method is used to search an entry in LDAP using Novell API
     * @param lConnection
     * @param searchFilter
     * @param searchBase
     * @return {@link Boolean}
     * @throws LDAPException
     */
    private static final boolean getSearchResult(final LDAPConnection lConnection, 
    		final String searchFilter, 
    		final String searchBase) throws LDAPException{
    	
    	boolean retVal = false;
    	System.out.println("** Search Starts : "  + System.currentTimeMillis());
    	final LDAPSearchResults searchResults =
    		lConnection.search(
    				searchBase,
    				LDAPConstants.SCOPE_SUB,
    				searchFilter,
    				null,
    				false);
    	System.out.println("** Search Ends : "  + System.currentTimeMillis());
    	if (searchResults != null && searchResults.hasMore()) {
    		// For Example , displayed only one attribute value 
    		LDAPEntry entry = searchResults.next();
    		System.out.println("Mail.: " + entry.getAttribute("mail"));
    		retVal= true; 
    	}
    	return retVal;
    }
    Interface Class Constants

    Code:
    /**
     * @author 		R. Thiru Ganesh Kumar
     * $name: 		LDAPConstants.java     
     * $description:This is the Interface class used to maintain the Constant vales
     * 				of the LDAPConnection.  
     */
    public interface LDAPConstants {
    	/* This variable contains the value of LDAP login */
    	public static final String LDAP_LOGIN_DN = "cn=Manager,o=ldapOrg,c=us";
    	/* This variable contains the value of LDAP Connection Port */
    	public static int LDAP_CONNECTION_PORT = LDAPConnection.DEFAULT_PORT;
    	/* This variable contains the value of LDAP password */
    	public static String LDAP_ADMIN_PASSWORD = "secret";
    	/* This variable contains the value of LDAP version */
    	public static int LDAP_VERSION =  LDAPConnection.LDAP_V3;
    	/* This variable contains the value of LDAP host */
    	public static String LDAP_HOST = "localhost";
    	/* This variable contains the value of JNDI Initial context factory */
    	public static String INITIAL_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
    	/* This variable contains the value of JNDI LDAP URL */
    	public static String PROVIDER_URL = "ldap://" + LDAP_HOST + ":"+ LDAP_CONNECTION_PORT;
    	/* This variable contains the value of JNDI LDAP Security authentication */
    	public static String SECURITY_AUTHENTICATION = "simple";
    	/* This variable contains the value of Novell API Search Scope */
    	public static int SCOPE_SUB = LDAPConnection.SCOPE_SUB;
    	/* This variable contains the value of JNDI API Search Control Sub tree Scope */
    	public static int SUBTREE_SCOPE =  SearchControls.SUBTREE_SCOPE;
    }

    Conclusion



    This article mainly focused on LDAP with Java. The LDAP basic operations are implemented through JNDI and Novell LDAP API are explained. I believe it may be help full for the beginners who are all interested in LDAP operations.

    My Sincerely thanks to Rajesh Chairmakani and Isrel Kumar who motivated, helped me to write this first article.

    References



    http://www.openldap.org/
    http://java.sun.com/products/jndi/tutorial/
    http://developer.novell.com/documentation//jldap/jldapenu/api/com/novell/ldap/package-summary.html

    "Implementing LDAP" author MARK WILCOX , ISBN 81-7366-174-X, Wrox India Pvt Ltd.,
     

    Attached Files:

  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Really impressive!
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice