Example usage for javax.naming.directory DirContext search

List of usage examples for javax.naming.directory DirContext search

Introduction

In this page you can find the example usage for javax.naming.directory DirContext search.

Prototype

public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons)
        throws NamingException;

Source Link

Document

Searches in the named context or object for entries that satisfy the given search filter.

Usage

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

/**
 * {@inheritDoc}// www .  j av a 2 s  .c  o m
 */
public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames)
        throws UserStoreException {

    String userAttributeSeparator = ",";
    String userDN = null;

    // read list of patterns from user-mgt.xml
    String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);

    if (patterns != null && !patterns.isEmpty()) {

        if (log.isDebugEnabled()) {
            log.debug("Using User DN Patterns " + patterns);
        }

        if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {
            userDN = getNameInSpaceForUserName(userName);
        } else {
            userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName));
        }
    }

    Map<String, String> values = new HashMap<>();
    DirContext dirContext = this.connectionSource.getContext();
    String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;
    NamingEnumeration<?> allAttrs = null;
    try {
        if (userDN != null) {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) {
                propertyNames = null;
            }
            searchCtls.setReturningAttributes(propertyNames);

            try {
                answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls);
            } catch (PartialResultException e) {
                // can be due to referrals in AD. so just ignore error
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (isIgnorePartialResultException()) {
                    if (log.isDebugEnabled()) {
                        log.debug(errorMessage, e);
                    }
                } else {
                    throw new UserStoreException(errorMessage, e);
                }
            } catch (NamingException e) {
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (log.isDebugEnabled()) {
                    log.debug(errorMessage, e);
                }
                throw new UserStoreException(errorMessage, e);
            }
        } else {
            answer = this.searchForUser(searchFilter, propertyNames, dirContext);
        }
        assert answer != null;
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                for (allAttrs = attributes.getAll(); allAttrs.hasMore();) {
                    Attribute attribute = (Attribute) allAttrs.next();
                    if (attribute != null) {
                        StringBuilder attrBuffer = new StringBuilder();
                        for (attrs = attribute.getAll(); attrs.hasMore();) {
                            Object attObject = attrs.next();
                            String attr = null;
                            if (attObject instanceof String) {
                                attr = (String) attObject;
                            } else if (attObject instanceof byte[]) {
                                //if the attribute type is binary base64 encoded string will be returned
                                attr = new String(Base64.encodeBase64((byte[]) attObject), "UTF-8");
                            }

                            if (attr != null && attr.trim().length() > 0) {
                                String attrSeparator = userStoreProperties.get(MULTI_ATTRIBUTE_SEPARATOR);
                                if (attrSeparator != null && !attrSeparator.trim().isEmpty()) {
                                    userAttributeSeparator = attrSeparator;
                                }
                                attrBuffer.append(attr).append(userAttributeSeparator);
                            }
                            String value = attrBuffer.toString();

                            /*
                             * Length needs to be more than userAttributeSeparator.length() for a valid
                             * attribute, since we
                             * attach userAttributeSeparator
                             */
                            if (value.trim().length() > userAttributeSeparator.length()) {
                                value = value.substring(0, value.length() - userAttributeSeparator.length());
                                values.put(attribute.getID(), value);
                            }

                        }

                    }
                }
            }
        }

    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user property values for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "Error occurred while Base64 encoding property values for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        // close the naming enumeration and free up resource
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }
    return values;
}

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

/**
 * {@inheritDoc}/*from  w  w  w.  j  av  a  2  s  .com*/
 */
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }

    int givenMax;
    int searchTime;

    try {
        givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = CommonConstants.MAX_USER_LIST;
    }

    try {
        searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = CommonConstants.MAX_SEARCH_TIME;
    }

    if (maxItemLimit <= 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

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

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user search. Please enter valid sequence.");
    }

    StringBuilder searchFilter = new StringBuilder(
            userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE);

    String serviceNameAttribute = "sn";

    StringBuilder finalFilter = new StringBuilder();

    // read the display name attribute - if provided
    String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);

    String[] returnedAtts;

    if (StringUtils.isNotEmpty(displayNameAttribute)) {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    } else {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    }

    if (debug) {
        log.debug(
                "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString());
        log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime);
    }

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    List<String> list = new ArrayList<>();

    try {
        dirContext = connectionSource.getContext();
        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);

        for (String searchBase : searchBaseArray) {

            answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (sr.getAttributes() != null) {
                    log.debug("Result found ..");
                    Attribute attr = sr.getAttributes().get(userNameProperty);

                    // If this is a service principle, just ignore and
                    // iterate rest of the array. The entity is a service if
                    // value of surname is Service

                    Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                    if (attrSurname != null) {
                        if (debug) {
                            log.debug(serviceNameAttribute + " : " + attrSurname);
                        }
                        String serviceName = (String) attrSurname.get();
                        if (serviceName != null
                                && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                            continue;
                        }
                    }

                    if (attr != null) {
                        String name = (String) attr.get();
                        list.add(name);
                    }
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        Arrays.sort(userNames);

        if (debug) {
            for (String username : userNames) {
                log.debug("result: " + username);
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userNames;
}

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

/**
 * {@inheritDoc}//from w w  w.  j a v a 2  s  .  c om
 */
@Override
public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException {

    boolean debug = log.isDebugEnabled();
    String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    // read the roles with this membership property
    String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);

    if (membershipProperty == null || membershipProperty.length() < 1) {
        throw new UserStoreException("Please set membership attribute");
    }

    String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    String userDNPattern = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);
    String nameInSpace;
    if (org.apache.commons.lang.StringUtils.isNotEmpty(userDNPattern)
            && !userDNPattern.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {
        nameInSpace = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
    } else {
        nameInSpace = this.getNameInSpaceForUserName(userName);
    }

    String membershipValue;
    if (nameInSpace != null) {
        try {
            LdapName ldn = new LdapName(nameInSpace);
            membershipValue = escapeLdapNameForFilter(ldn);
        } catch (InvalidNameException e) {
            log.error("Error while creating LDAP name from: " + nameInSpace);
            throw new UserStoreException("Invalid naming exception for : " + nameInSpace, e);
        }
    } else {
        return false;
    }

    searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + "))";
    String returnedAtts[] = { roleNameProperty };
    searchCtls.setReturningAttributes(returnedAtts);

    if (debug) {
        log.debug("Do check whether the user : " + userName + " is in role: " + roleName);
        log.debug("Search filter : " + searchFilter);
        for (String retAttrib : returnedAtts) {
            log.debug("Requesting attribute: " + retAttrib);
        }
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    try {
        dirContext = connectionSource.getContext();

        if (debug) {
            log.debug("Do check whether the user: " + userName + " is in role: " + roleName);
            log.debug("Search filter: " + searchFilter);
            for (String retAttrib : returnedAtts) {
                log.debug("Requesting attribute: " + retAttrib);
            }
        }

        searchFilter = "(&" + searchFilter + "(" + membershipProperty + "=" + membershipValue + ") ("
                + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))";

        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);

        for (String searchBase : searchBaseArray) {
            answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);

            if (answer.hasMoreElements()) {
                if (debug) {
                    log.debug("User: " + userName + " in role: " + roleName);
                }
                return true;
            }

            if (debug) {
                log.debug("User: " + userName + " NOT in role: " + roleName);
            }
        }
    } catch (NamingException e) {
        if (log.isDebugEnabled()) {
            log.debug(e.getMessage(), e);
        }
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return false;
}

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

/**
 * {@inheritDoc}//ww  w.  j a v a2  s. c om
 */
