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.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 *
 *///from   w ww.j ava  2s .  c  o  m
public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames, String profileName)
        throws UserStoreException {

    String userAttributeSeparator = ",";
    String userDN = null;
    LdapName ldn = (LdapName) userCache.get(userName);

    if (ldn == null) {
        // read list of patterns from user-mgt.xml
        String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);

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

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

            if (patterns.contains("#")) {
                userDN = getNameInSpaceForUserName(userName);
            } else {
                userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName));
            }
        }
    } else {
        userDN = ldn.toString();
    }

    Map<String, String> values = new HashMap<String, String>();
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }

    DirContext dirContext = this.connectionSource.getContext();
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;
    try {
        if (userDN != null) {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            if (propertyNames != null && propertyNames.length > 0) {
                searchCtls.setReturningAttributes(propertyNames);
            }
            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 (propertyNames == null) {
                    log.debug("No attributes requested");
                } else {
                    for (String attribute : propertyNames) {
                        log.debug("Requesting attribute :" + attribute);
                    }
                }
            }
            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);
        }
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                for (String name : propertyNames) {
                    if (name != null) {
                        Attribute attribute = attributes.get(name);
                        if (attribute != null) {
                            StringBuffer attrBuffer = new StringBuffer();
                            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));
                                }

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

                                /*
                                 * Length needs to be more than userAttributeSeparator.length() for a valid
                                 * attribute, since we
                                 * attach userAttributeSeparator
                                 */
                                if (value != null && value.trim().length() > userAttributeSeparator.length()) {
                                    value = value.substring(0,
                                            value.length() - userAttributeSeparator.length());
                                    values.put(name, 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);
    } finally {
        // close the naming enumeration and free up resources
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }
    return values;
}

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

protected boolean isExistingLDAPRole(RoleContext context) throws UserStoreException {

    boolean debug = log.isDebugEnabled();
    boolean isExisting = false;
    String roleName = context.getRoleName();

    if (debug) {//from ww  w  . j  a  va2  s  .  co  m
        log.debug("Searching for role: " + roleName);
    }
    String searchFilter = ((LDAPRoleContext) context).getListFilter();
    String roleNameProperty = ((LDAPRoleContext) context).getRoleNameProperty();
    searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "="
            + escapeSpecialCharactersForFilter(roleName) + "))";
    String searchBases = ((LDAPRoleContext) context).getSearchBase();

    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();
        // with DN patterns
        if (((LDAPRoleContext) context).getRoleDNPatterns().size() > 0) {
            for (String pattern : ((LDAPRoleContext) context).getRoleDNPatterns()) {
                if (debug) {
                    log.debug("Using pattern: " + pattern);
                }
                pattern = MessageFormat.format(pattern.trim(), escapeSpecialCharactersForDN(roleName));
                try {
                    answer = dirContext.search(escapeDNForSearch(pattern), searchFilter, searchCtls);
                } catch (NamingException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e);
                    }
                    // ignore
                }
                if (answer != null && answer.hasMoreElements()) {
                    return true;
                }
            }
        }
        //try out with handle multiple search bases
        String[] roleSearchBaseArray = searchBases.split("#");
        for (String searchBase : roleSearchBaseArray) {
            // no DN Patterns found
            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);
                }
                // ignore
            }
        }
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    if (debug) {
        log.debug("Is role: " + roleName + " exist: " + isExisting);
    }
    return isExisting;
}

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

/**
 *
 *//* w w  w. jav a 2 s  .  co  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 = UserCoreConstants.MAX_USER_ROLE_LIST;
    int searchTime = UserCoreConstants.MAX_SEARCH_TIME;

    try {
        givenMax = Integer.parseInt(
                realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = UserCoreConstants.MAX_USER_ROLE_LIST;
    }

    try {
        searchTime = Integer.parseInt(
                realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = UserCoreConstants.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 serch. Please enter valid sequence.");
    }

    StringBuffer searchFilter = new StringBuffer(
            realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);

    String serviceNameAttribute = "sn";

    StringBuffer finalFilter = new StringBuffer();

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

    String[] returnedAtts = null;

    if (displayNameAttribute != null) {
        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<String>();

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

        for (String searchBase : searchBaseArray) {

            answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);

            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) 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 display name is provided, read that attribute
                     */
                    Attribute displayName = null;
                    if (displayNameAttribute != null) {
                        displayName = sr.getAttributes().get(displayNameAttribute);
                        if (debug) {
                            log.debug(displayNameAttribute + " : " + displayName);
                        }
                    }

                    if (attr != null) {
                        String name = (String) attr.get();
                        String display = null;
                        if (displayName != null) {
                            display = (String) displayName.get();
                        }
                        // append the domain if exist
                        String domain = this.getRealmConfiguration()
                                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                        // get the name in the format of
                        // domainName/userName|domainName/displayName
                        name = UserCoreUtil.getCombinedName(domain, name, display);
                        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.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * Returns the list of role names for the given search base and other
 * parameters/*from  w ww  .j a v  a2s.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:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * @param searchBases/*from ww  w. ja v a 2  s. c  o m*/
 * @param searchFilter
 * @param searchCtls
 * @param property
 * @return
 * @throws UserStoreException
 */
private List<String> getListOfNames(String searchBases, String searchFilter, SearchControls searchCtls,
        String property, boolean appendDn) throws UserStoreException {
    searchFilter = searchFilter.replace("*", "\\*");
    boolean debug = log.isDebugEnabled();
    List<String> names = new ArrayList<String>();
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;

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

    try {
        dirContext = connectionSource.getContext();

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

            try {
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
                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(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.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

public String[] getUserListFromProperties(String property, String value, String profileName)
        throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    String userAttributeSeparator = ",";
    String serviceNameAttribute = "sn";

    List<String> values = new ArrayList<String>();
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER);
    String userPropertyName = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);

    searchFilter = "(&" + searchFilter + "(" + property + "="
            + escapeSpecialCharactersForFilterWithStarAsRegex(value) + "))";

    DirContext dirContext = this.connectionSource.getContext();
    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;

    if (debug) {//from  ww w.java 2  s .  c  o m
        log.debug("Listing users with Property: " + property + " SearchFilter: " + searchFilter);
    }

    String[] returnedAttributes = new String[] { userPropertyName, serviceNameAttribute };

    try {
        answer = this.searchForUser(searchFilter, returnedAttributes, dirContext);
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                Attribute attribute = attributes.get(userPropertyName);
                if (attribute != null) {
                    StringBuffer attrBuffer = new StringBuffer();
                    for (attrs = attribute.getAll(); attrs.hasMore();) {
                        String attr = (String) attrs.next();
                        if (attr != null && attr.trim().length() > 0) {

                            String attrSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                            if (attrSeparator != null && !attrSeparator.trim().isEmpty()) {
                                userAttributeSeparator = attrSeparator;
                            }
                            attrBuffer.append(attr + userAttributeSeparator);
                            if (debug) {
                                log.debug(userPropertyName + " : " + attr);
                            }
                        }
                    }
                    String propertyValue = attrBuffer.toString();
                    // Length needs to be more than userAttributeSeparator.length() for a valid
                    // attribute, since we
                    // attach userAttributeSeparator.
                    if (propertyValue != null
                            && propertyValue.trim().length() > userAttributeSeparator.length()) {

                        if (attributes.get(serviceNameAttribute).get()
                                .equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                            continue;
                        }

                        propertyValue = propertyValue.substring(0,
                                propertyValue.length() - userAttributeSeparator.length());
                        values.add(propertyValue);
                    }
                }
            }
        }

    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user list from property : " + property
                + " & value : " + value + " & profile name : " + profileName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        // close the naming enumeration and free up resources
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }

    if (debug) {
        String[] results = values.toArray(new String[values.size()]);
        for (String result : results) {
            log.debug("result: " + result);
        }
    }

    return values.toArray(new String[values.size()]);
}

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

@Override
public boolean doCheckIsUserInRole(String userName, String roleName) throws UserStoreException {

    boolean debug = log.isDebugEnabled();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    LDAPRoleContext context = (LDAPRoleContext) createRoleContext(roleName);
    // Get the effective search base
    String searchBases = this.getEffectiveSearchBase(context.isShared());
    String memberOfProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBEROF_ATTRIBUTE);

    if (memberOfProperty != null && memberOfProperty.length() > 0) {
        List<String> list;

        String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
        String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
        String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
        String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY);
        String primaryGroupId = realmConfig.getUserStoreProperty(LDAPConstants.PRIMARY_GROUP_ID);

        String returnedAtts[] = { memberOfProperty };

        if (binaryAttribute != null && primaryGroupId != null) {
            returnedAtts = new String[] { memberOfProperty, binaryAttribute, primaryGroupId };
        }//  w w w  .j  ava  2 s.  c  o m
        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);
            }
        }

        if (binaryAttribute != null && primaryGroupId != null) {
            list = this.getAttributeListOfOneElementWithPrimarGroup(searchBases, searchFilter, searchCtls,
                    binaryAttribute, primaryGroupId, userNameProperty, memberOfProperty);
        } else {
            // use cache
            LdapName ldn = (LdapName) userCache.get(userName);
            if (ldn != null) {
                searchBases = ldn.toString();
            } else {
                // create DN directly   but there is no way when multiple DNs are used. Need to improve letter
                String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);
                if (userDNPattern != null && userDNPattern.trim().length() > 0
                        && !userDNPattern.contains("#")) {
                    searchBases = MessageFormat.format(userDNPattern, escapeSpecialCharactersForDN(userName));
                }
            }

            list = this.getAttributeListOfOneElement(searchBases, searchFilter, searchCtls);
        }

        if (debug) {
            if (list != null) {
                boolean isUserInRole = false;
                for (String item : list) {
                    log.debug("Result: " + item);
                    if (item.equalsIgnoreCase(roleName)) {
                        isUserInRole = true;
                    }
                }
                log.debug("Is user: " + userName + " in role: " + roleName + " ? " + isUserInRole);
            } else {
                log.debug("No results found !");
            }
        }

        // adding roles list in to the cache
        if (list != null) {
            addAllRolesToUserRolesCache(userName, list);
            for (String role : list) {
                if (role.equalsIgnoreCase(roleName)) {
                    return true;
                }
            }
        }

    } else {
        // read the roles with this membership property
        String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_LIST_FILTER);
        String membershipProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);

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

        String roleNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE);
        String userDNPattern = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);
        String nameInSpace;
        if (userDNPattern != null && userDNPattern.trim().length() > 0 && !userDNPattern.contains("#")) {
            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) {
                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 (context.getRoleDNPatterns().size() > 0) {
                for (String pattern : context.getRoleDNPatterns()) {

                    if (debug) {
                        log.debug("Using pattern: " + pattern);
                    }
                    searchBases = MessageFormat.format(pattern.trim(), escapeSpecialCharactersForDN(roleName));
                    try {
                        answer = dirContext.search(escapeDNForSearch(searchBases), searchFilter, searchCtls);
                    } catch (NamingException e) {
                        if (log.isDebugEnabled()) {
                            log.debug(e);
                        }
                        //ignore
                    }

                    if (answer != null && answer.hasMoreElements()) {
                        if (debug) {
                            log.debug("User: " + userName + " in role: " + roleName);
                        }
                        return true;
                    }
                    if (debug) {
                        log.debug("User: " + userName + " NOT in role: " + roleName);
                    }
                }
            } else {

                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("#");

                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.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Update the set of users belong to a LDAP role.
 *
 * @param roleName/*w  w  w .j  a  v  a2 s.c om*/
 * @param deletedUsers
 * @param newUsers
 */
@SuppressWarnings("deprecation")
@Override
public void doUpdateUserListOfRole(String roleName, String[] deletedUsers, String[] newUsers)
        throws UserStoreException {

    String errorMessage = null;
    NamingEnumeration<SearchResult> groupSearchResults = null;

    LDAPRoleContext ctx = (LDAPRoleContext) createRoleContext(roleName);
    roleName = ctx.getRoleName();

    String searchFilter = ctx.getSearchFilter();

    if (isExistingLDAPRole(ctx)) {

        DirContext mainDirContext = this.connectionSource.getContext();

        try {
            searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(roleName));
            String membershipAttributeName = realmConfig
                    .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
            String[] returningAttributes = new String[] { membershipAttributeName };

            String searchBase = ctx.getSearchBase();
            groupSearchResults = searchInGroupBase(searchFilter, returningAttributes,
                    SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
            SearchResult resultedGroup = null;
            String groupName = null;
            while (groupSearchResults.hasMoreElements()) {
                resultedGroup = groupSearchResults.next();
                groupName = resultedGroup.getName();
            }
            // check whether update operations are going to violate non
            // empty role
            // restriction specified in user-mgt.xml by
            // checking whether all users are trying to be deleted
            // before updating LDAP.
            Attribute returnedMemberAttribute = resultedGroup.getAttributes().get(membershipAttributeName);
            if (!emptyRolesAllowed
                    && newUsers.length - deletedUsers.length + returnedMemberAttribute.size() == 0) {
                errorMessage = "There should be at least one member in the role. "
                        + "Hence can not delete all the members.";
                throw new UserStoreException(errorMessage);

            } else {
                List<String> newUserList = new ArrayList<String>();
                List<String> deleteUserList = new ArrayList<String>();

                if (newUsers != null && newUsers.length != 0) {
                    String invalidUserList = "";
                    String existingUserList = "";

                    for (String newUser : newUsers) {
                        if (StringUtils.isEmpty(newUser)) {
                            continue;
                        }
                        String userNameDN = getNameInSpaceForUserName(newUser);
                        if (userNameDN == null) {
                            invalidUserList += newUser + " ";
                        } else if (isUserInRole(userNameDN, resultedGroup)) {
                            existingUserList += userNameDN + ",";
                        } else {
                            newUserList.add(userNameDN);
                        }
                    }
                    if (!StringUtils.isEmpty(invalidUserList) || !StringUtils.isEmpty(existingUserList)) {
                        errorMessage = (StringUtils.isEmpty(invalidUserList) ? ""
                                : "'" + invalidUserList + "' not in the user store. ")
                                + (StringUtils.isEmpty(existingUserList) ? ""
                                        : "'" + existingUserList + "' already belong to the role : "
                                                + roleName);
                        throw new UserStoreException(errorMessage);
                    }
                }

                if (deletedUsers != null && deletedUsers.length != 0) {
                    String invalidUserList = "";
                    for (String deletedUser : deletedUsers) {
                        if (StringUtils.isEmpty(deletedUser)) {
                            continue;
                        }
                        String userNameDN = getNameInSpaceForUserName(deletedUser);
                        if (userNameDN == null) {
                            invalidUserList += deletedUser + ",";
                        } else {
                            deleteUserList.add(userNameDN);
                        }
                    }
                    if (!StringUtils.isEmpty(invalidUserList)) {
                        errorMessage = "'" + invalidUserList + "' not in the user store.";
                        throw new UserStoreException(errorMessage);
                    }

                }

                for (String userNameDN : newUserList) {
                    modifyUserInRole(userNameDN, groupName, DirContext.ADD_ATTRIBUTE, searchBase);
                }

                for (String userNameDN : deleteUserList) {
                    modifyUserInRole(userNameDN, groupName, DirContext.REMOVE_ATTRIBUTE, searchBase);
                    // needs to clear authz cache for deleted users
                    userRealm.getAuthorizationManager().clearUserAuthorization(userNameDN);
                }
            }
        } catch (NamingException e) {
            errorMessage = "Error occurred while modifying the user list of role: " + roleName;
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
            throw new UserStoreException(errorMessage, e);
        } finally {
            JNDIUtil.closeNamingEnumeration(groupSearchResults);
            JNDIUtil.closeContext(mainDirContext);
        }
    } else {
        errorMessage = "The role: " + roleName + " does not exist.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage);
        }
        throw new UserStoreException(errorMessage);
    }
}

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

/**
 * Check whether user is in the group by searching through its member attributes.
 *
 * @param userDN//  w  ww .j  a  va2  s  .c  o m
 * @param groupEntry
 * @return
 * @throws UserStoreException
 */
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 = realmConfig
                        .getUserStoreProperty(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.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Check whether this is the last/only user in this group.
 *
 * @param userDN/*from w  w  w  . j a v  a  2  s . c o m*/
 * @param groupEntry
 * @return groupContext
 */
@SuppressWarnings("rawtypes")
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 = realmConfig
                        .getUserStoreProperty(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;
}