Example usage for javax.naming.ldap LdapContext close

List of usage examples for javax.naming.ldap LdapContext close

Introduction

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

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this context.

Usage

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 {//from  w  w w  .  j av a2s. c o  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: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 .ja  va 2s  .  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: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 {//from   w  ww .  j  a  va 2s  .  c  om
        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 {//from   ww w  .  ja  v  a2s  .  c  om
        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:org.apache.cloudstack.ldap.LdapManagerImpl.java

private void closeContext(final LdapContext context) {
    try {
        if (context != null) {
            context.close();//from www. java 2 s  . c om
        }
    } catch (final NamingException e) {
        s_logger.warn(e.getMessage(), e);
    }
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Returns <i>true</i> if the Active Directory account and password are
 * valid (e.g. a context can be successfully established) or <i>false</i>
 * otherwise./*  w ww.j  a  v  a  2  s . c  o  m*/
 *
 * @param anAccountName An Active Directory account name.
 * @param anAccountPassword An Active Directory account passowrd.
 *
 * @return <i>true</i> or <i>false</i>
 */
@SuppressWarnings("unchecked")
public boolean isAccountValid(String anAccountName, String anAccountPassword) {
    boolean isValid = false;
    Logger appLogger = mAppMgr.getLogger(this, "isAccountValid");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    DataBag userBag = schemaUserBag();
    userBag.setValueByName(LDAP_ACCOUNT_NAME, anAccountName);

    try {
        loadUserByAccountName(userBag);
        Hashtable<String, String> environmentalVariables = new Hashtable<String, String>();
        environmentalVariables.put("com.sun.jndi.ldap.connect.pool", StrUtl.STRING_TRUE);
        environmentalVariables.put(Context.PROVIDER_URL, getPropertyValue("domain_url", null));
        environmentalVariables.put("java.naming.ldap.attributes.binary", "tokenGroups objectSid");
        environmentalVariables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        environmentalVariables.put(Context.SECURITY_PRINCIPAL,
                userBag.getValueAsString(LDAP_DISTINGUISHED_NAME));
        environmentalVariables.put(Context.SECURITY_CREDENTIALS, anAccountPassword);
        environmentalVariables.put(Context.REFERRAL, getPropertyValue("referral_handling", "ignore"));
        environmentalVariables.put(Context.SECURITY_AUTHENTICATION,
                getPropertyValue("authentication", "simple"));

        LdapContext ldapContext = new InitialLdapContext(environmentalVariables, null);
        ldapContext.close();

        isValid = true;
    } catch (Exception ignored) {
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return isValid;
}

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("");
    }// ww  w .j  a va  2s.  c  o  m

    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:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will rename the supplied dn in the LDAP namespace. See {@link
 * javax.naming.Context#rename(String, String)}.
 *
 * @param  oldDn  <code>String</code> object to rename
 * @param  newDn  <code>String</code> new name
 *
 * @throws  NamingException  if the LDAP returns an error
 *///w ww .j av a 2  s. c  om
protected void rename(final String oldDn, final String newDn) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Rename name with the following parameters:");
        this.logger.debug("  oldDn = " + oldDn);
        this.logger.debug("  newDn = " + newDn);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                ctx.rename(oldDn, newDn);
                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will delete the supplied dn from the LDAP namespace. Note that this
 * method does not throw NameNotFoundException if the supplied dn does not
 * exist. See {@link javax.naming.Context#destroySubcontext(String)}.
 *
 * @param  dn  <code>String</code> named object in the LDAP
 *
 * @throws  NamingException  if the LDAP returns an error
 *///  w  w  w. j av a2  s . c  om
protected void delete(final String dn) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Delete name with the following parameters:");
        this.logger.debug("  dn = " + dn);
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                ctx.destroySubcontext(dn);
                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will modify the supplied dn using the supplied modifications. The
 * modifications are performed in the order specified. Each modification
 * specifies a modification operation code and an attribute on which to
 * operate. Where possible, the modifications are performed atomically. See
 * {@link javax.naming.DirContext#modifyAttributes(String,
 * ModificationItem[])}.//from www.  j a v  a 2  s  .co m
 *
 * @param  dn  <code>String</code> named object in the LDAP
 * @param  mods  <code>ModificationItem[]</code> modifications
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected void modifyAttributes(final String dn, final ModificationItem[] mods) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Modify attributes with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  mods = " + Arrays.toString(mods));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    LdapContext ctx = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                ctx = this.getContext();
                ctx.modifyAttributes(dn, mods);
                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            }
        }
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
}