@Override
public String[] doGetUserListOfRole(String roleName, int maxItemLimit) throws UserStoreException {

    boolean debug = log.isDebugEnabled();
    List<String> userList = new ArrayList<String>();
    String[] names = new String[0];
    int givenMax = CommonConstants.MAX_USER_ROLE_LIST;
    int searchTime = CommonConstants.MAX_SEARCH_TIME;

    try {
        givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = CommonConstants.MAX_USER_ROLE_LIST;
    }

    try {
        searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = CommonConstants.MAX_SEARCH_TIME;
    }

    if (maxItemLimit <= 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setTimeLimit(searchTime);
        searchCtls.setCountLimit(maxItemLimit);

        String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
        String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);
        searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "="
                + escapeSpecialCharactersForFilter(roleName) + "))";

        String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        String returnedAtts[] = { membershipProperty };
        searchCtls.setReturningAttributes(returnedAtts);
        List<String> userDNList = new ArrayList<String>();

        SearchResult sr = null;
        dirContext = connectionSource.getContext();

        // handling multiple search bases
        String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
        String[] roleSearchBaseArray = searchBases.split("#");
        for (String searchBase : roleSearchBaseArray) {
            if (debug) {
                log.debug("Searching role: " + roleName + " SearchBase: " + searchBase + " SearchFilter: "
                        + searchFilter);
            }
            try {
                // read the DN of users who are members of the group
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
                int count = 0;
                if (answer.hasMore()) { // to check if there is a result
                    while (answer.hasMore()) { // to check if there are more than one group
                        if (count > 0) {
                            throw new UserStoreException("More than one group exist with name");
                        }
                        sr = answer.next();
                        count++;
                    }
                    break;
                }
            } catch (NamingException e) {
                // ignore
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
            }
        }

        if (debug) {
            log.debug("Found role: " + sr.getNameInNamespace());
        }

        // read the member attribute and get DNs of the users
        Attributes attributes = sr.getAttributes();
        if (attributes != null) {
            NamingEnumeration attributeEntry = null;
            for (attributeEntry = attributes.getAll(); attributeEntry.hasMore();) {
                Attribute valAttribute = (Attribute) attributeEntry.next();
                if (membershipProperty.equals(valAttribute.getID())) {
                    NamingEnumeration values = null;
                    for (values = valAttribute.getAll(); values.hasMore();) {
                        String value = values.next().toString();
                        if (userDNList.size() >= maxItemLimit) {
                            break;
                        }
                        userDNList.add(value);
                        if (debug) {
                            log.debug("Found attribute: " + membershipProperty + " value: " + value);
                        }
                    }
                }
            }
        }

        if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) {
            /* when the GroupEntryObjectClass is posixGroup, membership attribute is memberUid. We have to
               retrieve the DN using the memberUid.
               This procedure has to make an extra call to ldap. alternatively this can be done with a single ldap
               search using the memberUid and retrieving the display name and username. */
            List<String> userDNListNew = new ArrayList<>();

            for (String user : userDNList) {
                String userDN = getNameInSpaceForUserName(user);
                userDNListNew.add(userDN);
            }
            userDNList = userDNListNew;
        }

        // iterate over users' DN list and get userName and display name
        // attribute values
        String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE);
        String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);
        String[] returnedAttributes = { userNameProperty, displayNameAttribute };

        for (String user : userDNList) {
            if (debug) {
                log.debug("Getting name attributes of: " + user);
            }
            Attributes userAttributes;
            try {
                // '\' and '"' characters need another level of escaping before searching
                userAttributes = dirContext.getAttributes(escapeDNForSearch(user), returnedAttributes);

                String displayName = null;
                String userName = null;
                if (userAttributes != null) {
                    Attribute userNameAttribute = userAttributes.get(userNameProperty);
                    if (userNameAttribute != null) {
                        userName = (String) userNameAttribute.get();
                        if (debug) {
                            log.debug("UserName: " + userName);
                        }
                    }
                    if (org.apache.commons.lang.StringUtils.isNotEmpty(displayNameAttribute)) {
                        Attribute displayAttribute = userAttributes.get(displayNameAttribute);
                        if (displayAttribute != null) {
                            displayName = (String) displayAttribute.get();
                        }
                        if (debug) {
                            log.debug("DisplayName: " + displayName);
                        }
                    }
                }

                // Username will be null in the special case where the
                // username attribute has changed to another
                // and having different userNameProperty than the current
                // user-mgt.xml
                if (userName != null) {
                    user = UserStoreUtils.getCombinedName(userName, displayName);
                    userList.add(user);
                    if (debug) {
                        log.debug(user + " is added to the result list");
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "User " + user + " doesn't have the user name property : " + userNameProperty);
                    }
                }

            } catch (NamingException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Error in reading user information in the user store for the user " + user
                            + e.getMessage(), e);
                }
            }

        }
        names = userList.toArray(new String[userList.size()]);

    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error in reading user information in the user store";
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error in reading user information in the user store";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return names;
}

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

/**
 * {@inheritDoc}/*from www .j  av  a 2  s .c o m*/
 */
