Friday, April 11, 2008

LdapOperations

You may use the following code to create quick ldap assisting functions:
==========================================
LdapOperations.java
==========================================

package com.bhatiacorp.operations;

import java.util.Hashtable;

import javax.naming.*;
import javax.naming.directory.*;

import com.thortech.util.logging.Logger;

public class LdapOperations {

private String loggerTag;
private Logger logger;
private String CLASS_NAME;
private String ldapHost;
private String ldapPort;
private String adminID;
private String adminPassword;
boolean useSSL;

public LdapOperations(String ldapHost, String ldapPort, String adminID, String adminPassword, boolean useSSL){
this.ldapHost = ldapHost;
this.ldapPort = ldapPort;
this.adminID = adminID;
this.adminPassword = adminPassword;
this.useSSL = useSSL;
loggerTag = "XL_INTG.BHATIACORP_LDAPOPERATIONS";
logger = Logger.getLogger(loggerTag);
CLASS_NAME = getClass().getName();

logger.info(" server name = " + ldapHost );
logger.info(" server port = " + ldapPort );
logger.info("adminId = " + adminID);
logger.info(" useSSL = " + useSSL );
}


private DirContext getContext(String ldaphost, String ldapport, String adminID, String adminpassword, boolean useSSL)
{
DirContext ctx=null;
String providerurl=ldaphost+":"+ldapport;
if(ldapport=="")
{
ldapport="636";
}
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY ,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL ,providerurl);
if(useSSL==true)
{
// if SSL is used - use can use ssl enabled ldaphost
// eg. "ldaps://localhost:636"
// else
// eg. "ldap://localhost:636"
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
env.put(Context.SECURITY_AUTHENTICATION ,"simple");
env.put(Context.SECURITY_PRINCIPAL ,adminID);
env.put(Context.SECURITY_CREDENTIALS ,adminpassword);
ctx = new InitialDirContext(env);

}
catch(Exception ex)
{
ex.printStackTrace();
}
return ctx;
}

private DirContext getContext()
{
DirContext ctx=null;
try {
ctx=getContext("ldap://"+ldapHost,ldapPort,adminID,adminPassword,useSSL);
}
catch(Exception ex)
{
ex.printStackTrace();
}

return ctx;
}


/**
* @param cn
* @param attribute
* @param value
* @return
*/
public String addAttribute(String cn,String attribute, String newvalue) throws NamingException{
String rtnval="EXECUTION_SUCCESS";
DirContext ctx= null;
try{
ctx=getContext();
ModificationItem[] mods = new ModificationItem[1];
mods[0]=new ModificationItem(DirContext.ADD_ATTRIBUTE,new BasicAttribute(attribute,newvalue));
ctx.modifyAttributes(cn, mods);

}catch(Exception ex){
rtnval="ERROR: "+ex.getMessage();
ex.printStackTrace();
}finally{
ctx.close();
}
return rtnval;
}

/**
* @param cn
* @param attribute
* @param value
* @return
*/
public String modifyAttribute(String userId,String attribute, String newvalue) throws NamingException{
String rtnval="EXECUTION_SUCCESS";
DirContext ctx= null;
try{
System.out.println();
ModificationItem[] mods = new ModificationItem[1];
ctx=getContext();
mods[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(attribute,newvalue));
ctx.modifyAttributes("cn="+userId, mods);
}catch(Exception ex){
rtnval="ERROR: "+ex.getMessage();
ex.printStackTrace();
}finally{
ctx.close();
}
return rtnval;
}

/**
* @param cn
* @param attribute
* @param value
* @return
*/
public String modifyAttributeWithOutFullDN(String userId,String directoryRootNode, String attribute, String newvalue) throws NamingException{
String rtnval="EXECUTION_SUCCESS";

DirContext ctx= null;
try
{
ctx=getContext();
logger.info(" userId = " + userId );
ModificationItem[] mods = new ModificationItem[1];
String userDN=searchFullDn(directoryRootNode, "cn=" + userId);
logger.info(" user full dn = " + userDN );
logger.info(" attr name = " + attribute + " value = " + newvalue);
mods[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(attribute,newvalue));
ctx.modifyAttributes(userDN, mods);

logger.info(" update was done successfully ");
}catch(Exception ex){
rtnval="ERROR: "+ex.getMessage();
ex.printStackTrace();
}finally{
ctx.close();
}
return rtnval;
}

/*
public void printAttributes(Attributes attrs)
{
try
{
for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll(); e.hasMore();
System.out.println("value: " + e.next()));
}}catch(Exception ex)
{
ex.printStackTrace();
}

}
*/

/**
* @param cn
* @param attribute
* @param value
* @return
*/
public String deleteAttribute(String cn,String attribute, String newvalue) throws NamingException{
String rtnval="EXECUTION_SUCCESS";
ModificationItem[] mods = new ModificationItem[1];
try
{
DirContext ctx=getContext();
mods[0]=new ModificationItem(DirContext.REMOVE_ATTRIBUTE,new BasicAttribute(attribute,newvalue));
ctx.modifyAttributes(cn, mods);
}
catch(Exception ex)
{
rtnval="ERROR: "+ex.getMessage();
ex.printStackTrace();
}
return rtnval;
}


