Example usage for javax.naming.ldap InitialLdapContext InitialLdapContext

List of usage examples for javax.naming.ldap InitialLdapContext InitialLdapContext

Introduction

In this page you can find the example usage for javax.naming.ldap InitialLdapContext InitialLdapContext.

Prototype

@SuppressWarnings("unchecked")
public InitialLdapContext(Hashtable<?, ?> environment, Control[] connCtls) throws NamingException 

Source Link

Document

Constructs an initial context using environment properties and connection request controls.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String url = "ldap://localhost/o=JNDITutorial";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "userDN");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    // Create connection controls to use
    Control[] connectCtls = new Control[] { null };

    LdapContext ctx = new InitialLdapContext(env, connectCtls);
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String url = "ldap://localhost/o=JNDITutorial";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "userDN");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    LdapContext ctx = new InitialLdapContext(env, null);

    NamingEnumeration answer = ctx.search("ou=People", "(cn=*)", null);

    System.out.println(ctx.getResponseControls());

    while (answer.hasMore()) {
        SearchResult si = (SearchResult) answer.next();
        if (si instanceof HasControls) {
            System.out.println(((HasControls) si).getControls());
        }/*from   w w  w  . java2 s  .  c  o m*/
    }
    System.out.println(ctx.getResponseControls());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String url = "ldap://localhost/o=JNDITutorial";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "userDN");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    Control[] connectCtls = new Control[] { null };
    LdapContext ctx = new InitialLdapContext(env, null);

    Control[] ctxCtls = new Control[] { new SortControl(new String[] { "cn" }, Control.CRITICAL) };

    ctx.setRequestControls(ctxCtls);/*  www  .  ja  va  2s  .  c  om*/

    NamingEnumeration answer = ctx.list("");

    while (answer.hasMore()) {
        NameClassPair item = (NameClassPair) answer.next();
    }
}

From source file:ManageReferral.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:489/o=JNDITutorial");
    // env.put(Context.REFERRAL, "follow");
    env.put(Context.REFERRAL, "ignore");

    try {/*ww w .  j a  va  2  s.  co  m*/
        // Create initial context
        LdapContext ctx = (LdapContext) new InitialLdapContext(env, null);
        // ctx.setRequestControls(new Control[] {
        // new ManageReferralControl() });

        // Set controls for performing subtree search
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Perform search
        NamingEnumeration answer = ctx.search("", "(objectclass=*)", ctls);

        // Print the answer
        while (answer.hasMore()) {
            System.out.println(">>>" + ((SearchResult) answer.next()).getName());
        }

        // Close the context when we're done
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:PagedSearch.java

public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {// w ww  .  j a v  a2s .  com
        LdapContext ctx = new InitialLdapContext(env, null);

        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;

        do {
            /* perform the search */
            NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult entry = (SearchResult) results.next();
                System.out.println(entry.getName());
            }

            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            System.out.println("(total : " + total);
                        } else {
                            System.out.println("(total: unknown)");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                System.out.println("No controls were sent from the server");
            }
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);

        ctx.close();

    } catch (NamingException e) {
        System.err.println("PagedSearch failed.");
        e.printStackTrace();
    } catch (IOException ie) {
        System.err.println("PagedSearch failed.");
        ie.printStackTrace();
    }
}

From source file:PagedSearch.java

public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {// w w w .  ja  v a  2s  . co m
        LdapContext ctx = new InitialLdapContext(env, null);

        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;

        do {
            /* perform the search */
            NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult entry = (SearchResult) results.next();
                System.out.println(entry.getName());
            }

            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            System.out.println("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            System.out.println(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                System.out.println("No controls were sent from the server");
            }
            // Re-activate paged results
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);

        ctx.close();

    } catch (NamingException e) {
        System.err.println("PagedSearch failed.");
        e.printStackTrace();
    } catch (IOException ie) {
        System.err.println("PagedSearch failed.");
        ie.printStackTrace();
    }
}

From source file:SortedResults.java

