Example usage for javax.naming.directory DirContext getAttributes

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

Introduction

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

Prototype

public Attributes getAttributes(String name, String[] attrIds) throws NamingException;

Source Link

Document

Retrieves selected attributes associated with a named object.

Usage

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

private void populateDCMap() throws UserStoreException {
    try {// w  ww  .j a v  a  2s. c  o  m
        //get the directory context for DNS
        DirContext dnsContext = new InitialDirContext(environmentForDNS);
        //compose the DNS service to be queried
        String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName;
        //query the DNS
        Attributes attributes = dnsContext.getAttributes(DNSServiceName,
                new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME });
        Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME);
        //there can be multiple records with same domain name - get them all
        NamingEnumeration srvValues = srvRecords.getAll();
        dcMap = new TreeMap<Integer, SRVRecord>();
        //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap
        //int forcedPriority = 0;
        while (srvValues.hasMore()) {
            String value = srvValues.next().toString();
            SRVRecord srvRecord = new SRVRecord();
            String valueItems[] = value.split(" ");
            String priority = valueItems[0];
            if (priority != null) {
                int priorityInt = Integer.parseInt(priority);

                /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) {
                forcedPriority++;
                priorityInt = forcedPriority;
                }*/
                srvRecord.setPriority(priorityInt);
            } /* else {
              forcedPriority++;
              srvRecord.setPriority(forcedPriority);
              }*/
            String weight = valueItems[1];
            if (weight != null) {
                srvRecord.setWeight(Integer.parseInt(weight));
            }
            String port = valueItems[2];
            if (port != null) {
                srvRecord.setPort(Integer.parseInt(port));
            }
            String host = valueItems[3];
            if (host != null) {
                srvRecord.setHostName(host);
            }
            //we index dcMap on priority basis, therefore, priorities must be different
            dcMap.put(srvRecord.getPriority(), srvRecord);
        }
        //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the
        //host records for that
        for (SRVRecord srvRecord : dcMap.values()) {
            Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(),
                    new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME });
            Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME);
            //we know there is only one IP value for a given host. So we do just get, not getAll
            srvRecord.setHostIP((String) hostRecord.get());
        }
    } catch (NamingException e) {
        log.error("Error obtaining information from DNS Server" + e.getMessage(), e);
        throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e);
    }
}

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

/**
 *
 *///from w w w. j a  v  a 2 s .  c o 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:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 * @param groupDNs// w  ww.  j  av a  2s.co 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;
}