public String setADManagerInfo(String userId,String directoryRootNode, String mgrEmployeeId) throws NamingException{
String rtnval="EXECUTION_SUCCESS";

DirContext ctx= null;
try
{
ctx=getContext();
logger.info(" userId = " + userId );
logger.info(" manager employee id = " + mgrEmployeeId);
ModificationItem[] mods = new ModificationItem[1];
String userDN=searchFullDn(directoryRootNode, "cn=" + userId);
logger.info(" Manager DN to be searched is = " + "(|(extensionAttribute1=" + mgrEmployeeId+ ")(cn="+ mgrEmployeeId+ "))");
String managerDN = searchFullDn(directoryRootNode, "(|(extensionAttribute1=" + mgrEmployeeId+ ")(cn="+ mgrEmployeeId+ "))" );
if(this.isEmptyString(managerDN)){
return "EXECUTION_FAILURE_MANAGER_DOESN'T_EXISTS";
}
logger.info(" user full dn = " + userDN );
logger.info(" attr name is manager value = " + managerDN);
mods[0]=new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("manager", managerDN));
ctx.modifyAttributes(userDN, mods);

logger.info(" update was done successfully ");
}catch(Exception ex){
rtnval="ERROR: "+ex.getMessage();
}finally{
ctx.close();
}
return rtnval;
}


/**
* @param directoryRootNode
* @param nameToSearch
* @return
*/
public String searchFullDn(String directoryRootNode,String nameToSearch){
try
{
SearchControls searchControls = new SearchControls (SearchControls.SUBTREE_SCOPE, 1, 0, new String[0], true, false);
NamingEnumeration srchResults = getContext().search(directoryRootNode, "(&("+nameToSearch+")(objectclass=*))",searchControls);
if (srchResults.hasMore())
{
SearchResult sr = (SearchResult)srchResults.next();
return sr.getName().toString()+","+directoryRootNode;
}
} catch (NamingException e){
e.printStackTrace();
}
return "";
}

/**
*
* @param cnvalue
* @param fname
* @param lname
* @param treevalue
* @return
*/
public String createUser(String cnvalue, String fname, String lname, String treevalue){
String rtnval="EXECUTION_SUCCESS";
String treenodevalue="ou=People,dc=bhatiacorp,dc=com";
if(treevalue!="")
treenodevalue=treevalue;
try {
BasicAttributes attrs = new BasicAttributes();
BasicAttribute ocs = new BasicAttribute("objectClass");
ocs.add("top");
ocs.add("person");
ocs.add("organizationalPerson");
//Add whichever classes apply in your case
attrs.put(ocs);
attrs.put(new BasicAttribute("cn" , cnvalue));
attrs.put(new BasicAttribute("sn" , lname));
attrs.put(new BasicAttribute("displayName" , fname+" "+ lname));
String fulldn="cn="+cnvalue+","+treenodevalue;
getContext().createSubcontext(fulldn, attrs);
}
catch (Exception ex) {
rtnval="ERROR: "+ex.getMessage();
ex.printStackTrace();
}

return rtnval;
}

/**
*
* @param cnvalue
* @return
*/
public String deleteUser(String cnvalue)
{
String rtnval="EXECUTION_SUCCESS";
String dn=searchFullDn("dc=bhatiacorp,dc=com", cnvalue);
try {
getContext().destroySubcontext(dn);
}
catch (Exception ex) {
rtnval="ERROR: "+ex.getMessage();
ex.printStackTrace();
}

return rtnval;

}


/**
* Return true if the given string is empty.
*/
public final boolean isEmptyString(String toCheck) {
if ((toCheck != null) && (toCheck.trim().length() > 0)) {
return false;
}
return true;
}

/**
* Return true if the given object is null.
*/
public final boolean isNull(Object toCheck) {
return (toCheck == null);
}

/**
*
* @param cn
* @param domain
* @param NewOU
* @return
*/
public String moveUser2NewOU(String cn, String domain,String NewOU){
String rtnval="EXECUTION_SUCCESS";
try {
DirContext ctx=getContext();
String OldCN="CN="+cn+",CN=Users,"+domain;
System.out.println("Old CN:"+OldCN);
String NewCN="CN="+cn+",OU="+NewOU+","+domain;
System.out.println("New CN:"+NewCN);
System.out.println("Starting Modify DN ");
ctx.rename(OldCN, NewCN);
System.out.println("Ended Modify DN with Success..."+rtnval);
//ctx.rename("CN=Rajnish Bhatia,OU=HR,dc=bhatiacorp,dc=com", "CN=Rajnish Bhatia,OU=IT,dc=bhatiacorp,dc=com");
//System.out.println(ctx.lookup("CN=Rajnish Bhatia,OU=IT,dc=bhatiacorp,dc=com"));
ctx.close();
} catch (Exception e) {
System.out.println("Ended Modify DN with Error...");
rtnval="ERROR : "+e.getMessage();
e.printStackTrace();
}
return rtnval;
}

/**
* @param args
*/
public static void main(String[] args) {
try
{
LdapOperations c=new LdapOperations();
//System.out.println(c.createUser("AB","ABtest","test","ou=People,dc=bhatiacorp,dc=com"));
System.out.println(c.modifyAttribute("cn=AB,ou=People,dc=bhatiacorp,dc=com", "extensionAttribute12", "12-12-1999"));
//System.out.println(c.searchFullDn("dc=bhatiacorp,dc=com","cn=AB"));
//System.out.println(c.deleteUser("cn=AB"));
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}

No comments: