Thursday, May 29, 2014

JAVA LDAP API EXAMPLE, Create User, Delete User, List All User and Group, LDAP Modify attribute

There are many functionality require in project related to LDAP.

1) Creating Users
2) Modifying attribute
3) Attaching Group to user
4) Deleting User and Group


Creating Users

-----------------------------------------------------------Code Start-----------------------------------

package com.ldap;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

import javax.naming.Context;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import com.db.IPOPSProdDB;
import com.db.VO;

public class CreateSingleUser {

   
public  void initialize(){
       
       
        DirContext ctx=null;
        Connection conn = null;
         try{       
       
            Hashtable env = new Hashtable();           
            //String password ="password";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL,"Ldap://:");          
            env.put(Context.SECURITY_AUTHENTICATION,"simple");
            //env.put(Context.SECURITY_PRINCIPAL,"cn=test1,cn=users,DC=company,DC=COM");
            env.put(Context.SECURITY_PRINCIPAL,"cn=root");
            env.put(Context.SECURITY_CREDENTIALS,"passw0rd");
            ctx=new InitialDirContext(env);
           
              VO vo = null;
              vo = new VO();
              vo.setCsr_id("wpsbind");
              vo.setCn("wpsbind");   
           
            adduser(ctx,vo);
       
       
           
           
           
         }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try{
                ctx.close();
                //conn.close();
                System.out.println("context closed");
                System.out.println("connection closed");
                }catch(Exception Ignore)
                {       
                    Ignore.printStackTrace();
                }
        }
     }


private void adduser(DirContext ctx,VO vo){
   
    try{
       
         String pass="wpsbind";
       
        Attributes attributes = new BasicAttributes();
        Attribute objClasses = new BasicAttribute("objectClass");
       /* objClasses.add("top");
        objClasses.add("person");
        objClasses.add("organizationalPerson");
        objClasses.add("inetOrgPerson")*/;
       
       
        objClasses.add("inetOrgPerson");
         objClasses.add("organizationalPerson");
         objClasses.add("person");
         objClasses.add("top");
        attributes.put(objClasses);

        // Define User attributes

        attributes.put("uid", vo.getCsr_id());
        attributes.put("sn", vo.getCn());
        attributes.put("cn", vo.getCn());
        //attributes.put("givenName", "testgivenName");
        //attributes.put("displayName", "testdisplayName");           
        attributes.put("userPassword", pass);   
       
       
       
       
        if(vo.getEmail()!=null && vo.getEmail().length() > 0){
            attributes.put("mail", vo.getEmail());
        }
        if(vo.getPhone()!=null && vo.getPhone().length() >0){
            attributes.put("mobile", vo.getPhone());
        }
       
       
         ctx.createSubcontext("uid="+ vo.getCsr_id()+",cn=users,DC=company,DC=COM",attributes);
       
       
       
       
       
       
       
    }catch(Exception e){
        e.printStackTrace();
        System.out.println("exception_for_user_LDAP >> "+vo.getCsr_id());
        //e.printStackTrace();
       
    }finally{
        try{
           
            System.out.println("pstmt closed");
           
            }catch(Exception Ignore)
            {       
                Ignore.printStackTrace();
            }
    }
}



    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
       
        CreateSingleUser createUser = new CreateSingleUser();
        createUser.initialize();

    }

}



-----------------------------------------------------------Code end-----------------------------------

Assign Group to User
Here I am reading User and Group detail from text file



--------------------Code start-----------------------------------------------------

package com.ldap;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;

public class GropReadApply {

    /**
     * @param args
     */
   
    DirContext ctx=null;
   
    public void closeContext(){
        try{
            ctx.close();
            System.out.println("context closed");
            }catch(Exception Ignore)
            {      
                Ignore.printStackTrace();
            }
    }
   
    public void assingGrouptoUser(String username, String groupName)    {

      
    try {     
      
        ModificationItem[] mods = new ModificationItem[1];
        Attribute mod =new BasicAttribute("uniqueMember",  "uid="+username+",cn=users,DC=company,DC=COM");
        mods[0] =  new ModificationItem(DirContext.ADD_ATTRIBUTE, mod);
        ctx.modifyAttributes("cn="+groupName+",cn=groups,DC=company,DC=COM", mods);
    } catch (Exception e) {
        // If user is already added, ignore exception
        System.out.println("no_assignment "+username+":"+groupName);
        e.printStackTrace();
    }/*finally{
        try{
            ctx.close();
            System.out.println("context closed");
            }catch(Exception Ignore)
            {      
                Ignore.printStackTrace();
            }
    }*/
}
   
public  DirContext initialize(){
        
      
        //DirContext ctx=null;
         try{      
      
            Hashtable env = new Hashtable();          
            //String password ="password";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL,"Ldap://:");
                     env.put(Context.SECURITY_AUTHENTICATION,"simple");
            //env.put(Context.SECURITY_PRINCIPAL,"cn=test,cn=users,DC=company,DC=COM");          
            //env.put(Context.SECURITY_CREDENTIALS,"wpsbind");
            env.put(Context.SECURITY_PRINCIPAL,"cn=root");
            env.put(Context.SECURITY_CREDENTIALS,"passw0rd");
            ctx=new InitialDirContext(env);
         }catch (Exception e) {
                e.printStackTrace();
         }
          
            return ctx;
    }
   
    public static void main(String[] args) {
        
      
        GropReadApply gropReadApply = new GropReadApply();
        gropReadApply.initialize();
        BufferedReader br = null;

        try {

            String sCurrentLine = null;

            br = new BufferedReader(new FileReader("C:\\UserGroupList.txt"));
            int couunt=0;
            int nogropu=0;
            while ((sCurrentLine = br.readLine()) != null) {
                //System.out.println(sCurrentLine);
                int start = sCurrentLine.indexOf("uid=");
                int send = sCurrentLine.indexOf(",");
                String csr_id=sCurrentLine.substring(start+4, send);
                //System.out.println(csr_id);
                int gstart = sCurrentLine.indexOf("Group : ");
                String group = sCurrentLine.substring(gstart+7).trim();
                //System.out.println(group);
                //System.out.println("NO GROUP ASSIGNED".equalsIgnoreCase(group));
              
                if(! ("NO GROUP ASSIGNED".equalsIgnoreCase(group))){
                    gropReadApply.assingGrouptoUser(csr_id, group);
                    //System.out.println(sCurrentLine);
                    couunt++;
                }else{
                    nogropu++;
                }
              
              
              
            }
            System.out.println("Has Group value"+couunt);
            System.out.println("Has no Group value"+nogropu);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null)br.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        gropReadApply.closeContext();
    }
   
   

}
---------------------------------Code end------------------------------------------------



Delete Users from LDAP

------------------------------------------------------------------------
private void deleteUser(DirContext ctx,VO vo){
    try {
        ctx.destroySubcontext("uid="+ vo.getCsr_id()+",cn=users,DC=company,DC=COM");
        System.out.println("user deleted >> "+vo.getCsr_id());
    } catch (NamingException e) {
        // TODO Auto-generated catch block
        System.out.println("exception for deleteUser >> "+vo.getCsr_id());
        e.printStackTrace();
      
    }
}

---------------------------------------------------------------------------------------------------

Shows Group and User Ids from LDAP


----------------------------------------Code start-------------------------------------------

package com.ldap;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import javax.naming.NamingEnumeration;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;

import com.db.IPOPSProdDB;
import com.db.VO;

