Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:org.wso2.carbon.identity.account.suspension.notification.task.ldap.LDAPNotificationReceiversRetrieval.java

@Override
public List<NotificationReceiver> getNotificationReceivers(long lookupMin, long lookupMax,
        long delayForSuspension, String tenantDomain) throws AccountSuspensionNotificationException {

    List<NotificationReceiver> users = new ArrayList<NotificationReceiver>();

    if (realmConfiguration != null) {
        String ldapSearchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
        RealmService realmService = NotificationTaskDataHolder.getInstance().getRealmService();

        try {//from w w  w.j  a va2s  .com
            ClaimManager claimManager = (ClaimManager) realmService
                    .getTenantUserRealm(IdentityTenantUtil.getTenantId(tenantDomain)).getClaimManager();
            String userStoreDomain = realmConfiguration
                    .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
            if (StringUtils.isBlank(userStoreDomain)) {
                userStoreDomain = IdentityUtil.getPrimaryDomainName();
            }

            String usernameMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.USERNAME_CLAIM);
            String firstNameMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.FIRST_NAME_CLAIM);
            String emailMapAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.EMAIL_CLAIM);
            String lastLoginTimeAttribute = claimManager.getAttributeName(userStoreDomain,
                    NotificationConstants.LAST_LOGIN_TIME);

            if (log.isDebugEnabled()) {
                log.debug(
                        "Retrieving ldap user list for lookupMin: " + lookupMin + " - lookupMax: " + lookupMax);
            }

            LDAPConnectionContext ldapConnectionContext = new LDAPConnectionContext(realmConfiguration);
            DirContext ctx = ldapConnectionContext.getContext();

            //carLicense is the mapped LDAP attribute for LastLoginTime claim
            String searchFilter = "(&(" + lastLoginTimeAttribute + ">=" + lookupMin + ")("
                    + lastLoginTimeAttribute + "<=" + lookupMax + "))";

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

            NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

            if (log.isDebugEnabled()) {
                log.debug("LDAP user list retrieved.");
            }

            while (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                NotificationReceiver receiver = new NotificationReceiver();
                receiver.setEmail((String) result.getAttributes().get(emailMapAttribute).get());
                receiver.setUsername((String) result.getAttributes().get(usernameMapAttribute).get());
                receiver.setFirstName((String) result.getAttributes().get(firstNameMapAttribute).get());
                receiver.setUserStoreDomain(userStoreDomain);

                long lastLoginTime = Long
                        .parseLong(result.getAttributes().get(lastLoginTimeAttribute).get().toString());
                long expireDate = lastLoginTime + TimeUnit.DAYS.toMillis(delayForSuspension);
                receiver.setExpireDate(new SimpleDateFormat("dd-MM-yyyy").format(new Date(expireDate)));

                if (log.isDebugEnabled()) {
                    log.debug("Expire date was set to: " + receiver.getExpireDate());
                }
                users.add(receiver);
            }
        } catch (NamingException e) {
            throw new AccountSuspensionNotificationException("Failed to filter users from LDAP user store.", e);
        } catch (UserStoreException e) {
            throw new AccountSuspensionNotificationException("Failed to load LDAP connection context.", e);
        } catch (org.wso2.carbon.user.api.UserStoreException e) {
            throw new AccountSuspensionNotificationException(
                    "Error occurred while getting tenant user realm for " + "tenant:" + tenantDomain, e);
        }
    }
    return users;
}

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

/**
 * {@inheritDoc}/*from  w w w  .ja v a 2 s  .co 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  a v a  2 s . c o  m
 */
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}//  w w w  .  java  2s.c  o m
 */
@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}/*  w ww  .j a  va  2 s.  c  om*/
 */
@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.//  w w  w.j  a  v  a2 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: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.
 *//*  ww  w .j  a  v a2s .  co  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

/**
 * Check whether this is the last/only user in this group.
 *
 * @param userDN DN of the User./* ww w.  ja v a 2  s. c om*/
 * @param groupEntry SearchResult Representing the Group.
 * @return true if user is the only one in role, false otherwise.
 */
protected boolean isOnlyUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isOnlyUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            NamingEnumeration attributes = groupAttributes.getAll();
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                String attributeID = memberAttribute.getID();
                if (memberAttributeName.equals(attributeID)) {
                    if (memberAttribute.size() == 1 && userDN.equals(memberAttribute.get())) {
                        return true;
                    }
                }

            }

            attributes.close();

        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while looping through attributes set of group: "
                + groupEntry.getNameInNamespace();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return isOnlyUserInRole;
}

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

/**
 * Check whether user is in the group by searching through its member attributes.
 *
 * @param userDN DN of the User whose existence in the group is searched.
 * @param groupEntry SearchResult representation of the Group.
 * @return true if the user exists in the role, false otherwise.
 * @throws UserStoreException If an error occurs while retrieving data.
 *///from   w  ww . ja  v a 2s .  c o m
protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            // get group's returned attributes
            NamingEnumeration attributes = groupAttributes.getAll();
            // loop through attributes
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) {
                    // loop through attribute values
                    for (int i = 0; i < memberAttribute.size(); i++) {
                        if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) {
                            return true;
                        }
                    }
                }

            }
            attributes.close();
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while looping through attributes set of group: "
                + groupEntry.getNameInNamespace();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return isUserInRole;
}

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

/**
 * {@inheritDoc}//  w w  w. j ava  2s . 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 org.wso2.carbon.identity.agent.outbound.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;
}