Skip to content

Instantly share code, notes, and snippets.

@arjunKumbakkara
Last active May 10, 2017 18:05
Show Gist options
  • Save arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882 to your computer and use it in GitHub Desktop.
Save arjunKumbakkara/66b37d09ac6217bba70cc6af6fd88882 to your computer and use it in GitHub Desktop.
LDAP Server Java Integration [Active Directory Integration with CRUD Operations]
package ldapmodule;
import javax.naming.*;
import javax.naming.directory.*;
import java.util.ArrayList;
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[ South Zone ]</td>
* </tr>
* </table>
* </p>
* 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 @https://arjunkumbakkara.github.io/
*/
public class LDAPIntegrationModule {
private static final String Zone =" North";
private static final String LDAPBANNER = "TELECOM OPERATOR** "+Zone+" ZONE LDAP-----> ";
private String server;
private int port;
private String entityDN;
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*/
public LDAPIntegrationModule(String server, String entityDN, String userName, String password) throws NamingException{
reInitiateConnection(server, 389, entityDN, userName, password);
}
/**Method stub creates a new Connection on the CUSTOM port which is passed*/
public LDAPIntegrationModule(String server, int port, String entityDN, String userName, String password) throws NamingException{
reInitiateConnection(server, port, entityDN, userName, password);
}
/**Method stub creates a new Connection on the default port 389 by killing the existing connection*/
public void reInitiateConnection(String server, String entityDN, String userName, String password) throws NamingException{
reInitiateConnection(server, 389, entityDN, userName, password);
}
/**Method stub creates a new Connection on the custom port passed by killing the existing connection*/
public void reInitiateConnection(String server, int port, String entityDN, String userName, String password) throws NamingException{
if (isConnected){
close();
}
this.server = server;
this.port = port;
this.entityDN = entityDN;
this.userName = userName;
this.password = password;
connectAlready();
}
/**The Real DEAL*/
private void connectAlready() throws NamingException{
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, userName);
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.*/
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(entityDN, 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
*/
public ArrayList<SearchResult> getRSByCustomFilterSupply(String searchFilter) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration<SearchResult> rs = connectionDir.search(entityDN, searchFilter, searchControls);
if (rs.hasMoreElements()) {
ArrayList<SearchResult> searchResultSet = new ArrayList<SearchResult>();
while (rs.hasMore()) {
searchResultSet.add(rs.next());
}
return searchResultSet;
}
return null;
}
/**CREATE Operation for LDAP (Active Directory)*/
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)*/
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)*/
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*/
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*/
public boolean isConnected() {
return isConnected;
}
/**This basically is a set of comma seperated values called as Distinguished name[Gotta be unique]*/
private String getDName(String uid) {
return "uid=" + uid + "," + entityDN;
}
}
package ldapmodule;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchResult;
/**
*
* @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[ South Zone]</td>
* </tr>
* </table>
* </p>
*/
public class LDAPSimulator {
static LDAPIntegrationModule ldap=null;
public static int port =3564;
public static String server ="10.0.0.91";
public static String entityDN ="Mr.X";
public static String userName ="admin";
public static String password ="admin";
public static String filterSearch="(&(objectClass=entity)(uid=8097494899))";
/*the unique thing which needs to be passes*/
public static String msisdn ="8097494899";
public static SearchResult searchResult=null;
public static ArrayList<SearchResult> sr=null;
public static boolean isDone=false;
public static Attributes values; // Add up the values
public static ModificationItem[] mod; //Add up the Values its a serializable Object
public static void main(String[] args) throws UnknownHostException, NamingException {
System.out.println(":::::::::::::::::::::::::::::::::::::::::::::::::LDAP Bridging OPEN:::::::::::::::::::::::::::::::::::::::::::");
System.out.println("About to Open an LDAP connection on the custom port recieved as "+port);
//Connect
try{
ldap = new LDAPIntegrationModule(server, port, entityDN, userName, password);
System.out.println("Communication Successfully established with the LDAP Server");
}catch(Exception e){
throw new NamingException("Communication with the LDAP Server encountered failure");
}
//Search
System.out.println("About to Search an object with its details particular Entity/MSISDN "+msisdn);
searchResult=ldap.getEntityDetails(msisdn);
if(searchResult!=null){
System.out.println("Details pertinent to Entity/MSISDN "+searchResult.toString());
//Your Logic Here
}else{
try{
throw new Exception("Applied constraint or UID fetched no details,Check Connection.");
}catch(Exception e){
System.err.println("Exception while throwing error ..Yikes!");
}
}
//Search with a Filter
System.out.println("About to Search objects with a Filter"+filterSearch);
sr=ldap.getResultByCustomFilter(filterSearch);
if(sr!=null){
System.out.println("Details pertinent to Entity/MSISDN "+sr.toString());
//Your Logic Here
}else{
try{
throw new Exception("Applied filter fetched no details,Check Connection.");
}catch(Exception e){
System.err.println("Exception while throwing error ..Yikes!");
}
}
//Create Operation
System.out.println("About to add an entity to the Active Directory"+filterSearch);
isDone=ldap.addEntity(msisdn, values);
if(isDone){
System.out.println("Successful addition of entity to the Active Directory for "+msisdn);
//Your Logic here
//Notify a system or anything
}else{
System.err.println("Successful addition of entity to the Active Directory for "+msisdn);
}
//Update Operation
System.out.println("About to Update an entity to the Active Directory"+filterSearch);
isDone=ldap.updateEntity(msisdn, mod);
if(isDone){
System.out.println("Successful Modification of entity to the Active Directory for "+msisdn);
//Your Logic here
//Notify a system or anything
}else{
System.err.println("unSuccessful Modification of entity to the Active Directory for "+msisdn);
}
//Delete Operation
System.out.println("About to Delete an entity to the Active Directory"+msisdn);
isDone=ldap.deleteEntity(msisdn);
//You could check the connection before each operation as well.
if(ldap.isConnected()){
if(isDone){
System.out.println("Successful deletion of entity to the Active Directory for "+msisdn);
//Your Logic here
//Notify a system or anything
}else{
System.err.println("unSuccessful deletion of entity to the Active Directory for "+msisdn);
}
}
System.out.println("About to Close the LDAP connection");
System.out.println("::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::LDAP Bridging OPEN::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment