Example usage for javax.naming.directory SearchResult getAttributes

List of usage examples for javax.naming.directory SearchResult getAttributes

Introduction

In this page you can find the example usage for javax.naming.directory SearchResult getAttributes.

Prototype

public Attributes getAttributes() 

Source Link

Document

Retrieves the attributes in this search result.

Usage

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(List, String)
 *///ww  w. java  2 s.  c o m
@Override
public void addLinks(List<String> sourceIds, String targetId) throws DirectoryException {
    String attributeId = getStaticAttributeId();
    if (attributeId == null && !sourceIds.isEmpty()) {
        log.warn("trying to edit a non-static reference: ignoring");
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();

    String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // compute the target dn to add to all the matching source
            // entries
            SearchResult ldapEntry = targetSession.getLdapEntry(targetId);
            if (ldapEntry == null) {
                throw new DirectoryException(
                        String.format("could not add links to unexisting %s in directory %s", targetId,
                                ldapTargetDirectory.getName()));
            }
            String targetAttributeValue;
            if (staticAttributeIdIsDn) {
                targetAttributeValue = ldapEntry.getNameInNamespace();
            } else {
                targetAttributeValue = targetId;
            }

            for (String sourceId : sourceIds) {
                // fetch the entry to be able to run the security policy
                // implemented in an entry adaptor
                DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
                if (sourceEntry == null) {
                    log.warn(String.format(
                            "entry %s in directory %s not found: could not add link to %s in directory %s",
                            sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName()));
                    continue;
                }
                if (BaseSession.isReadOnlyEntry(sourceEntry)) {
                    // skip this entry since it cannot be edited to add the
                    // reference to targetId
                    log.warn(String.format(
                            "entry %s in directory %s is readonly: could not add link to %s in directory %s",
                            sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName()));
                    continue;
                }
                ldapEntry = sourceSession.getLdapEntry(sourceId);
                String sourceDn = ldapEntry.getNameInNamespace();
                Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
                if (storedAttr.contains(targetAttributeValue)) {
                    // no need to readd
                    continue;
                }
                try {
                    // add the new dn
                    Attributes attrs = new BasicAttributes(attributeId, targetAttributeValue);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks([%s], %s): LDAP modifyAttributes dn='%s'"
                                        + " mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                StringUtils.join(sourceIds, ", "), targetId, sourceDn, attrs, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrs);

                    // robustly clean any existing empty marker now that we
                    // are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, %s): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    StringUtils.join(sourceIds, ", "), targetId, sourceDn,
                                    cleanAttrs.toString(), this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot add dynamic reference in field %s for target %s",
                                getFieldName(), targetId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

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

/**
 * @param searchBases//from w w w.j  ava2 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

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

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

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

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

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

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

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

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

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

    return roles;
}

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

/**
 * @param sr//from   w  w  w. j  a v  a  2s  .c  o m
 * @param groupAttributeName
 * @return
 */
private List<String> parseSearchResult(SearchResult sr, String groupAttributeName) {
    List<String> list = new ArrayList<String>();
    Attributes attrs = sr.getAttributes();

    if (attrs != null) {
        try {
            NamingEnumeration ae = null;
            for (ae = attrs.getAll(); ae.hasMore();) {
                Attribute attr = (Attribute) ae.next();
                if (groupAttributeName == null || groupAttributeName.equals(attr.getID())) {
                    NamingEnumeration e = null;
                    for (e = attr.getAll(); e.hasMore();) {
                        String value = e.next().toString();
                        int begin = value.indexOf("=") + 1;
                        int end = value.indexOf(",");
                        if (begin > -1 && end > -1) {
                            value = value.substring(begin, end);
                        }
                        list.add(value);
                    }
                    JNDIUtil.closeNamingEnumeration(e);
                }
            }
            JNDIUtil.closeNamingEnumeration(ae);
        } catch (NamingException e) {
            log.debug(e.getMessage(), e);
        }
    }
    return list;
}

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) {/*  w  w w . java  2s  .c om*/
        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

/**
 *
 *///from w  w  w  .j av  a2  s  .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

/**
 *
 *///from  w w w.j a  v a2  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.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * {@inheritDoc}/*from ww  w.ja  v  a 2s. com*/
 */
@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.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@SuppressWarnings("deprecation")
@Override/*from w  w w .  j a  v  a 2 s.  c om*/
public void doDeleteUser(String userName) throws UserStoreException {

    boolean debug = log.isDebugEnabled();

    if (debug) {
        log.debug("Deleting user: " + userName);
    }
    // delete user from LDAP group if read-write enabled.
    String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));
    String[] returningUserAttributes = new String[] { userNameAttribute };

    DirContext mainDirContext = this.connectionSource.getContext();

    NamingEnumeration<SearchResult> userResults = searchInUserBase(searchFilter, returningUserAttributes,
            SearchControls.SUBTREE_SCOPE, mainDirContext);
    NamingEnumeration<SearchResult> groupResults = null;

    DirContext subDirContext = null;
    try {
        SearchResult userResult = null;
        String userDN = null;
        // here we assume only one user
        // TODO: what to do if there are more than one user
        while (userResults.hasMore()) {
            userResult = userResults.next();
            userDN = userResult.getName();
            log.debug("User DN: " + userDN);
        }

        // LDAP roles of user to delete the mapping

        List<String> roles = new ArrayList<String>();
        String[] externalRoles = doGetExternalRoleListOfUser(userName, "*");
        roles.addAll(Arrays.asList(externalRoles));
        if (isSharedGroupEnabled()) {
            String[] sharedRoles = doGetSharedRoleListOfUser(null, userName, "*");
            if (sharedRoles != null) {
                roles.addAll(Arrays.asList(sharedRoles));
            }
        }
        String[] rolesOfUser = roles.toArray(new String[roles.size()]);

        if (rolesOfUser.length != 0) {

            String[] returningGroupAttributes = new String[] {
                    realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE) };
            for (String role : rolesOfUser) {

                RoleContext context = createRoleContext(role);
                String searchBase = ((LDAPRoleContext) context).getSearchBase();
                searchFilter = ((LDAPRoleContext) context).getSearchFilter();
                role = context.getRoleName();

                if (role.indexOf("/") > -1) {
                    role = (role.split("/"))[1];
                }
                String grpSearchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(role));
                groupResults = searchInGroupBase(grpSearchFilter, returningGroupAttributes,
                        SearchControls.SUBTREE_SCOPE, mainDirContext, searchBase);
                SearchResult groupResult = null;
                while (groupResults.hasMore()) {
                    groupResult = groupResults.next();
                }
                if (isOnlyUserInRole(userDN, groupResult) && !emptyRolesAllowed) {
                    String errorMessage = "User: " + userName + " is the only user " + "in " + role + "."
                            + "There should be at " + "least one user" + " in the role. Hence can"
                            + " not delete the user.";
                    throw new UserStoreException(errorMessage);
                }
            }
            // delete role list
            doUpdateRoleListOfUser(userName, rolesOfUser, new String[] {});
        }

        // delete user entry if it exist
        if (userResult != null && userResult.getAttributes().get(userNameAttribute).get().toString()
                .toLowerCase().equals(userName.toLowerCase())) {
            if (log.isDebugEnabled()) {
                log.debug("Deleting " + userDN + " with search base " + userSearchBase);
            }
            subDirContext = (DirContext) mainDirContext.lookup(userSearchBase);
            subDirContext.destroySubcontext(userDN);
        }
        userCache.remove(userName);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while deleting the user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(groupResults);
        JNDIUtil.closeNamingEnumeration(userResults);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(mainDirContext);
    }
}

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

/**
 *
 *//*ww  w. ja v  a2 s. c  om*/
public String[] getUserListOfLDAPRole(RoleContext context, String filter) throws UserStoreException {

    boolean debug = log.isDebugEnabled();

    if (debug) {
        log.debug("Getting user list of role: " + context.getRoleName() + " with filter: " + filter);
    }

    List<String> userList = new ArrayList<String>();
    String[] names = new String[0];
    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;
    }

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

        String searchFilter = ((LDAPRoleContext) context).getListFilter();
        String roleNameProperty = ((LDAPRoleContext) context).getRoleNameProperty();
        searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "="
                + escapeSpecialCharactersForFilter(context.getRoleName()) + "))";

        String membershipProperty = realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        String returnedAtts[] = { membershipProperty };
        searchCtls.setReturningAttributes(returnedAtts);

        List<String> userDNList = new ArrayList<String>();

        SearchResult sr = null;
        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(context.getRoleName()));
                try {
                    answer = dirContext.search(escapeDNForSearch(pattern), searchFilter, searchCtls);
                    if (answer.hasMore()) {
                        sr = (SearchResult) answer.next();
                        break;
                    }
                } catch (NamingException e) {
                    // ignore
                    if (log.isDebugEnabled()) {
                        log.debug(e);
                    }
                }
            }
        }

        if (sr == null) {
            // handling multiple search bases
            String searchBases = ((LDAPRoleContext) context).getSearchBase();
            String[] roleSearchBaseArray = searchBases.split("#");
            for (String searchBase : roleSearchBaseArray) {
                if (debug) {
                    log.debug("Searching role: " + context.getRoleName() + " 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 = (SearchResult) 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 == null || membershipProperty.equals(valAttribute.getID())) {
                    NamingEnumeration values = null;
                    for (values = valAttribute.getAll(); values.hasMore();) {
                        String value = values.next().toString();
                        userDNList.add(value);

                        if (debug) {
                            log.debug("Found attribute: " + membershipProperty + " value: " + value);
                        }
                    }
                }
            }
        }

        if (MEMBER_UID.equals(realmConfig.getUserStoreProperty(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 = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
        String displayNameAttribute = realmConfig.getUserStoreProperty(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(
                        user.replace("\\\\", "\\\\\\").replace("\\\"", "\\\\\""), 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 (displayNameAttribute != null) {
                        Attribute displayAttribute = userAttributes.get(displayNameAttribute);
                        if (displayAttribute != null) {
                            displayName = (String) displayAttribute.get();
                        }
                        if (debug) {
                            log.debug("DisplayName: " + displayName);
                        }
                    }
                }
                String domainName = realmConfig
                        .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);

                // 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 = UserCoreUtil.getCombinedName(domainName, userName, displayName);
                    userList.add(user);
                    if (debug) {
                        log.debug(user + " is added to the result list");
                    }
                }
                // Skip listing users which are not applicable to current
                // user-mgt.xml
                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 for filter : " + filter;
        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 for filter : " + filter;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }

    return names;
}