Example usage for javax.naming.directory Attributes get

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

Introduction

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

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///  ww w  . j av a  2  s .c  om
public void loadUserByAccountName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

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

    int field = 0;
    String accountName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField dataField : aUserBag.getFields()) {
        fieldName = dataField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = dataField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_COMMON_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from  w  w  w. ja va  2s  .c o m
public void loadUserByCommonName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

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

    int field = 0;
    String commonName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aUserBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_COMMON_NAME))
            commonName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (commonName == null) {
        String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *//*from  www.j  a  v  a 2s . co m*/
public void loadGroupByAccountName(DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

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

    int field = 0;
    String accountName = null;
    int attrCount = aGroupBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aGroupBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);
    String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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 ww . j  a  va 2  s  . c  o m*/
        log.debug("Listing users with Property: " + property + " SearchFilter: " + searchFilter);
    }

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

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

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

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

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

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

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

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

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

/**
 * @param groupDNs// w ww . ja  va  2 s .  c  o  m
 * @return
 * @throws UserStoreException
 */
private List<String> getGroupNameAttributeValuesOfGroups(List<LdapName> groupDNs) throws UserStoreException {
    log.debug("GetGroupNameAttributeValuesOfGroups with DN");
    boolean debug = log.isDebugEnabled();
    // get the DNs of the groups to which user belongs to, as per the search
    // parameters
    String groupNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    String[] returnedAttributes = { groupNameAttribute };
    List<String> groupNameAttributeValues = new ArrayList<String>();
    DirContext dirContext = null;
    try {
        dirContext = this.connectionSource.getContext();

        for (LdapName group : groupDNs) {
            if (!isInSearchBase(group, new LdapName(groupSearchBase))) {
                // ignore those groups outside the group search base
                continue;
            }
            if (debug) {
                log.debug("Using DN: " + group);
            }

            Rdn rdn = group.getRdn(group.getRdns().size() - 1);
            // get the last element of the RDNs.

            if (rdn.getType().equalsIgnoreCase(groupNameAttribute)) {
                /*
                * Checking to see if the required information can be retrieved from the RDN
                * If so, we can add that value and continue without creating an LDAP context
                * Connection
                * */
                groupNameAttributeValues.add(rdn.getValue().toString());
                continue;
            }

            Attributes groupAttributes = dirContext.getAttributes(group, returnedAttributes);
            if (groupAttributes != null) {
                Attribute groupAttribute = groupAttributes.get(groupNameAttribute);
                if (groupAttribute != null) {
                    String groupNameAttributeValue = (String) groupAttribute.get();
                    if (debug) {
                        log.debug(groupNameAttribute + " : " + groupNameAttributeValue);
                    }
                    groupNameAttributeValues.add(groupNameAttributeValue);
                }
            }
        }
    } catch (UserStoreException e) {
        String errorMessage = "Error in getting group name attribute values of groups";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        String errorMessage = "Error in getting group name attribute values of groups";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }
    return groupNameAttributeValues;
}

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

/**
 *
 *//*from   w ww .  j  av a  2  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  www  .  j av  a2 s .co  m*/
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;
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

protected void importGroups(LDAPImportContext ldapImportContext, Attributes userAttributes, User user)
        throws Exception {

    Properties groupMappings = ldapImportContext.getGroupMappings();

    String groupMappingsUser = groupMappings.getProperty("user");

    Set<Long> newUserGroupIds = new LinkedHashSet<>();

    LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
            .getConfiguration(ldapImportContext.getCompanyId(), ldapImportContext.getLdapServerId());

    if (Validator.isNotNull(groupMappingsUser) && ldapServerConfiguration.groupSearchFilterEnabled()) {

        String baseDN = ldapServerConfiguration.baseDN();

        StringBundler sb = new StringBundler(9);

        sb.append(StringPool.OPEN_PARENTHESIS);
        sb.append(StringPool.AMPERSAND);

        String groupSearchFilter = ldapServerConfiguration.groupSearchFilter();

        LDAPUtil.validateFilter(groupSearchFilter, "LDAPServerConfiguration.groupSearchFilter");

        sb.append(groupSearchFilter);//w w w.j a v  a 2 s  . c  o m

        sb.append(StringPool.OPEN_PARENTHESIS);
        sb.append(groupMappingsUser);
        sb.append(StringPool.EQUAL);

        Binding binding = _portalLDAP.getUser(ldapImportContext.getLdapServerId(),
                ldapImportContext.getCompanyId(), user.getScreenName(), user.getEmailAddress());

        String fullUserDN = binding.getNameInNamespace();

        sb.append(escapeValue(fullUserDN));

        sb.append(StringPool.CLOSE_PARENTHESIS);
        sb.append(StringPool.CLOSE_PARENTHESIS);

        byte[] cookie = new byte[0];

        while (cookie != null) {
            List<SearchResult> searchResults = new ArrayList<>();

            String groupMappingsGroupName = GetterUtil.getString(groupMappings.getProperty("groupName"));

            groupMappingsGroupName = StringUtil.toLowerCase(groupMappingsGroupName);

            cookie = _portalLDAP.searchLDAP(ldapImportContext.getCompanyId(),
                    ldapImportContext.getLdapContext(), cookie, 0, baseDN, sb.toString(),
                    new String[] { groupMappingsGroupName }, searchResults);

            for (SearchResult searchResult : searchResults) {
                String fullGroupDN = searchResult.getNameInNamespace();

                newUserGroupIds = importGroup(ldapImportContext, fullGroupDN, user, newUserGroupIds);
            }
        }
    } else {
        Properties userMappings = ldapImportContext.getUserMappings();

        String userMappingsGroup = userMappings.getProperty("group");

        if (Validator.isNull(userMappingsGroup)) {
            if (_log.isInfoEnabled()) {
                _log.info("Skipping group import because no mappings for LDAP "
                        + "groups were specified in user mappings " + userMappings);
            }

            return;
        }

        Attribute userGroupAttribute = userAttributes.get(userMappingsGroup);

        if (userGroupAttribute == null) {
            return;
        }

        for (int i = 0; i < userGroupAttribute.size(); i++) {
            String fullGroupDN = (String) userGroupAttribute.get(i);

            newUserGroupIds = importGroup(ldapImportContext, fullGroupDN, user, newUserGroupIds);
        }
    }

    addUserGroupsNotAddedByLDAPImport(user.getUserId(), newUserGroupIds);

    Set<Long> oldUserGroupIds = new LinkedHashSet<>();

    List<UserGroup> oldUserGroups = _userGroupLocalService.getUserUserGroups(user.getUserId());

    for (UserGroup oldUserGroup : oldUserGroups) {
        oldUserGroupIds.add(oldUserGroup.getUserGroupId());
    }

    if (!oldUserGroupIds.equals(newUserGroupIds)) {
        long[] userGroupIds = ArrayUtil.toLongArray(newUserGroupIds);

        _userGroupLocalService.setUserUserGroups(user.getUserId(), userGroupIds);
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from   www .  j a v a  2s.c om
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Create attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Create value: ***");
                    } else {
                        log.debug("Create value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute.
                    // Sun:
                    //   [LDAP: error code 20 - Attribute Or Value Exists]
                    if (e.getMessage().startsWith("[LDAP: error code 20 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_CREATE_OK;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            if (unicodePwd) {
                Enumeration enumeration = attrs.getIDs();
                while (enumeration.hasMoreElements()) {
                    String id = (String) enumeration.nextElement();
                    if ("unicodePwd".equalsIgnoreCase(id)) {
                        Attribute attr = attrs.get(id);
                        for (int i = 0; i < attr.size(); i++) {
                            attr.set(i, encodeUnicodePwd(attr.get(i)));
                        }
                    }
                }
            }
            dirContext = getDirContext(paramValueMap);
            dirContext.bind(entryName, null, attrs);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
            if (log.isDebugEnabled())
                log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: "
                        + e.getMessage());
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                return DEFAULT_RESULT_CREATE_OK;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }

}