Monday, April 5, 2010

AD Move User to New OU

The Active Directory Connector by default creates users in CN=Users.

Sometimes, you need to move user to another ou based on some logic, for example based of location.

So, here is the code code snippet that you can use to move user to another ou and attach it to create user "Success" response code in AD Provisioining process.

import javax.naming.*;
import javax.naming.directory.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import Thor.API.Exceptions.tcAPIException;
import Thor.API.tcResultSet;
import Thor.API.tcUtilityFactory;
import Thor.API.Base.tcUtilityOperationsIntf;
import Thor.API.Operations.tcUserOperationsIntf;

import com.thortech.util.logging.Logger;
import java.util.Hashtable;
public class MoveUserToOU {
public Logger logger;

public String MoveUser2NewOU(String cn, String ADServer, String domain,String Location, String AdminID, String Password){
String rtnval="EXECUTION_SUCCESS";
if (Location.equalsIgnoreCase(""))
{
return rtnval;
}
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_PROTOCOL, "ssl");
env.put(Context.PROVIDER_URL, "ldaps://"+ADServer+":636/");
//AdminID="Administrator@identity.com"
env.put(Context.SECURITY_PRINCIPAL, AdminID);
//Password="Password1";
env.put(Context.SECURITY_CREDENTIALS, Password);
try {
DirContext ctx = new InitialDirContext(env);
String OldCN="CN="+cn+",OU=Users,OU=OTHR,"+domain;
logger.debug("Old CN:"+OldCN);
String NewCN="CN="+cn+",OU=Users,OU="+getNewOU(Location)+","+domain;
logger.debug("New CN:"+NewCN);
logger.debug("Starting Modify DN ");
ctx.rename(OldCN, NewCN);
logger.debug("Ended Modify DN with Success..."+rtnval);
//ctx.rename("CN=Tanweer Ahmad,OU=HR,dc=identity,dc=com", "CN=Tanweer Ahmad,OU=IT,dc=identity,dc=com");
//System.out.println(ctx.lookup("CN=Tanweer Ahmad,OU=IT,dc=identity,dc=com"));
ctx.close();
} catch (Exception e) {
logger.debug("Ended Modify DN with Error...");
rtnval="ERROR : "+e.getMessage();
e.printStackTrace();
}
return rtnval;
}

public String getNewOU(String Location) {
String NewOU="";
if(Location.equalsIgnoreCase("CA"))
NewOU="CA";
else
if(Location.equalsIgnoreCase("TN"))
NewOU="TN";
else
if(Location.equalsIgnoreCase("NJ"))
NewOU="NJ";
else
if(Location.equalsIgnoreCase("TX"))
NewOU="TX";
return NewOU;
}
}