Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Creative commons Attribution-NonCommercial license. http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
  
  package base.ldap;
  
 import java.util.List;
 import java.util.Map;
 
Manages connecting to an LDAP server and executing basic LDAP commands. Querying the Centaur LDAP server:
 LdapHelper ldap = new LdapHelper("ldaps://centaur.unimelb.edu.au:636/", "uid=username,ou=people,o=myorg", "password", true);
 for(String item : ldap.find("ou=people,o=unimelb", "(&(objectclass=person)(uid=james*))")) {
     System.out.println(" - " + item);
 }
 
 
 public class LdapHelper {
 
 	private DirContext ctx;

Initialise an LdapHelper wrapper to a specific LDAP server

Parameters:
url JDBC url, ie ldaps://servername.com:689
username LDAP username
password LDAP password
trusting When true, SSL certificate validation should be bypassed.
 
 	public LdapHelper(String urlString usernameString passwordboolean trustingthrows NamingException {
 		Hashtable<StringStringenv = new Hashtable<>();
 		env.put(."com.sun.jndi.ldap.LdapCtxFactory");
 		env.put(.url);
 		env.put(.username);
 		env.put(.password);
 		if(trusting) {
 			env.put("java.naming.ldap.factory.socket""base.ssl.TrustingSslSocketFactory");
 		}
 
 		 = new InitialDirContext(env);
 	}

This method has been renamed, see getChildren()

Deprecated:
Deprecated in favour of getChildren()
Parameters:
dn
Returns:
Throws:
java.io.IOException
See also:
getChildren(java.lang.String)
 
 	public List<Stringlist(String dnthrows IOException {
 		return getChildren(dn);
 	}

Fetch the set of LDAP object sitting below this object in the ldap tree.

Parameters:
dn Full dn of the parent object
Returns:
List of full dn strings for each child object
Throws:
java.io.IOException
 
 	public List<StringgetChildren(String dnthrows IOException {
 		List<Stringnames = new ArrayList<>();
 		try {
 			items = .list(dn);
 			while(items.hasMore()) {
 				NameClassPair item = items.next();
				names.add(item.getName());
			}
catch (NamingException e) {
			throw new IOException(e);
		}
		return names;
	}
	public Map<StringStringgetAttributes(String dnthrows IOException {
		Map<StringStringattributes = new Hashtable<>();
		try {
			Attributes result = .getAttributes(dn);
			NamingEnumeration<? extends Attributeitems = result.getAll();
			while(items.hasMore()) {
				Attribute item = items.next();
				if(item.size() > 0) {
					String c = attributes.get(item.getID());
					for(int i = 0; i < item.size(); i++) {
						if(c == null) {
							c = "";
						}
						if(c.length() > 0) {
							c = c + "|";
						}
						try {
							c = c + item.get(i);
							Logger.getLogger(LdapHelper.class.getName()).log(."Ignoring LDAP attribute that cant be cast to String: " + item.getID(), e);
						}
					}
					attributes.put(item.getID(), c);
else {
					if(item.get() instanceof String) {
						attributes.put(item.getID(), (String)item.get());
					}
				}
			}
catch (NamingException e) {
			throw new IOException(e);
		}
		return attributes;
	}

Check if a DN exists on the ldap server.

Parameters:
dn Unique DN to check
Returns:
True if DN exists
Throws:
java.io.IOException
	public boolean exists(String dnthrows IOException {
		try {
			return true;
			return false;
catch (NamingException e) {
			throw new IOException(e);
		}
	}

Find the full unique DN of a person, where the username matches the cn field.

Parameters:
base DN containing the people we wish to search
username The value of the persons 'cn' attribute
Returns:
Unique DN of this person, or null if not found.
Throws:
java.io.IOException
	public String findPersonDN(String baseString usernamethrows IOException {
		try {
			NamingEnumeration<SearchResultanswer = .search(base"(&(objectclass=person)(cn="+username+"))"ctls);
			if (answer.hasMore()) {
				SearchResult sr = answer.next();
				answer.close();
				return sr.getNameInNamespace();
			}
			answer.close();
			..println("Warning: "+e.getMessage());
catch (NamingException e) {
			throw new IOException(e);
		}
		return null;
	}
	public String getGroupDN(String baseString groupthrows IOException {
		try {
			NamingEnumeration<SearchResultanswer = .search(base"(&(objectclass=group)(cn=*"+group+"*))"ctls);
			if (answer.hasMore()) {
				SearchResult sr = answer.next();
				answer.close();
				return sr.getNameInNamespace();
			}
			answer.close();
			..println("Warning: "+e.getMessage());
catch (NamingException e) {
			throw new IOException(e);
		}
		return null;
	}

Search the entire LDAP server using a filter

Parameters:
filter The search filter
Returns:
List of dn strings for each object that matches the filter
Throws:
java.io.IOException
	public List<Stringfind(String filterthrows IOException {
		List<Stringnames = new ArrayList<>();
		try {
			NamingEnumeration<SearchResultanswer = .search(""filterctls);
			while (answer.hasMore()) {
				SearchResult sr = answer.next();
			}
			answer.close();
catch (NamingException e) {
			throw new IOException(e);
		}
		return names;
	}

Search the entire LDAP server using a filter

Parameters:
baseDn The do a subtree search starting from this location
filter The search filter
Returns:
List of dn strings for each object that matches the filter
Throws:
java.io.IOException
	public List<Stringfind(String baseDnString filterthrows IOException {
		List<Stringnames = new ArrayList<>();
		try {
			NamingEnumeration<SearchResultanswer = .search(baseDnfilterctls);
			while (answer.hasMore()) {
				SearchResult sr = answer.next();
			}
			answer.close();
catch (NamingException e) {
			throw new IOException(e);
		}
		return names;
	}
	public void add(String dnString schemasMap<StringStringattributesthrows IOException {
		Attributes newAttributes = new BasicAttributes(true);
		Attribute oc = new BasicAttribute("objectclass");
		for(String oclass : schemas.split(",")) {
			oc.add(oclass);
		}
		newAttributes.put(oc);
		for(String attribute : attributes.keySet()) {
			newAttributes.put(new BasicAttribute(attributeattributes.get(attribute)));
		}
		try {
			.createSubcontext(dnnewAttributes);
catch (NamingException e) {
			throw new IOException(e);
		}
	}

Remove an entry from the LDAP server, including all associated attributes and children objects

Parameters:
dn The DN of the object being removed.
Throws:
java.io.IOException
	public void delete(String dnthrows IOException {
		try {
catch (NamingException e) {
			throw new IOException(e);
		}
	}
	public void addMemberToGroup(String userDnString groupDnthrows IOException {
		Attribute mod0 = new BasicAttribute("member"userDn);
		mods[0] = new ModificationItem(.mod0);
		try {
			.modifyAttributes(groupDnmods);
			throw new IOException(e);
catch (NamingException e) {
			throw new IOException(e);
		}
	}
	public void removeMemberFromGroup(String userDnString groupDnthrows IOException {
		Attribute mod0 = new BasicAttribute("member"userDn);
		try {
			.modifyAttributes(groupDnmods);
			throw new IOException(e);
catch (NamingException e) {
			throw new IOException(e);
		}
	}

Depreciated in favour of using the more generic getMultivalueAttribute() call. Use the following instead:
 ldap.getMultivalueAttribute(dn, "member");
 

Deprecated:
Deprecated in favour of using ldap.getMultivalueAttribute(dn, "member")
Parameters:
dn
Returns:
Throws:
java.io.IOException
	public List<StringgetGroupMembers(String dnthrows IOException {
		return getMultivalueAttribute(dn"member");
	}
	public List<StringgetMultivalueAttribute(String dnString attributethrows IOException {
		List<Stringmembers = new ArrayList<>();
		try {
			Attributes result = .getAttributes(dn);
			NamingEnumeration<? extends Attributeitems = result.getAll();
			while(items.hasMore()) {
				Attribute item = items.next();
				if(item.getID().equalsIgnoreCase(attribute)) {
					for(int i = 0; i < item.size(); i++) {
						members.add((String)item.get(i));
					}
				}
			}
catch (NamingException e) {
			throw new IOException(e);
		}
		return members;
	}
		List<Stringmembers = new ArrayList<>();
		try {
			Attributes result = .getAttributes(dn);
			NamingEnumeration<? extends Attributeitems = result.getAll();
			while(items.hasMore()) {
				Attribute item = items.next();
				if(item.getID().equalsIgnoreCase("memberOf")) {
					for(int i = 0; i < item.size(); i++) {
						members.add((String)item.get(i));
					}
				}
			}
catch (NamingException e) {
			throw new IOException(e);
		}
		return members;
	}
	public void modifyAttribute(String dnString attributeString valuethrows IOException {
		Attribute mod0 = new BasicAttribute(attributevalue);
		try {
			throw new IOException(e);
catch (NamingException e) {
			throw new IOException(e);
		}
	}
	public void addAttribute(String dnString attributeString valuethrows IOException {
		Attribute mod0 = new BasicAttribute(attributevalue);
		mods[0] = new ModificationItem(.mod0);
		try {
			throw new IOException(e);
catch (NamingException e) {
			throw new IOException(e);
		}
	}
	public void removeAttribute(String dnString attributethrows IOException {
		Attribute mod0 = new BasicAttribute(attributenull);
		try {
			throw new IOException(e);
catch (NamingException e) {
			throw new IOException(e);
		}
	}

Remove an individual value from a multi-value attribute.

Parameters:
dn
attribute
value
Throws:
java.io.IOException
	public void removeAttribute(String dnString attributeString valuethrows IOException {
		Attribute mod0 = new BasicAttribute(attributevalue);
		try {
			throw new IOException(e);
catch (NamingException e) {
			throw new IOException(e);
		}
	}
	public static String ldapEscape(String escape) {
		escape = escape.replaceAll("\\\\""\\\\\\\\");
		escape = escape.replaceAll(",""\\\\,");
		escape = escape.replaceAll("#""\\\\#");
		escape = escape.replaceAll("\\+""\\\\+");
		escape = escape.replaceAll("<""\\\\<");
		escape = escape.replaceAll(">""\\\\>");
		escape = escape.replaceAll(";""\\\\;");
		escape = escape.replaceAll("=""\\\\=");
		return escape;
	}
New to GrepCode? Check out our FAQ X