Oracle JNDI LDAP Connection Test

If you want to test your ldap connection you may use this code. Please keep in mind when you create the project add Spring necessary jars as well as spring ldap and sun-jndi-ldapbp.jar

package springframeworkldapclient;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class LdapContextCreation {

    public static void main(String[] args) {
        LdapContextCreation ldapContxCrtn = new LdapContextCreation();
        LdapContext ctx = ldapContxCrtn.getLdapContext();
    }

    public LdapContext getLdapContext() {
        LdapContext ctx = null;
        try {
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.SECURITY_AUTHENTICATION, "Simple");
            env.put(Context.SECURITY_PRINCIPAL, "USERNAME");
            env.put(Context.SECURITY_CREDENTIALS, "PASSWORD");
            env.put(Context.PROVIDER_URL, "ldap://localhost:389");
            ctx = new InitialLdapContext(env, null);
            System.out.println("Connection Successful.");
        } catch (NamingException ex) {
            System.out.println("LDAP Connection: FAILED");
            System.out.println("Could not connect: " + ex);
        }
        return ctx;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *