Created
December 12, 2014 09:58
-
-
Save bbuecherl/9431c03c71e5780fb328 to your computer and use it in GitHub Desktop.
Simple LDAP Connection-Class for java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Properties; | |
import javax.naming.Context; | |
import javax.naming.NamingEnumeration; | |
import javax.naming.NamingException; | |
import javax.naming.directory.Attributes; | |
import javax.naming.directory.InitialDirContext; | |
import javax.naming.directory.SearchControls; | |
import javax.naming.directory.SearchResult; | |
public class LDAP { | |
private static final String CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; | |
private InitialDirContext ctx; | |
private String basedn; | |
private SearchControls ctrls; | |
private LDAP(String url, String user, String password, String b) throws NamingException { | |
ctx = LDAP.doConnect(url, user, password); | |
basedn = b.length() > 0 ? "," + b : b; | |
ctrls = new SearchControls(); | |
} | |
public ArrayList<Attributes> search(String base, String filter) throws NamingException { | |
NamingEnumeration<SearchResult> ne = ctx.search(base + basedn, filter, ctrls); | |
ArrayList<Attributes> arr = new ArrayList<>(); | |
while(ne.hasMore()) { | |
arr.add(ne.next().getAttributes()); | |
} | |
return arr; | |
} | |
public Attributes get(String base) throws NamingException { | |
return ctx.getAttributes(base + basedn); | |
} | |
private static InitialDirContext doConnect(String url, String user, String password) throws NamingException { | |
Properties props = new Properties(); | |
props.put(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY); | |
props.put(Context.PROVIDER_URL, url); | |
props.put(Context.SECURITY_PRINCIPAL, user); | |
props.put(Context.SECURITY_CREDENTIALS, password); | |
return new InitialDirContext(props); | |
} | |
public static LDAP connect(String url, String user, String pass, String basedn) throws NamingException { | |
return new LDAP(url, user, pass, basedn); | |
} | |
public static boolean testConnection(String url, String user, String password) { | |
try { | |
return LDAP.doConnect(url, user, password) != null; | |
} catch (Exception e) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment