Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMore.

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//* w  w  w . j a  v  a 2 s  . co  m*/
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void lookupInContext(Context context, String prefix) {
    try {/*w w w  .j  a v  a  2s  . c o  m*/
        prefix += "/";
        NamingEnumeration<Binding> bindList = context.listBindings("");
        while (bindList.hasMore()) {
            Binding bind = bindList.next();
            if (bind != null) {
                if (bind.getObject() instanceof Context) {
                    lookupInContext((Context) bind.getObject(), prefix + bind.getName());
                }
                String[] binds = bind.getName().split("!");
                if (binds.length > 1) {
                    try {
                        jndiMapping.put(Class.forName(binds[1]), prefix + binds[0]);
                    } catch (Throwable ex) {
                        LOGGER.log(Level.WARNING,
                                "Class could not be found for EJB mapping: " + ex.getMessage());
                    }
                }
            }
        }
    } catch (Throwable ex) {
        LOGGER.log(Level.WARNING, "Bindings could not be found for EJB context: " + ex.getMessage());
    }
}

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.ja  va 2s. c o  m
 * @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) {
        }
    }
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void initJndiMapping() {
    try {//from  w ww  .ja va  2s. c o  m
        String lookupName = CONFIG.getContent().getEjbLookup();
        initialContext = new InitialContext();

        // For glassfish implementation
        NamingEnumeration<Binding> bindList = initialContext.listBindings("");
        while (bindList.hasMore()) {
            Binding bind = bindList.next();
            if (bind != null && ("java:" + lookupName).equals(bind.getName())
                    && bind.getObject() instanceof Context) {
                lookupInContext((Context) bind.getObject(), "java:" + lookupName);
            }
        }

        // For Jboss implementation
        if (jndiMapping.isEmpty()) {
            lookupInContext((Context) initialContext.lookup("java:" + lookupName), "java:" + lookupName);
        }
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "JNDI for EJB mapping could not be initialized: " + ex.getMessage());
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the values of the specified fields for the supplied id. 
 * @see IExternalStorage#getFields(java.lang.String, java.util.List)
 *///from   w w w . j a va2s .c om
public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException {
    Hashtable<String, Object> htReturn = new Hashtable<String, Object>();
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] saFields = fields.toArray(new String[0]);
        oScope.setReturningAttributes(saFields);

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes '");
            sbFailed.append(fields);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration neAttributes = oAttributes.getAll();
        while (neAttributes.hasMore()) {
            Attribute oAttribute = (Attribute) neAttributes.next();
            String sAttributeName = oAttribute.getID();

            if (oAttribute.size() > 1) {
                Vector<Object> vValue = new Vector<Object>();
                NamingEnumeration neAttribute = oAttribute.getAll();
                while (neAttribute.hasMore())
                    vValue.add(neAttribute.next());

                htReturn.put(sAttributeName, vValue);
            } else {
                Object oValue = oAttribute.get();
                if (oValue == null)
                    oValue = "";
                htReturn.put(sAttributeName, oValue);
            }
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields: " + fields, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return htReturn;
}

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

/**
 *
 * {@inheritDoc}//from w  ww  . j  a  va  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:ldap.ActiveLoginImpl.java

/**
 * Returns whether this user is listed in the admin users role
 *
 * @param login/*from   w  ww .ja va  2 s.  c  o m*/
 * @return
 * @throws Exception
 */
public boolean isAdmin(String login, DirContext context, String DN) throws Exception {
    NamingEnumeration result = null;

    String[] returnAttributes = new String[] { "uniqueMember" };

    /* specify search constraints to search subtree */
    SearchControls constraints = new SearchControls();

    constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);

    constraints.setReturningAttributes(returnAttributes);
    /*
            Entry user = null;
            try {
    user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context);
            } catch (NamingException e) {
               throw new LdapException("getUser NamingException" + e.getMessage(), e);
            }
       String DN = null;
            if (user == null) {
               logger.info("USER DOES NOT EXIST");
               return false;
            } else {
          DN = user.getName().toString();
               if (DN != null) {
      logger.info("DN = " + DN);
               }
       }
    */

    //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints);
    result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints);

    if (result.hasMore()) {
        if (debug) {
            SearchResult sResult = (SearchResult) result.next();
            logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString());
        }
        return true;
    } else if (debug)
        logger.info("Failed to find admin object with member " + DN);

    return false;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * @param searchFilter Username search filter.
 * @param returnedAtts Required attribute list of the user
 * @param dirContext LDAP connection context.
 * @return Search results for the given user.
 * @throws UserStoreException If an error occurs while searching.
 *///from   w  w  w  . j  a  v a2s. c o m
private NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE);
    if (returnedAtts[0].equals(CommonConstants.WILD_CARD_FILTER)) {
        returnedAtts = null;
    }
    searchCtls.setReturningAttributes(returnedAtts);

    if (log.isDebugEnabled()) {
        try {
            log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                    + dirContext.getNameInNamespace());
        } catch (NamingException e) {
            log.debug("Error while getting DN of search base", e);
        }
        if (returnedAtts == null) {
            log.debug("No attributes requested");
        } else {
            for (String attribute : returnedAtts) {
                log.debug("Requesting attribute :" + attribute);
            }
        }
    }

    String[] searchBaseAraay = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);
    NamingEnumeration<SearchResult> answer = null;

    try {
        for (String searchBase : searchBaseAraay) {
            answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
            if (answer.hasMore()) {
                return answer;
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while search user for filter : " + searchFilter;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while search user for filter : " + searchFilter;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return answer;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

@Override
public void doUpdateRoleListOfUser(String userName, String[] deletedRoles, String[] newRoles)
        throws UserStoreException {

    // get the DN of the user entry
    String userNameDN = this.getNameInSpaceForUserName(userName);
    String membershipAttribute = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
    /*/*from   www . j  a  v  a  2s.  c  o  m*/
     * check deleted roles and delete member entries from relevant groups.
     */
    String errorMessage = null;
    String roleSearchFilter = null;

    DirContext mainDirContext = this.connectionSource.getContext();

    try {
        if (deletedRoles != null && deletedRoles.length != 0) {
            // perform validation for empty role occurrences before
            // updating in LDAP
            // check whether this is shared roles and where shared roles are
            // enable

            for (String deletedRole : deletedRoles) {
                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);
                roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                String[] returningAttributes = new String[] { membershipAttribute };
                String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
                NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                        returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                SearchResult resultedGroup = null;
                if (groupResults.hasMore()) {
                    resultedGroup = groupResults.next();
                }
                if (resultedGroup != null && isOnlyUserInRole(userNameDN, resultedGroup)
                        && !emptyRolesAllowed) {
                    errorMessage = userName + " is the only user in the role: " + deletedRole
                            + ". Hence can not delete user from role.";
                    throw new UserStoreException(errorMessage);
                }

                JNDIUtil.closeNamingEnumeration(groupResults);
            }
            // if empty role violation does not happen, continue
            // updating the LDAP.
            for (String deletedRole : deletedRoles) {

                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);

                if (doCheckExistingRole(deletedRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(deletedRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    modifyUserInRole(userNameDN, groupDN, DirContext.REMOVE_ATTRIBUTE, searchBase);
                    JNDIUtil.closeNamingEnumeration(groupResults);
                } else {
                    errorMessage = "The role: " + deletedRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }
        if (newRoles != null && newRoles.length != 0) {

            for (String newRole : newRoles) {
                String searchFilter = userStoreProperties.get(LDAPConstants.ROLE_NAME_FILTER);

                if (doCheckExistingRole(newRole)) {
                    roleSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(newRole));
                    String[] returningAttributes = new String[] { membershipAttribute };
                    String searchBase = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);

                    NamingEnumeration<SearchResult> groupResults = searchInGroupBase(roleSearchFilter,
                            returningAttributes, SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                    SearchResult resultedGroup = null;
                    // assume only one group with given group name
                    String groupDN = null;
                    if (groupResults.hasMore()) {
                        resultedGroup = groupResults.next();
                        groupDN = resultedGroup.getName();
                    }
                    if (resultedGroup != null && !isUserInRole(userNameDN, resultedGroup)) {
                        modifyUserInRole(userNameDN, groupDN, DirContext.ADD_ATTRIBUTE, searchBase);
                    } else {
                        errorMessage = "User: " + userName + " already belongs to role: " + groupDN;
                        throw new UserStoreException(errorMessage);
                    }

                    JNDIUtil.closeNamingEnumeration(groupResults);

                } else {
                    errorMessage = "The role: " + newRole + " does not exist.";
                    throw new UserStoreException(errorMessage);
                }
            }
        }

    } catch (NamingException e) {
        errorMessage = "Error occurred while modifying the role list of user: " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(mainDirContext);
    }
}

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);
    }//w  ww  .  j  a  v a 2 s.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);
}