public static void main(String[] args) throws IOException {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {/* w  w w  .  j ava  2 s  . c  o m*/
        // Create initial context with no connection request controls
        LdapContext ctx = new InitialLdapContext(env, null);

        // Create a sort control that sorts based on CN
        String sortKey = "cn";
        ctx.setRequestControls(new Control[] { new SortControl(sortKey, Control.CRITICAL) });

        // Perform a search
        NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

        // Iterate over search results
        System.out.println("---->sort by cn");
        while (results != null && results.hasMore()) {
            // Display an entry
            SearchResult entry = (SearchResult) results.next();
            System.out.println(entry.getName());

            // Handle the entry's response controls (if any)
            if (entry instanceof HasControls) {
                // ((HasControls)entry).getControls();
            }
        }
        // Examine the sort control response
        Control[] controls = ctx.getResponseControls();
        if (controls != null) {
            for (int i = 0; i < controls.length; i++) {
                if (controls[i] instanceof SortResponseControl) {
                    SortResponseControl src = (SortResponseControl) controls[i];
                    if (!src.isSorted()) {
                        throw src.getException();
                    }
                } else {
                    // Handle other response controls (if any)
                }
            }
        }

        // Close when no longer needed
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:org.web4thejob.security.ADAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (authentication.getName() == null || (String) authentication.getCredentials() == null) {
        throw new BadCredentialsException("");
    }//from   ww w .  ja v  a 2 s . c  om

    String principal = getPrincipal(authentication.getName());
    String passwd = (String) authentication.getCredentials();

    LdapContext ctx = null;
    try {
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getCanonicalName());
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
        env.put(Context.PROVIDER_URL, url);
        ctx = new InitialLdapContext(env, null);
        //LDAP Connection Successful

        UserDetails userDetails = userDetailsService.loadUserByUsername(principal);
        return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
    } catch (NamingException nex) {
        throw new BadCredentialsException("LDAP authentication failed.", nex);
    } catch (UsernameNotFoundException e) {
        throw new BadCredentialsException("UserDetails did not find a valid user for name: " + principal, e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:com.marklogic.samplestack.integration.web.LDAPIT.java

@Before
public void setup() throws NamingException {
    env = new Hashtable<String, Object>();
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    if (ldapUsername != null) {
        env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
    }//from www  .j a  va  2 s . c  o m
    if (ldapPassword != null) {
        env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapServer);

    // ensures that objectSID attribute values
    // will be returned as a byte[] instead of a String
    // env.put("java.naming.ldap.attributes.binary", "uid");

    // the following is helpful in debugging errors
    //env.put("com.sun.jndi.ldap.trace.ber", System.err);

    ctx = new InitialLdapContext(env, null);

}

From source file:com.constellio.model.services.users.sync.FastBindConnectionControl.java

@SuppressWarnings("unchecked")
public LDAPFastBind(String ldapurl, Boolean followReferences, boolean activeDirectory) {
    env = new Hashtable();
    //This can make LDAP search slow : http://stackoverflow.com/questions/16412236/how-to-resolve-javax-naming-partialresultexception
    //env.put(Context.REFERRAL, "follow");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.PROVIDER_URL, ldapurl);
    env.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
    if (followReferences) {
        env.put(Context.REFERRAL, "follow");
    }/*from ww w  .  j a v a 2 s  . c  om*/

    if (StringUtils.startsWith(ldapurl, "ldaps")) {
        //env.put(Context.SECURITY_PROTOCOL, "ssl");
        env.put("java.naming.ldap.factory.socket",
                "com.constellio.model.services.users.sync.ldaps.DummySSLSocketFactory");
    }

    if (activeDirectory) {
        connCtls = new Control[] { new FastBindConnectionControl() };
    } else {
        connCtls = new Control[] {};
    }

    //first time we initialize the context, no credentials are supplied
    //therefore it is an anonymous bind.      

    /*try {
       ctx = new InitialLdapContext(env, connCtls);
            
    } catch (NamingException e) {
       throw new RuntimeNamingException(e.getMessage());
    }*/
    //FIX de Vincent pour o a q
    try {
        ctx = new InitialLdapContext(env, connCtls);
    } catch (NamingException e) {
        if (activeDirectory) {
            connCtls = new Control[] {};
            try {
                ctx = new InitialLdapContext(env, connCtls);
            } catch (NamingException e2) {
                throw new RuntimeException(e);
            }
        } else {
            throw new RuntimeException(e);
        }
    }
}