Skip to content

Instantly share code, notes, and snippets.

@arjunKumbakkara
Last active May 18, 2017 11:34
Show Gist options
  • Save arjunKumbakkara/2bf03fb898131d756790d917fd1e35da to your computer and use it in GitHub Desktop.
Save arjunKumbakkara/2bf03fb898131d756790d917fd1e35da to your computer and use it in GitHub Desktop.
LDAP Integration Protocol V2.0 API
package ldap;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Properties;
/**
*
* @author Arjun Kumbakkara
* @version 1.0.0
*
* <p>
* <b><u>Development History</u></b><br>
* <table border="1" width="100%">
* <tr>
* <td width="15%"><b>Date</b></td>
* <td width="20%"><b>Author</b></td>
* <td><b>Description</b></td>
* </tr>
* <tr>
* <td>May 10th, 2017</td>
* <td>Arjun Kumbakkara</td>
* <td>For **Telecom Operator[ West Zone ]</td>
* </tr>
* </table>
* </p>
* @since May 18th ,2017
* @for **** technologies
*
* Usage:
* Use as a wrapper
* Autowire this as a Bean and Call [Spring Boot bias 'Hell yeah']
* new isn't that bad.
*
* For More Details/Use Cases REACH/CHECK @https://arjunkumbakkara.github.io/
* or
* directly
* https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*/
public class LDAPIntegrationModule {
private static final String Zone =" West";
private static final String LDAPBANNER = "**** "+Zone+" ZONE LDAP-----> ";
private String server;
private int port;
private String BindDN;
private String userName;
private String password;
/*We take Default port as 389 as it is*/
private boolean isConnected;
private InitialDirContext connectionDir;
/**Method stub creates a new Connection on the default port 389
* @param Server Address
* @param BindDN
* @param UserName(Can be Ignored)
* @param Bind Password [incase of Simple Authentication]
* @return No Return as such but creates the Ldap Context for further Operations.
* @see https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
* */
public LDAPIntegrationModule(String server, String BindDN, String userName, String password) throws NamingException{
reInitiateConnection(server, 389, BindDN, userName, password);
}
/**Method stub creates a new Connection on the CUSTOM port which is passed
* @param Server Address
* @param BindDN
* @param port
* @param UserName(Can be Ignored)
* @param Bind Password [incase of Simple Authentication]
* @return No Return as such but creates the Ldap Context for further Operations.
* @see https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
* */
public LDAPIntegrationModule(String server, int port, String BindDN, String userName, String password) throws NamingException{
reInitiateConnection(server, port, BindDN, userName, password);
}
/**Method stub creates a new Connection on the default port 389 by killing the existing connection
* @param Server Address
* @param BindDN
* @param port
* @param UserName(Can be Ignored)
* @param Bind Password [incase of Simple Authentication]
* @return No Return as such but creates the Ldap Context for further Operations.
* @see https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public void reInitiateConnection(String server, String BindDN, String userName, String password) throws NamingException{
reInitiateConnection(server, 389, BindDN, userName, password);
}
/**Method stub creates a new Connection on the custom port passed by killing the existing connection
* @param Server Address
* @param BindDN
* @param UserName(Can be Ignored)
* @param Bind Password [incase of Simple Authentication]
* @return No Return as such but creates the Ldap Context for further Operations.
* @see https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
* */
public void reInitiateConnection(String server, int port, String BindDN, String userName, String password) throws NamingException{
if (isConnected){
close();
}
this.server = server;
this.port = port;
this.BindDN = BindDN;
this.userName = userName;
this.password = password;
connectAlready();
}
/**The Real DEAL
* @return A connection
* @see https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
private void connectAlready() throws NamingException{
Hashtable<String, String> ldapEnv = new Hashtable<String, String>(11);
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
//ldapEnv.put(Context.PROVIDER_URL, "ldap://societe.fr:389");
ldapEnv.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
//ldapEnv.put(Context.SECURITY_PRINCIPAL, "cn=administrateur,cn=users,dc=societe,dc=fr");
ldapEnv.put(Context.SECURITY_PRINCIPAL, BindDN);
ldapEnv.put(Context.SECURITY_CREDENTIALS, password);
//ldapEnv.put(Context.SECURITY_PROTOCOL, "ssl");
//ldapEnv.put(Context.SECURITY_PROTOCOL, "simple");
//ldapEnv.put(Context.REFERRAL, "ignore");
ldapEnv.put("java.naming.ldap.version", "2");
ldapEnv.put("java.naming.ldap.derefAliases", "never");
connectionDir = new InitialDirContext(ldapEnv);
System.out.println(LDAPBANNER + "Authentication Success! LDAP BRIDGING IS SUCCESSFUL");
/*
Properties conf = new Properties();
conf.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
conf.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);
conf.put(Context.SECURITY_CREDENTIALS, password);
conf.put(Context.SECURITY_PRINCIPAL, BindDN);
conf.put("java.naming.ldap.version", "2");
conf.put("java.naming.ldap.derefAliases", "never");
connectionDir = new InitialDirContext(conf);
System.out.println(LDAPBANNER + "Authentication Success! LDAP BRIDGING IS SUCCESSFUL");*/
isConnected = true;
}
/*""::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::LDAP::CRUD Operations for an "ENTITY"::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::"
*/
/**THE REAL DEAL : This is the flat search!! returns a single object ! So the UID passed has to be unique.
* @param String UID / any String
* @return Search result
* @see https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public SearchResult getEntity(String uid) {
String searchFilter = "(&(objectClass=entity)(uid=" + uid + "))";
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
try {
NamingEnumeration<SearchResult> rs = connectionDir.search(BindDN, searchFilter, searchControls);
if (rs.hasMoreElements()) {
SearchResult searchResult = rs.nextElement();
//The uid Passed has to be Unique No matter what!
if (rs.hasMoreElements()) {
System.err.println(LDAPBANNER + "Encountered Error as Multiple Matches are found for the passed UID: " + uid);
return null;
}
return searchResult;
}
} catch (NamingException e) {
System.err.println(LDAPBANNER + "Failure looking for user with with this (" + uid + ") error: " + e.getMessage());
}
return null;
}
/**
* Pass a filter here in this
* Takes in searchFilter a ldap search filter (ex. '(&(objectClass=entity)(uid=8197494489))')
* @return ArrayList<SearchResult> is returned.
* If nothing found returns NULL
*
*
* @param searchBase [base from where the search starts in the tree]
* @param searchFilter [Required/devised filter]
* @param searchControls [Collection of all search options.refer for more]
*
* This is a specific case where we pass search base , search filter and Search control set explicitly.
* @throws Exception
* @see Refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
*/
public SearchResult getRSByCustomFilterSupply(String searchBase,String searchFilter,SearchControls searchControls) throws Exception {
SearchResult searchResult =null;
NamingEnumeration<SearchResult> rs = connectionDir.search(searchBase, searchFilter, searchControls);
if (rs.hasMoreElements()) {
searchResult = rs.nextElement();
System.out.println("Response Thus ::: "+searchResult.toString());
/* if (!rs.hasMoreElements()) {
System.err.println(LDAPBANNER + "Encountered Error as Multiple Matches/non differential results found are found for the passed UID: ");
return null;
}*/
}else{
System.err.println(LDAPBANNER + "Encountered Error as Multiple Matches/non differential results found are found for the passed Filter: ");
throw new Exception("SearchResult Collection returned as empty.Which denotes Erroneos Integration");
}
return searchResult;
}
/**
* If nothing found returns NULL
* Refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* FOR BSNL WEST ZONE
*
* @param searchFilter [Pass Only the filter]
*
* Here we just pass the Filter..Rest is opinionated.
*
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*/
public SearchResult getRSByCustomFilterSupply(String searchFilter) throws NamingException {
SearchResult searchResult =null;
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
boolean on = false;
searchControls.setDerefLinkFlag(on);
searchControls.setTimeLimit(1000);
String searchBase = "dview=WZ2OCS1_request_data";
NamingEnumeration<SearchResult> rs = connectionDir.search(searchBase, searchFilter, searchControls);
/* if (rs.hasMoreElements()) {
ArrayList<SearchResult> searchResultSet = new ArrayList<SearchResult>();
while (rs.hasMore()) {
searchResultSet.add(rs.next());
}
return searchResultSet;
}*/
if (rs.hasMoreElements()) {
searchResult = rs.nextElement();
System.out.println("Response Thus ::: "+searchResult.toString());
/* if (!rs.hasMoreElements()) {
System.err.println(LDAPBANNER + "Encountered Error as Multiple Matches/non differential results found are found for the passed UID: ");
return null;
}*/
}else{
System.err.println(LDAPBANNER + "Encountered Error as Multiple Matches/non differential results found are found for the passed Filter: ");
}
return searchResult;
}
/**CREATE Operation for LDAP (Active Directory)
*
*
* @param uid [UID string]
* @param value [Attributes Colection]
*
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public boolean addEntity(String uid, Attributes value) {
String dName = getDName(uid);
try {
connectionDir.createSubcontext(dName, value);
System.out.println(LDAPBANNER + "Add Entity : Entity added is " + dName + ".");
return true;
} catch (NameAlreadyBoundException e) {
System.err.println(LDAPBANNER + "Add Entity: Entity Already Exists in LDAP directory");
return false;
} catch (NamingException e) {
System.err.println(LDAPBANNER + "Error encountered while adding Entity" + e.getMessage());
return false;
}
}
/** UPDATE Operation for LDAP (Active Directory)
* @param uid [UID string]
* @param ModificationItem[] updateValues [ModificationItem Colection]
*
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
* refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public boolean updateEntity(String uid, ModificationItem[] updateValues) {
try {
connectionDir.modifyAttributes(getDName(uid), updateValues);
return true;
} catch (NamingException e) {
System.err.println(LDAPBANNER + "Update encountered Failure: " + e.getMessage());
return false;
}
}
/** DELETE Operation for LDAP (Active Directory)
*
* @param uid [UID string]
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public boolean deleteEntity(String uid) {
try {
connectionDir.destroySubcontext(uid);
return true;
} catch (NamingException e) {
System.err.println(LDAPBANNER + "Deletion encountered Failure: " + e.getMessage());
return false;
}
}
/** Kills the established LDAP Connection
* @param none
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public void close() {
isConnected = false;
try {
connectionDir.close();
System.out.println(LDAPBANNER + "Connection closed and killed!");
} catch (NamingException e) {
System.err.println(LDAPBANNER + "Closure Failure: failed to close the connection: " + e.getMessage());
}
}
/** Connection Status Checker
*
* @param none
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
public boolean isConnected() {
return isConnected;
}
/**This basically is a set of comma seperated values called as Distinguished name[Gotta be unique]
*
* @param none
* @see refer https://gist.github.com/arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882
*
* */
private String getDName(String uid) {
return "uid=" + uid + "," + BindDN;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment