package com.bhatiacorp.utils;
import java.security.Provider;
import java.security.Security;
import java.util.Hashtable;
import java.util.Vector;
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.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import Thor.API.tcResultSet;
import Thor.API.tcUtilityFactory;
import Thor.API.Operations.tcLookupOperationsIntf;
import com.thortech.util.logging.Logger;
import com.thortech.xl.dataaccess.tcDataProvider;
public class DistributionListUtils {
private String loggerTag;
private Logger logger;
private String CLASS_NAME;
public static double DISTRIBUTION_GROUP_GLOBAL = 2D;
public static double SECURITY_GROUP_GLOBAL = -2147483646D;
private String mLdapHost;
private String mLdapPort;
private String mAdminID;
private String mAdminPassword;
private boolean mUseSSL;
private String mLdapDistributionListLocation;
private String mRootContext;
private tcLookupOperationsIntf lookIntf;
private static String lookupCodeKeyCol = "Lookup Definition.Lookup Code Information.Code Key";
private static String lookupDecodeKeyCol = "Lookup Definition.Lookup Code Information.Decode";
public DistributionListUtils(String pLdapHost, String pLdapPort,
String pAdminID, String pAdminPassword, String pUseSSL,
String pLdapDistributionLocation, String pRootContext) {
loggerTag = "XL_INTG.BHATIACORP_UTILS";
logger = Logger.getLogger(loggerTag);
CLASS_NAME = getClass().getName();
mLdapHost = pLdapHost;
mLdapPort = pLdapPort;
mAdminID = pAdminID;
mAdminPassword = pAdminPassword;
mUseSSL = (pUseSSL.equalsIgnoreCase("true")) ? true : false;
mLdapDistributionListLocation = pLdapDistributionLocation;
mRootContext = pRootContext;
if (mUseSSL) {
Provider provider = Security.getProvider("com.sun.net.ssl.internal.ssl.Provider");
try {
if (provider == null) {
Class class1 = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
Provider provider1 = (Provider) class1.newInstance();
Security.addProvider(provider1);
}
} catch (ClassNotFoundException classnotfoundexception) {
logger.error("DistributionListUtils -> Exception while setting provide for ssl. Could not find class com.sun.net.ssl.internal.ssl.Provider.\n"
+ classnotfoundexception.getMessage());
} catch (IllegalAccessException illegalaccessexception) {
logger.error("DistributionListUtils -> Exception while setting provide for ssl. IllegalAccessException: "
+ illegalaccessexception.getMessage());
} catch (InstantiationException instantiationexception) {
logger.error("DistributionListUtils -> Exception while setting provide for ssl. InstantiationException: "
+ instantiationexception.getMessage());
}
}
}
private DirContext getDirContext(String pLdapHost, String pLdapPort,
String pAdminID, String pAdminPassword,
boolean pUseSSL) {
DirContext ctx = null;
String providerurl = pLdapHost + ":" + pLdapPort;
if (pLdapPort == "") {
pLdapPort = "636";
}
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, providerurl);
if (pUseSSL == true) {
env.put(Context.SECURITY_PROTOCOL, "ssl");
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, pAdminID);
env.put(Context.SECURITY_CREDENTIALS, pAdminPassword);
ctx = new InitialDirContext(env);
} catch (Exception ex) {
ex.printStackTrace();
}
return ctx;
}
private DirContext getDirContext() {
DirContext ctx = null;
try {
if (mUseSSL = true) {
ctx = getDirContext("ldaps://" + mLdapHost, mLdapPort,
mAdminID, mAdminPassword, true);
} else {
ctx = getDirContext("ldap://" + mLdapHost, mLdapPort, mAdminID,
mAdminPassword, false);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return ctx;
}
/**
* Close the directory context of the LDAP server.
*
*/
protected void closeContext(DirContext ctx) {
try {
if (ctx != null) {
ctx.close();
}
} catch (NamingException e) {
logger.warn("DirContext.close failed", e);
}
}
public String assignDistributionList(String pDepartmentID, String pUserId,
String pCompany) throws Exception {
String rtnval = "EXECUTION_SUCCESS";
String tempDepartmentID = new String(pDepartmentID);
if (this.isEmptyString(pDepartmentID)) {
tempDepartmentID = (pCompany.equalsIgnoreCase("BHATIACORP"))
? new String("0000")
: new String("0000-CON");
}
String groupName = "CN="+ tempDepartmentID;
String groupDN = groupName + "," + this.mLdapDistributionListLocation;
//check if group Exists.
Vector groupSearchResult = this.search("(&(objectclass=group)("+groupName+"))");
if(groupSearchResult.isEmpty()){
createGroup(groupDN, pCompany);
}
Vector memberList = getSepcifiedGroupAttributeValue(groupName, "member");
if(memberList == null)
memberList = new Vector();
for(int i = 0; i < memberList.size(); i++){
String member = (String)memberList.elementAt(i);
member = member.toUpperCase();
memberList.setElementAt(member, i);
}
String userDN = getUserDN(pUserId);
if(!memberList.contains(userDN)){
addUserToGroup(userDN, groupDN);
}
return rtnval;
}
public boolean addUserToGroup(String userDN, String groupDN) throws Exception{
DirContext dirCtx = null;
try{
BasicAttributes basicattributes = new BasicAttributes(true);
basicattributes.put(new BasicAttribute("member", userDN));
dirCtx = getDirContext();
dirCtx.modifyAttributes(groupDN,dirCtx.ADD_ATTRIBUTE, basicattributes);
return true;
}catch(Exception exp){
throw exp;
}finally{
this.closeContext(dirCtx);
}
}
public boolean removeUserToGroup(String userDN, String groupDN) throws Exception{
DirContext dirCtx = null;
try{
BasicAttributes basicattributes = new BasicAttributes(true);
basicattributes.put(new BasicAttribute("member", userDN));
dirCtx = getDirContext();
dirCtx.modifyAttributes(groupDN,dirCtx.REMOVE_ATTRIBUTE, basicattributes);
return true;
}catch(Exception exp){
throw exp;
}finally{
this.closeContext(dirCtx);
}
}
public boolean createGroup(String pGroupName, String companyName) throws Exception{
try{
String defaultGroupMemberShip = null;
double groupType = 0D;
String groupName = new String(pGroupName);
if(companyName.equalsIgnoreCase("BHATIACORP")){
defaultGroupMemberShip = "CN=ALL-BCORP-STAFF" +"," + this.mLdapDistributionListLocation;
groupType = DistributionListUtils.SECURITY_GROUP_GLOBAL;
}else{
defaultGroupMemberShip = "CN=ALL-NON-BCORP-STAFF" +"," + this.mLdapDistributionListLocation;
groupName = groupName.concat("-CON");
groupType = DistributionListUtils.DISTRIBUTION_GROUP_GLOBAL;
}
Double groupTypeDouble = new Double(groupType);
String groupTypeDoubleStr = Integer.toString(groupTypeDouble.intValue());
return createGroup(pGroupName, groupTypeDoubleStr, defaultGroupMemberShip );
}catch(Exception exp){
throw exp;
}
}
public boolean createGroup(String groupName, String groupType, String defaultGroupMembership) throws Exception{
DirContext dirCtx = null;
try{
dirCtx = getDirContext();
BasicAttributes basicattributes = new BasicAttributes(true);
basicattributes.put(new BasicAttribute("objectclass", "group"));
basicattributes.put(new BasicAttribute("cn", groupName));
basicattributes.put(new BasicAttribute("sAMAccountName", groupName));
basicattributes.put(new BasicAttribute("groupType", groupType));
basicattributes.put(new BasicAttribute("memberOf", defaultGroupMembership));
dirCtx.createSubcontext(groupName, basicattributes);
return true;
}catch(Exception exp){
throw exp;
}finally{
this.closeContext(dirCtx);
}
}
private String getUserDN(String pUserId) throws Exception{
DirContext dirCtx = null;
try{
String userId = "CN="+ pUserId;
dirCtx = getDirContext();
Vector searchResults = search("("+userId+ ")");
if(searchResults.isEmpty())return null;
String userDNValue = (String)searchResults.get(0);
String userDN = userDNValue + "," + this.mRootContext;
return new String(userDN.toUpperCase());
}catch(Exception exp){
throw exp;
}finally{
this.closeContext(dirCtx);
}
}
public Vector getSepcifiedGroupAttributeValue(String groupName, String lookfor) throws Exception{
DirContext dirCtx = getDirContext();
try{
String[] attributes = {lookfor};
Vector searchResults = search("("+groupName+ ")", attributes);
SearchResult searchResult = (SearchResult)searchResults.get(0);
Attributes searchResultAttributes = searchResult.getAttributes();
Attribute attr = searchResultAttributes.get(lookfor);
Vector attrVector = new Vector(attr.size());
for(int i=0; i< attr.size(); i++){
String value = new String(attr.get(i).toString());
attrVector.add(value.toUpperCase());
}
closeContext(dirCtx);
return attrVector;
}catch(Exception exp){
throw exp;
}finally{
this.closeContext(dirCtx);
}
}
public Vector search(String filter) throws Exception{
DirContext ctx = null;
try{
ctx = getDirContext();
SearchControls searchcontrols = new SearchControls();
searchcontrols.setSearchScope(2);
SearchResult searchresult;
NamingEnumeration namingenumeration = ctx.search(this.mRootContext, filter, searchcontrols);
Vector vector = new Vector();
for(;namingenumeration.hasMoreElements();vector.addElement(searchresult.getName())){
searchresult = (SearchResult)namingenumeration.nextElement();
searchresult.setRelative(false);
}
return vector;
}catch(Exception exception){
logger.error("Error during search : " + exception);
}finally{
closeContext(ctx);
}
return null;
}
public Vector search(String filter, String[] retAttr) throws Exception{
DirContext ctx = null;
try{
ctx = getDirContext();
SearchControls searchcontrols = new SearchControls();
searchcontrols.setSearchScope(2);
if(retAttr != null)
searchcontrols.setReturningAttributes(retAttr);
SearchResult searchresult;
NamingEnumeration namingenumeration = ctx.search(this.mRootContext, filter, searchcontrols);
Vector vector = new Vector();
for(;namingenumeration.hasMoreElements();vector.addElement(searchresult)){
searchresult = (SearchResult)namingenumeration.nextElement();
searchresult.setRelative(false);
}
return vector;
}catch(Exception exception){
logger.error("Error during search : " + exception);
}finally{
closeContext(ctx);
}
return null;
}
public String getLookupCodeValue(String lookupName, String valueToLookFor, tcDataProvider tcdataprovider)
throws Exception{
lookIntf = (tcLookupOperationsIntf)tcUtilityFactory.getUtility(tcdataprovider, "Thor.API.Operations.tcLookupOperationsIntf");
tcResultSet tcresultset = lookIntf.getLookupValues(lookupName);
int i = tcresultset.getRowCount();
for(int j = 0; j < i; j++){
tcresultset.goToRow(j);
if(valueToLookFor.equalsIgnoreCase(tcresultset.getStringValue(lookupDecodeKeyCol)))
return tcresultset.getStringValue(lookupCodeKeyCol);
}
return "";
}
/**
* 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);
}
}//end of class DistributionListUtils
courtesy:Rajesh Mittal
Friday, April 11, 2008
DistributionListUtils
Posted by Rajnish Bhatia at 6:07 PM
Subscribe to:
Post Comments (Atom)
1 comment:
Hi Rajnish,
Thank you for sharing the code.
Is the memberOf a mandatory attribute?
When I tried to run the code (modified to fit my case), I get this error:
javax.naming.NamingException: [LDAP: error code 80 - 00000523: SysErr: DSID-031A0FB6, problem 22 (Invalid argument), data 0
^@]; remaining name 'CN=UCD-FINE-1400-004,OU=STUDENTS,dc=ucdenver,dc=pvt'
at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3049)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2951)
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2758)
at com.sun.jndi.ldap.LdapCtx.c_createSubcontext(LdapCtx.java:774)
What does this mean?
Thanks
Post a Comment