@Override
public boolean doCheckExistingRole(String roleName) throws UserStoreException {

    boolean debug = log.isDebugEnabled();
    boolean isExisting = false;

    if (debug) {
        log.debug("Searching for role: " + roleName);
    }
    String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
    String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "="
            + escapeSpecialCharactersForFilter(roleName) + "))";
    String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);

    if (debug) {
        log.debug("Using search filter: " + searchFilter);
    }
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(new String[] { roleNameProperty });
    NamingEnumeration<SearchResult> answer = null;
    DirContext dirContext = null;

    try {
        dirContext = connectionSource.getContext();
        String[] roleSearchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);
        for (String searchBase : roleSearchBaseArray) {
            if (debug) {
                log.debug("Searching in " + searchBase);
            }
            try {
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
                if (answer.hasMoreElements()) {
                    isExisting = true;
                    break;
                }
            } catch (NamingException e) {
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
            }
        }
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    if (debug) {
        log.debug("Is role: " + roleName + " exist: " + isExisting);
    }
    return isExisting;
}

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.//from   w  w  w.  j av  a2s  . c o 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: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.
 *//*ww  w.  j a  v  a  2s . co  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

/**
 * @param userName Username of the user.
 * @param searchBase Searchbase which the user should be searched for.
 * @param searchFilter Search filter of the username.
 * @return DN of the user whose usename is given.
 * @throws UserStoreException If an error occurs while connecting to the LDAP userstore.
 *//*from  ww  w.  j  av  a2 s.  c om*/
private String getNameInSpaceForUserName(String userName, String searchBase, String searchFilter)
        throws UserStoreException {
    boolean debug = log.isDebugEnabled();

    String userDN = null;

    DirContext dirContext = this.connectionSource.getContext();
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        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);
            }
        }
        SearchResult userObj;
        String[] searchBases = searchBase.split(CommonConstants.XML_PATTERN_SEPERATOR);
        for (String base : searchBases) {
            answer = dirContext.search(escapeDNForSearch(base), searchFilter, searchCtls);
            if (answer.hasMore()) {
                userObj = answer.next();
                if (userObj != null) {
                    //no need to decode since , if decoded the whole string, can't be encoded again
                    //eg CN=Hello\,Ok=test\,test, OU=Industry
                    userDN = userObj.getNameInNamespace();
                    break;
                }
            }
        }
        if (debug) {
            log.debug("Name in space for " + userName + " is " + userDN);
        }
    } catch (Exception e) {
        log.debug(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userDN;
}

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

/**
 * @param searchBases Group search bases.
 * @param searchFilter Search filter for role search with membership value included.
 * @param searchCtls Search controls with returning attributes set.
 * @param property Role name attribute name in LDAP userstore.
 * @return List of roles according to the given filter.
 * @throws UserStoreException If an error occurs while retrieving data from LDAP context.
 *///from  w ww  .j av  a2 s.  c  o m
private List<String> getListOfNames(String searchBases, String searchFilter, SearchControls searchCtls,
        String property) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    List<String> names = new ArrayList<>();
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;

    if (debug) {
        log.debug("Result for searchBase: " + searchBases + " searchFilter: " + searchFilter + " property:"
                + property);
    }

    try {
        dirContext = connectionSource.getContext();

        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);
        for (String searchBase : searchBaseArray) {

            try {
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);

                while (answer.hasMoreElements()) {
                    SearchResult sr = answer.next();
                    if (sr.getAttributes() != null) {
                        Attribute attr = sr.getAttributes().get(property);
                        if (attr != null) {
                            for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
                                String name = (String) vals.nextElement();
                                if (debug) {
                                    log.debug("Found user: " + name);
                                }
                                names.add(name);
                            }
                        }
                    }
                }
            } catch (NamingException e) {
                // ignore
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
            }

            if (debug) {
                for (String name : names) {
                    log.debug("Result  :  " + name);
                }
            }

        }

        return names;
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
}

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

/**
 * Reused method to search groups with various filters.
 *
 * @param searchFilter Group Search Filter
 * @param returningAttributes Attributes which the values needed.
 * @param searchScope Search Scope/*from   www .j a  v  a  2s  .  c  om*/
 * @return Group Representation with given returning attributes
 */
protected NamingEnumeration<SearchResult> searchInGroupBase(String searchFilter, String[] returningAttributes,
        int searchScope, DirContext rootContext, String searchBase) throws UserStoreException {
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> groupSearchResults = null;
    try {
        groupSearchResults = rootContext.search(escapeDNForSearch(searchBase), searchFilter, userSearchControl);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in group base.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return groupSearchResults;
}