public class LdapListAlluser {
   
   
    DirContext ctx=null;
   
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        LdapListAlluser listAlluser = new LdapListAlluser();
        listAlluser.initialize();
        //ldapUtil.adduser(null, null);
    }
   
   
   
    private void listGroup(){
       
        String base = "cn=groups,DC=company,DC=COM"; // base for LDAP
        String[] att = { "cn", "*" };
       
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        sc.setReturningAttributes(att);
       
        try {
            //inetOrgPerson
            //inetorgperson
            NamingEnumeration results = ctx.search(base,"(objectclass=groupofuniquenames)", sc);
            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // get the attributes and attribute list
                Attributes atts = sr.getAttributes();
                NamingEnumeration attrList = atts.getAll();
                // while we have attributes
                while (attrList.hasMore()) {
                Attribute attr = (Attribute) attrList.next();
                NamingEnumeration values = attr.getAll();
                String id, value = "";
                while (values.hasMore()) {
                id = attr.getID();
                value = values.next().toString();
                System.out.println(id + " " + value);
                if("cn".equalsIgnoreCase(id)){
                    System.out.println(id + " " + value);
                }
                if("uniquemember".equalsIgnoreCase(id)){
                    System.out.println(id + " " + value);
                }
                }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }
   
    private void listUsers(){
   
        String base = "cn=users,DC=company,DC=COM"; // base for LDAP
        String[] att = { "uid", "*" };
       
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
        sc.setReturningAttributes(att);
       
        try {
            //inetOrgPerson
            //inetorgperson
            NamingEnumeration results = ctx.search(base,"(objectclass=inetOrgPerson)", sc);
            while (results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                // get the attributes and attribute list
                Attributes atts = sr.getAttributes();
                NamingEnumeration attrList = atts.getAll();
                // while we have attributes
                while (attrList.hasMore()) {
                Attribute attr = (Attribute) attrList.next();
                NamingEnumeration values = attr.getAll();
                String id, value = "";
                while (values.hasMore()) {
                id = attr.getID();
                value = values.next().toString();
                //System.out.println(id + " " + value);
                if("uid".equalsIgnoreCase(id)){
                   
                    if( ("wpsbind".equalsIgnoreCase(value))){
                        System.out.println(id + " " + value);
                    }else if( ("wpsadmin".equalsIgnoreCase(value))){
                        System.out.println(id + " " + value);
                    }else {                       
                        System.out.println(id + " " + value);
                    }
                }
                }
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
    }
   
   
     private String getUserUID(String userDN) {
            int start = userDN.indexOf("=");
            int end = userDN.indexOf(",");

            if (end == -1) {
                end = userDN.length();
            }

            return userDN.substring(start+1, end);
        }
   
     public List getMembers(String groupName) throws NamingException {
            List members = new LinkedList();

            // Set up attributes to search for
            String[] searchAttributes = new String[1];
            searchAttributes[0] = "uniqueMember";

          //  ctx.
           
            Attributes attributes =     ctx.getAttributes("cn="+groupName+",cn=groups,DC=company,DC=COM", searchAttributes);
           
           
            //Attributes attributes =      ctx.getAttributes("*");
            if (attributes != null) {
                Attribute memberAtts = attributes.get("uniqueMember");
                if (memberAtts != null) {
                    for (NamingEnumeration vals = memberAtts.getAll();
                         vals.hasMoreElements();
                         members.add(getUserUID((String)vals.nextElement()))) ;
                }
            }

            return members;
        }
   
public  void initialize(){
       
       
       
         try{       
       
            Hashtable env = new Hashtable();           
            //String password ="password";
            env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL,"Ldap://:");
                  env.put(Context.SECURITY_AUTHENTICATION,"simple");
            //env.put(Context.SECURITY_PRINCIPAL,"cn=wpsbind,cn=users,DC=company,DC=COM");
            env.put(Context.SECURITY_PRINCIPAL,"cn=root");
            //env.put(Context.SECURITY_CREDENTIALS,"wpsbind");
            env.put(Context.SECURITY_CREDENTIALS,"passw0rd");
            ctx=new InitialDirContext(env);
           
            listUsers();
           
            //listGroup();
       
               
                   
           
         }catch (Exception e) {
            e.printStackTrace();
        }finally{
            try{
                ctx.close();
                System.out.println("context closed");
                }catch(Exception Ignore)
                {       
                    Ignore.printStackTrace();
                }
        }
     }

}
-----------------------------------------Code End------------------------------------



Modify attribute

public void modifyAttribute(DirContext ctx){
         try{   
                ModificationItem[] mods = new ModificationItem[1];
                Attribute mod0 = new BasicAttribute("displayName", "test");
                mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, mod0);
                ctx.modifyAttributes("uid=test1,cn=users,DC=company,DC=COM", mods);
                System.out.println("done");
         }catch (Exception e) {
                e.printStackTrace();
            }
    }

Followers