Example usage for javax.naming.directory SearchControls setSearchScope

List of usage examples for javax.naming.directory SearchControls setSearchScope

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls setSearchScope.

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query) {
    LOGGER.debug("Building group searcher for query {}", query);

    final SearchControls groupSearchCtls = new SearchControls();
    groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst());
    // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
    groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);

    return (ctx) -> {
        try {/*  w w  w  .  j  a  va  2  s  .c o  m*/
            final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query,
                    groupSearchCtls);
            return results;
        } catch (final NamingException e) {
            throw new AlfrescoRuntimeException("Failed to import groups.", e);
        }
    };
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args/*from w  w w  . ja  v a  2 s.co  m*/
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*w  ww . j  a va 2  s.co  m*/
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws AlfrescoRuntimeException
 */
protected void processQuery(final SearchCallback callback, final String searchBase, final String query,
        final String[] returningAttributes) {
    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Processing query {}\nSearch base: {}\n\rReturn result limit: {}\n\tDereflink: {}\n\rReturn named object: {}\n\tTime limit for search: {}\n\tAttributes to return: {} items\n\tAttributes: {}",
                query, searchBase, searchControls.getCountLimit(), searchControls.getDerefLinkFlag(),
                searchControls.getReturningObjFlag(), searchControls.getTimeLimit(),
                String.valueOf(returningAttributes.length), Arrays.toString(returningAttributes));
    }

    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                this.commonCloseSearchResult(result);
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (final NamingException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (final ParseException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 *
 * {@inheritDoc}/* w  w w.ja v  a  2 s .c  o m*/
 */
@Override
public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    LOGGER.debug("resolveDistinguishedName userId: {}", userId);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            final Attributes attributes = result.getAttributes();
            final Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LOGGER.warn("User returned by user search does not have mandatory user id attribute {}",
                            attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                final String name = result.getNameInNamespace();

                this.commonCloseSearchResult(result);
                result = null;
                return name;
            }

            this.commonCloseSearchResult(result);
            result = null;
        }

        final Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (final NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory
        final Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        final Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*from w  w  w .  ja  v a2 s  . c  o  m*/
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws org.alfresco.error.AlfrescoRuntimeException
 */
private void processQuery(SearchCallback callback, String searchBase, String query,
        String[] returningAttributes) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);
    if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
        LDAPMultiBaseUserRegistry.logger.debug("Processing query");
        LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPMultiBaseUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPMultiBaseUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPMultiBaseUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPMultiBaseUserRegistry.logger.debug("        Attribute: " + ra);
        }
    }
    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                // Close the contexts, see ALF-20682
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (NamingException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (ParseException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        if (result != null) {
            try {
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }//from  w  w  w.  jav  a2s. co  m
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    InitialDirContext ctx = null;

    for (String userSearchBase : this.userSearchBases) {

        String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))";

        NamingEnumeration<SearchResult> searchResults = null;
        SearchResult result = null;

        try {
            ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

            // Execute the user query with an additional condition that ensures only the user with the required ID is
            // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

            searchResults = ctx.search(userSearchBase,
                    "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))",
                    new Object[] { userId }, userSearchCtls);

            if (searchResults.hasMore()) {
                result = searchResults.next();
                Attributes attributes = result.getAttributes();
                Attribute uidAttribute = attributes.get(this.userIdAttributeName);
                if (uidAttribute == null) {
                    if (this.errorOnMissingUID) {
                        throw new AlfrescoRuntimeException(
                                "User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    } else {
                        LDAPMultiBaseUserRegistry.logger
                                .warn("User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    }
                }
                // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
                // only resolve this user if the user ID matches
                else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                    String name = result.getNameInNamespace();

                    // Close the contexts, see ALF-20682
                    Context context = (Context) result.getObject();
                    if (context != null) {
                        context.close();
                    }
                    result = null;
                    return name;
                }

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
            }
        } catch (NamingException e) {
            // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

            Object[] args1 = { userId, query };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);
        }

        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
    }

    if (ctx != null) {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.debug("error when closing ldap context", e);
        }
    }

    // failed to search
    //        Object[] args = {e.getLocalizedMessage()};
    throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic);
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * /*w ww  .j ava 2  s.  c  o m*/
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * {@inheritDoc}//  w ww.j  ava2 s.c  om
 */
public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException {
    Map<String, String> idNameMap = new LinkedHashMap<String, String>();
    String text = censorHumanoidSearchPhrase(stub);
    String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))";
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(maxCount);
    ctls.setReturningAttributes(new String[] { "cn", "uid" });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get());
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }
    return idNameMap;
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/*from   w  w w .  j a va 2 s.  c  om*/
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation            

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            Attributes attributes = result.getAttributes();
            Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LDAPUserRegistry.logger
                            .warn("User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                String name = result.getNameInNamespace();

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
                return name;
            }

            // Close the contexts, see ALF-20682
            Context context = (Context) result.getObject();
            if (context != null) {
                context.close();
            }
            result = null;
        }

        Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

        Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                logger.debug("error when closing ldap context", e);
            }
        }
    }
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 * //from w  w w.  jav  a  2s.c  om
 * @param callback
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws AlfrescoRuntimeException           
 */
private void processQuery(SearchCallback callback, String searchBase, String query,
        String[] returningAttributes) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);
    if (LDAPUserRegistry.logger.isDebugEnabled()) {
        LDAPUserRegistry.logger.debug("Processing query");
        LDAPUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPUserRegistry.logger.debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPUserRegistry.logger.debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPUserRegistry.logger.debug("        Attribute: " + ra);
        }
    }
    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                // Close the contexts, see ALF-20682
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (NamingException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (ParseException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        if (result != null) {
            try {
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
            searchResults = null;
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
        try {
            callback.close();
        } catch (NamingException e) {
        }
    }
}