Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

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

Introduction

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

Prototype

int SUBTREE_SCOPE

To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@Override
public void doDeleteUserClaimValues(String userName, String[] claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    try {//from w  ww  .  j  ava2 s  .co  m

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI

        for (String claimURI : claims) {
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            updatedAttributes.put(currentUpdatedAttribute);
        }

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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  .  j av a2  s  . com*/
 * @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:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * @param searchFilter//from   w  w  w.  ja va2s  .  c o  m
 * @param returnedAtts
 * @param dirContext
 * @return
 * @throws UserStoreException
 */
protected NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    if (returnedAtts != null && returnedAtts.length > 0) {
        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("#");
    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:com.aurel.track.util.LdapUtil.java

static TPersonBean getLdapUser(String providerUrl, String bindDN, String bindPassword,
        String loginAttributeName, String searchStr) throws Exception {
    LdapContext ctx = null;/*from  w  ww.j  ava  2  s. co m*/
    try {
        ctx = getInitialContext(providerUrl, bindDN, bindPassword);
        if (ctx == null) {
            LOGGER.warn("The context is null");
        }
        // Control the search
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Don't ask for more than we can handle anyways
        if (ldapMap == null || ldapMap.isEmpty()) {
            LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
            return null;
        }
        String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
        String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
        String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
        String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
        NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
        /* for each entry print out name + all attrs and values */
        while (results != null && results.hasMore()) {
            SearchResult sr = (SearchResult) results.next();
            return getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName,
                    emailAttributeName, phoneAttributName);
        }
    } catch (NamingException e) {
        LOGGER.warn(
                "Searching from " + providerUrl + " by filter " + searchStr + " failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } finally {
        if (ctx != null) {
            ctx.close();
        }
    }
    return null;
}

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

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*w  ww  .  j  a  va2s .  c  om*/
 *            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:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

protected void addLDAPRole(RoleContext context) throws UserStoreException {

    String roleName = context.getRoleName();
    String[] userList = context.getMembers();
    String groupEntryObjectClass = ((LDAPRoleContext) context).getGroupEntryObjectClass();
    String groupNameAttribute = ((LDAPRoleContext) context).getRoleNameProperty();
    String searchBase = ((LDAPRoleContext) context).getSearchBase();

    if ((userList == null || userList.length == 0) && !emptyRolesAllowed) {
        String errorMessage = "Can not create empty role. There should be at least " + "one user for the role.";
        throw new UserStoreException(errorMessage);
    } else if (userList == null && emptyRolesAllowed
            || userList != null && userList.length > 0 && !emptyRolesAllowed || emptyRolesAllowed) {

        // if (userList.length > 0) {
        DirContext mainDirContext = this.connectionSource.getContext();
        DirContext groupContext = null;
        NamingEnumeration<SearchResult> results = null;

        try {/*from ww  w. j av a  2s  . c o m*/
            // create the attribute set for group entry
            Attributes groupAttributes = new BasicAttributes(true);

            // create group entry's object class attribute
            Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
            objectClassAttribute.add(groupEntryObjectClass);
            groupAttributes.put(objectClassAttribute);

            // create cn attribute
            Attribute cnAttribute = new BasicAttribute(groupNameAttribute);
            cnAttribute.add(roleName);
            groupAttributes.put(cnAttribute);
            // following check is for if emptyRolesAllowed made this
            // code executed.
            if (userList != null && userList.length > 0) {

                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                Attribute memberAttribute = new BasicAttribute(memberAttributeName);
                for (String userName : userList) {

                    if (userName == null || userName.trim().length() == 0) {
                        continue;
                    }
                    // search the user in user search base
                    String searchFilter = realmConfig
                            .getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
                    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
                    results = searchInUserBase(searchFilter, new String[] {}, SearchControls.SUBTREE_SCOPE,
                            mainDirContext);
                    // we assume only one user with the given user
                    // name under user search base.
                    SearchResult userResult = null;
                    if (results.hasMore()) {
                        userResult = results.next();
                    } else {
                        String errorMsg = "There is no user with the user name: " + userName
                                + " to be added to this role.";
                        logger.error(errorMsg);
                        throw new UserStoreException(errorMsg);
                    }
                    // get his DN
                    String userEntryDN = userResult.getNameInNamespace();
                    // put it as member-attribute value
                    memberAttribute.add(userEntryDN);
                }
                groupAttributes.put(memberAttribute);
            }

            groupContext = (DirContext) mainDirContext.lookup(searchBase);
            NameParser ldapParser = groupContext.getNameParser("");
            /*
             * Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" +
             * roleName);
             */
            Name compoundGroupName = ldapParser.parse("cn=" + roleName);
            groupContext.bind(compoundGroupName, null, groupAttributes);

        } catch (NamingException e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } catch (Exception e) {
            String errorMsg = "Role: " + roleName + " could not be added.";
            if (log.isDebugEnabled()) {
                log.debug(errorMsg, e);
            }
            throw new UserStoreException(errorMsg, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(results);
            JNDIUtil.closeContext(groupContext);
            JNDIUtil.closeContext(mainDirContext);
        }

    }

}

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

/**
 * Returns the list of role names for the given search base and other
 * parameters./*ww  w .  j a  v  a 2  s  .  co m*/
 * @param searchTime Maximum search time
 * @param filter Filter for searching role names
 * @param maxItemLimit Maximum number of roles required
 * @param searchFilter Group name search filter
 * @param roleNameProperty Attribute name of the group in LDAP user store.
 * @param searchBase Group search base.
 * @return The list of roles in the given search base.
 * @throws UserStoreException If an error occurs while retrieving the required information.
 */
private List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter,
        String roleNameProperty, String searchBase) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> roles = new ArrayList<>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);
    searchCtls.setTimeLimit(searchTime);

    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    StringBuilder finalFilter = new StringBuilder();
    finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=")
            .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");

    if (debug) {
        log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString());
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;

    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);

        while (answer.hasMoreElements()) {
            SearchResult sr = answer.next();
            if (sr.getAttributes() != null) {
                Attribute attr = sr.getAttributes().get(roleNameProperty);
                if (attr != null) {
                    String name = (String) attr.get();
                    roles.add(name);
                }
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase
                + " ConstructedFilter: " + finalFilter.toString();
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase
                + " ConstructedFilter: " + finalFilter.toString();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

    if (debug) {
        for (String role : roles) {
            log.debug("result: " + role);
        }
    }

    return roles;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the LDAP users//  w w  w.j  av  a  2s  . co m
 * 
 * @param ctx
 * @param loginAttributeName
 * @param searchStrs
 * @return
 */
static List<TPersonBean> getLdapUsers(LdapContext ctx, String loginAttributeName, List<String> searchStrs) {
    List<TPersonBean> personBeans = new LinkedList<TPersonBean>();
    if (ldapMap == null || ldapMap.isEmpty()) {
        LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
        return personBeans;
    }
    String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
    String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
    String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
    String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
    for (String searchStr : searchStrs) {
        LOGGER.debug("Searching by filter " + searchStr);
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try {
            NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    LOGGER.debug("Search successful " + searchStr);
                    personBeans.add(personBean);
                }
            }
        } catch (NamingException e) {
            LOGGER.warn("Search failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return personBeans;
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * Returns the list of role names for the given search base and other
 * parameters//from ww w  . j av a  2  s .c  o m
 *
 * @param searchTime
 * @param filter
 * @param maxItemLimit
 * @param searchFilter
 * @param roleNameProperty
 * @param searchBase
 * @param appendTenantDomain
 * @return
 * @throws UserStoreException
 */
protected List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter,
        String roleNameProperty, String searchBase, boolean appendTenantDomain) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> roles = new ArrayList<String>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);
    searchCtls.setTimeLimit(searchTime);

    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    // / search filter TODO
    StringBuffer finalFilter = new StringBuffer();
    finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=")
            .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");

    if (debug) {
        log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString());
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;

    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);
        // append the domain if exist
        String domain = this.getRealmConfiguration()
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            if (sr.getAttributes() != null) {
                Attribute attr = sr.getAttributes().get(roleNameProperty);
                if (attr != null) {
                    String name = (String) attr.get();
                    name = UserCoreUtil.addDomainToName(name, domain);
                    if (appendTenantDomain) {
                        String dn = sr.getNameInNamespace();
                        name = UserCoreUtil.addTenantDomainToEntry(name, getTenantDomainFromRoleDN(dn, name));
                    }
                    roles.add(name);
                }
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase
                + " ConstructedFilter: " + finalFilter.toString();
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase
                + " ConstructedFilter: " + finalFilter.toString();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

    if (debug) {
        Iterator<String> rolesIte = roles.iterator();
        while (rolesIte.hasNext()) {
            log.debug("result: " + rolesIte.next());
        }
    }

    return roles;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

/**
 * Performs the specified operation and returns the results.
 *  //from  w w w.  j a va2 s. c o m
 * @return - Depending on operation, DEFAULT_RESULT or read/search result (always XML)
 */
public String performOperation(String message, ParameterResolutionContext prc)
        throws SenderException, ParameterException {
    Map paramValueMap = null;
    String entryName = null;
    if (paramList != null && prc != null) {
        paramValueMap = prc.getValueMap(paramList);
        entryName = (String) paramValueMap.get("entryName");
        if (log.isDebugEnabled())
            log.debug("entryName=[" + entryName + "]");
    }
    if ((entryName == null || StringUtils.isEmpty(entryName)) && !getOperation().equals(OPERATION_CHALLENGE)) {
        throw new SenderException(
                "entryName must be defined through params, operation [" + getOperation() + "]");
    }
    if (getOperation().equals(OPERATION_READ)) {
        return performOperationRead(entryName, prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_UPDATE)) {
        return performOperationUpdate(entryName, prc, paramValueMap, parseAttributesFromMessage(message));
    } else if (getOperation().equals(OPERATION_CREATE)) {
        return performOperationCreate(entryName, prc, paramValueMap, parseAttributesFromMessage(message));
    } else if (getOperation().equals(OPERATION_DELETE)) {
        return performOperationDelete(entryName, prc, paramValueMap, parseAttributesFromMessage(message));
    } else if (getOperation().equals(OPERATION_SEARCH)) {
        return performOperationSearch(entryName, prc, paramValueMap, (String) paramValueMap.get(FILTER),
                SearchControls.ONELEVEL_SCOPE);
    } else if (getOperation().equals(OPERATION_DEEP_SEARCH)) {
        return performOperationSearch(entryName, prc, paramValueMap, (String) paramValueMap.get(FILTER),
                SearchControls.SUBTREE_SCOPE);
    } else if (getOperation().equals(OPERATION_SUB_CONTEXTS)) {
        return performOperationGetSubContexts(entryName, prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_GET_TREE)) {
        return performOperationGetTree(entryName, prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_CHALLENGE)) {
        return performOperationChallenge((String) paramValueMap.get("principal"), prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_CHANGE_UNICODE_PWD)) {
        return performOperationChangeUnicodePwd(entryName, prc, paramValueMap);
    } else {
        throw new SenderException("unknown operation [" + getOperation() + "]");
    }
}