Example usage for javax.naming.directory Attribute get

List of usage examples for javax.naming.directory Attribute get

Introduction

In this page you can find the example usage for javax.naming.directory Attribute get.

Prototype

Object get() throws NamingException;

Source Link

Document

Retrieves one of this attribute's values.

Usage

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getUsers(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> userSearchResultEnum = null;
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {/*from   w w  w .  j av a2  s.c om*/
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        extendedUserSearchFilter = "(objectclass=" + userObjectClass + ")(|(uSNChanged>=" + deltaSyncUserTime
                + ")(modifyTimestamp>=" + deltaSyncUserTimeStamp + "Z))";

        if (userSearchFilter != null && !userSearchFilter.trim().isEmpty()) {
            String customFilter = userSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }

            extendedUserSearchFilter = "(&" + extendedUserSearchFilter + customFilter + ")";
        } else {
            extendedUserSearchFilter = "(&" + extendedUserSearchFilter + ")";
        }
        LOG.info("extendedUserSearchFilter = " + extendedUserSearchFilter);

        long highestdeltaSyncUserTime = deltaSyncUserTime;

        // When multiple OUs are configured, go through each OU as the user search base to search for users.
        for (int ou = 0; ou < userSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    userSearchResultEnum = ldapContext.search(userSearchBase[ou], extendedUserSearchFilter,
                            userSearchControls);

                    while (userSearchResultEnum.hasMore()) {
                        // searchResults contains all the user entries
                        final SearchResult userEntry = userSearchResultEnum.next();

                        if (userEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("userEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        //System.out.println("userEntry = " + userEntry);

                        Attributes attributes = userEntry.getAttributes();
                        if (attributes == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("attributes  missing for entry " + userEntry.getNameInNamespace()
                                        + ", skipping sync");
                            }
                            continue;
                        }

                        Attribute userNameAttr = attributes.get(userNameAttribute);
                        if (userNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(userNameAttribute + " missing for entry "
                                        + userEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }

                        String userFullName = (userEntry.getNameInNamespace()).toLowerCase();
                        String userName = (String) userNameAttr.get();

                        if (userName == null || userName.trim().isEmpty()) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(userNameAttribute + " empty for entry "
                                        + userEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }

                        Attribute timeStampAttr = attributes.get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            LOG.info("uSNChangedVal = " + uSNChangedVal + "and currentDeltaSyncTime = "
                                    + currentDeltaSyncTime);
                            if (currentDeltaSyncTime > highestdeltaSyncUserTime) {
                                highestdeltaSyncUserTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = attributes.get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncUserTime) {
                                    highestdeltaSyncUserTime = currentDeltaSyncTime;
                                    deltaSyncUserTimeStamp = timeStampVal;
                                }
                            }
                        }

                        if (!groupSearchFirstEnabled) {
                            String transformUserName = userNameTransform(userName);
                            try {
                                sink.addOrUpdateUser(transformUserName);
                            } catch (Throwable t) {
                                LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                        + ", for user: " + transformUserName);
                            }
                            //System.out.println("Adding user fullname = " + userFullName + " username = " + transformUserName);
                            userNameMap.put(userFullName, transformUserName);
                            Set<String> groups = new HashSet<String>();

                            // Get all the groups from the group name attribute of the user only when group search is not enabled.
                            if (!groupSearchEnabled) {
                                for (String useGroupNameAttribute : userGroupNameAttributeSet) {
                                    Attribute userGroupfAttribute = userEntry.getAttributes()
                                            .get(useGroupNameAttribute);
                                    if (userGroupfAttribute != null) {
                                        NamingEnumeration<?> groupEnum = userGroupfAttribute.getAll();
                                        while (groupEnum.hasMore()) {
                                            String gName = getShortGroupName((String) groupEnum.next());
                                            String transformGroupName = groupNameTransform(gName);
                                            groups.add(transformGroupName);
                                        }
                                    }
                                }
                            }

                            List<String> groupList = new ArrayList<String>(groups);
                            try {
                                sink.addOrUpdateUser(transformUserName, groupList);

                            } catch (Throwable t) {
                                LOG.error("sink.addOrUpdateUserGroups failed with exception: " + t.getMessage()
                                        + ", for user: " + transformUserName + " and groups: " + groupList);
                            }
                            counter++;
                            if (counter <= 2000) {
                                if (LOG.isInfoEnabled()) {
                                    LOG.info("Updating user count: " + counter + ", userName: " + userName
                                            + ", groupList: " + groupList);
                                }
                                if (counter == 2000) {
                                    LOG.info(
                                            "===> 2000 user records have been synchronized so far. From now on, only a summary progress log will be written for every 100 users. To continue to see detailed log for every user, please enable Trace level logging. <===");
                                }
                            } else {
                                if (LOG.isTraceEnabled()) {
                                    LOG.trace("Updating user count: " + counter + ", userName: " + userName
                                            + ", groupList: " + groupList);
                                } else {
                                    if (counter % 100 == 0) {
                                        LOG.info("Synced " + counter + " users till now");
                                    }
                                }
                            }
                        } else {
                            // If the user from the search result is present in the group user table,
                            // then addorupdate user to ranger admin.
                            LOG.debug("Chekcing if the user " + userFullName
                                    + " is part of the retrieved groups");
                            if (groupUserTable.containsColumn(userFullName)
                                    || groupUserTable.containsColumn(userName)) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(userFullName, transformUserName);
                                //Also update the username in the groupUserTable with the one from username attribute.
                                Map<String, String> userMap = groupUserTable.column(userFullName);
                                for (Map.Entry<String, String> entry : userMap.entrySet()) {
                                    LOG.debug("Updating groupUserTable " + entry.getValue() + " with: "
                                            + transformUserName + " for " + entry.getKey());
                                    groupUserTable.put(entry.getKey(), userFullName, transformUserName);
                                }
                            }
                        }

                    }

                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getUsers() completed with user count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getUsers() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getUsers() user count: " + counter);
            }
        }
        if (deltaSyncUserTime < highestdeltaSyncUserTime) {
            // Incrementing highestdeltaSyncUserTime (for AD) in order to avoid search record repetition for next sync cycle.
            deltaSyncUserTime = highestdeltaSyncUserTime + 1;
            // Incrementing the highest timestamp value (for Openldap) with 1sec in order to avoid search record repetition for next sync cycle.
            deltaSyncUserTimeStamp = dateFormat.format(new Date(highestdeltaSyncUserTime + 60l));
        }
    } finally {
        if (userSearchResultEnum != null) {
            userSearchResultEnum.close();
        }
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
}

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

private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException {
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/*from w  w  w . ja  v  a  2  s.c  o  m*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        } catch (ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet()) {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            Attribute attribute = ldapAttributes.get(attributeName);
            if (attribute != null) {
                String value = (String) attribute.get(0);
                if (value != null) {
                    properties.put(keyQName, value);
                }
            } else {
                String defaultValue = attributeDefaults.get(key);
                if (defaultValue != null) {
                    properties.put(keyQName, defaultValue);
                }
            }
        } else {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}

From source file:org.cggh.repo.security.sync.ldap.LDAPUserRegistry.java

protected NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException {
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/*  w ww.j  av  a2  s  .c  om*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        } catch (ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet()) {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            Attribute attribute = ldapAttributes.get(attributeName);
            if (attribute != null) {
                String value = (String) attribute.get(0);
                if (value != null) {
                    properties.put(keyQName, value);
                }
            } else {
                String defaultValue = attributeDefaults.get(key);
                if (defaultValue != null) {
                    properties.put(keyQName, defaultValue);
                }
            }
        } else {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}

From source file:com.surevine.ldap2alfresco.ProfileFieldTextConverter.java

/**
 * Encode some attributes as JSON./* w ww  .j a va2s. c  o  m*/
 * @param json The JSON object to insert into
 * @param attributes Collection of attributes
 */
public void toJson(final JSONObject json, final Attributes attributes) {

    Attribute attribute = attributes.get(attributeLabel);

    if (attribute == null) {
        LOGGER.debug("Missing attribute: " + attributeLabel);

        // just put an empty entry into the JSON
        try {
            if (allowMultiples) {
                json.put(jsonLabel, new JSONArray());
            } else {
                json.put(jsonLabel, "");
            }
        } catch (JSONException e) {
            logException(Level.ERROR, e);
        }

        return;
    }

    int numValues = attribute.size();

    if (numValues == 0) {
        LOGGER.error("Attribute " + attributeLabel + " contains no values");
        return;
    }

    try {
        if (allowMultiples) {

            JSONArray values = new JSONArray();

            NamingEnumeration<?> valueEnum = attribute.getAll();

            while (valueEnum.hasMore()) {
                String value = valueEnum.next().toString();
                if (value != null && value.length() > MAX_STRING_LENGTH) {
                    value = value.substring(0, MAX_STRING_LENGTH - 1);
                }
                values.put(value);
            }

            json.put(jsonLabel, values);
        } else {
            // expecting only one value
            if (numValues != 1) {
                LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues);
                return;
            }

            String value = attribute.get().toString();
            if (value != null && value.length() > MAX_STRING_LENGTH) {
                value = value.substring(0, MAX_STRING_LENGTH - 1);
            }

            json.put(jsonLabel, value);
        }
    } catch (NamingException e) {
        logException(Level.ERROR, e);
        return;
    } catch (JSONException e) {
        logException(Level.ERROR, e);
        return;
    }
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

private NodeDescription mapToNode(Map<String, String> attributeMapping, Map<String, String> attributeDefaults,
        SearchResult result) throws NamingException {
    NodeDescription nodeDescription = new NodeDescription(result.getNameInNamespace());
    Attributes ldapAttributes = result.getAttributes();

    // Parse the timestamp
    Attribute modifyTimestamp = ldapAttributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/* ww w . j ava 2 s. c  o  m*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
        } catch (ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    // Apply the mapped attributes
    PropertyMap properties = nodeDescription.getProperties();
    for (String key : attributeMapping.keySet()) {
        QName keyQName = QName.createQName(key, this.namespaceService);

        // cater for null
        String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            Attribute attribute = ldapAttributes.get(attributeName);
            String defaultAttribute = attributeDefaults.get(key);

            if (attribute != null) {
                String value = (String) attribute.get(0);
                if (value != null) {
                    properties.put(keyQName, value);
                }
            } else if (defaultAttribute != null) {
                properties.put(keyQName, defaultAttribute);
            } else {
                // Make sure that a 2nd sync, updates deleted ldap attributes(MNT-14026)
                properties.put(keyQName, null);
            }
        } else {
            String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                properties.put(keyQName, defaultValue);
            }
        }
    }
    return nodeDescription;
}

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

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

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

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

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

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

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

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

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

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

    return roles;
}

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

/**
 * {@inheritDoc}/*  w w w.  ja  va2  s .c o m*/
 */
@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:com.surevine.ldap2alfresco.ProfileFieldTelephoneConverter.java

/**
 * Encode some attributes as JSON.// w  w  w.  j  a  v  a 2  s .  c  o  m
 * @param json The JSON object to insert into
 * @param attributes Collection of attributes
 */
public void toJson(final JSONObject json, final Attributes attributes) {

    Attribute attribute = attributes.get(attributeLabel);

    if (attribute == null) {
        LOGGER.debug("Missing attribute: " + attributeLabel);

        // just put an empty entry into the JSON
        try {
            if (allowMultiples) {
                json.put(jsonLabel, new JSONArray());
            } else {
                JSONObject blank = new JSONObject();
                blank.put(JSON_LABEL_NETWORK, "");
                blank.put(JSON_LABEL_NUMBER, "");
                blank.put(JSON_LABEL_EXTENSION, "");
                json.put(jsonLabel, blank);
            }
        } catch (JSONException e) {
            logException(Level.ERROR, e);
        }

        return;
    }

    int numValues = attribute.size();

    if (numValues == 0) {
        LOGGER.error("Attribute " + attributeLabel + " contains no values");
        return;
    }

    try {
        if (allowMultiples) {

            JSONArray values = new JSONArray();

            NamingEnumeration<?> valueEnum = attribute.getAll();

            while (valueEnum.hasMore()) {
                String value = valueEnum.next().toString();
                JSONObject entry = decodePhoneNumber(value);

                if (entry == null) {
                    LOGGER.error("Failed to parse telephone number from :" + value);
                } else {
                    values.put(entry);
                }
            }

            json.put(jsonLabel, values);
        } else {
            // expecting only one value
            if (numValues != 1) {
                LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues);
                return;
            }

            String value = attribute.get().toString();
            JSONObject entry = decodePhoneNumber(value);

            if (entry == null) {
                LOGGER.error("Failed to parse telephone fields from :" + value);
            } else {
                json.put(jsonLabel, entry);
            }
        }
    } catch (NamingException e) {
        logException(Level.ERROR, e);
        return;
    } catch (JSONException e) {
        logException(Level.ERROR, e);
        return;
    }
}

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

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

            }

            attributes.close();

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