Example usage for javax.naming.directory SearchResult getAttributes

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

Introduction

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

Prototype

public Attributes getAttributes() 

Source Link

Document

Retrieves the attributes in this search result.

Usage

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeGroups(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws NamingException {
    int changesCount = 0;
    List<Group> existingGroupsList = executorDao.getAllGroups();
    Map<String, Group> existingGroupsByLdapNameMap = Maps.newHashMap();
    for (Group group : existingGroupsList) {
        if (!Strings.isNullOrEmpty(group.getLdapGroupName())) {
            existingGroupsByLdapNameMap.put(group.getLdapGroupName(), group);
        }//  www.  jav a  2 s .c om
    }
    Set<Group> ldapGroupsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        Set<Executor> ldapExecutors = executorDao.getGroupChildren(importGroup);
        for (Executor executor : ldapExecutors) {
            if (executor instanceof Group) {
                ldapGroupsToDelete.add((Group) executor);
            }
        }
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    Map<String, SearchResult> groupResultsByDistinguishedName = Maps.newHashMap();
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_GROUP_FILTER, controls);
        while (list.hasMore()) {
            SearchResult searchResult = list.next();
            if (searchResult.getAttributes().get(ATTR_GROUP_MEMBER) == null) {
                continue;
            }
            groupResultsByDistinguishedName.put(searchResult.getNameInNamespace(), searchResult);
        }
    }
    for (SearchResult searchResult : groupResultsByDistinguishedName.values()) {
        String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
        String description = getStringAttribute(searchResult,
                LdapProperties.getSynchronizationGroupDescriptionAttribute());
        ToStringHelper toStringHelper = MoreObjects.toStringHelper("group info");
        toStringHelper.add("name", name).add("description", description).omitNullValues();
        log.debug("Read " + toStringHelper.toString());
        Group group = existingGroupsByLdapNameMap.get(name);
        if (group == null) {
            if (!LdapProperties.isSynchronizationCreateExecutors()) {
                continue;
            }
            group = new Group(name, description);
            group.setLdapGroupName(name);
            log.info("Creating " + group);
            executorDao.create(group);
            executorDao.addExecutorsToGroup(Lists.newArrayList(group), importGroup);
            permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), group);
            changesCount++;
        } else {
            ldapGroupsToDelete.remove(group);
            if (LdapProperties.isSynchronizationUpdateExecutors()) {
                List<IChange> changes = Lists.newArrayList();
                if (isAttributeNeedsChange(description, group.getDescription())) {
                    changes.add(new AttributeChange("description", group.getDescription(), description));
                    group.setDescription(description);
                    executorDao.update(group);
                }
                if (executorDao.removeExecutorFromGroup(group, wasteGroup)) {
                    changes.add(new Change("waste group removal"));
                }
                if (executorDao.addExecutorToGroup(group, importGroup)) {
                    changes.add(new Change("import group addition"));
                }
                if (!changes.isEmpty()) {
                    log.info("Updating " + group + ": " + changes);
                    changesCount++;
                }
            }
        }

        Set<Actor> actorsToDelete = Sets.newHashSet(executorDao.getGroupActors(group));
        Set<Actor> actorsToAdd = Sets.newHashSet();
        Set<Actor> groupTargetActors = Sets.newHashSet();
        fillTargetActorsRecursively(dirContext, groupTargetActors, searchResult,
                groupResultsByDistinguishedName, actorsByDistinguishedName);
        for (Actor targetActor : groupTargetActors) {
            if (!actorsToDelete.remove(targetActor)) {
                actorsToAdd.add(targetActor);
            }
        }
        if (actorsToAdd.size() > 0) {
            log.info("Adding to " + group + ": " + actorsToAdd);
            executorDao.addExecutorsToGroup(actorsToAdd, group);
            changesCount++;
        }
        if (actorsToDelete.size() > 0) {
            executorDao.removeExecutorsFromGroup(Lists.newArrayList(actorsToDelete), group);
            changesCount++;
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapGroupsToDelete.size() > 0) {
        executorDao.removeExecutorsFromGroup(ldapGroupsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapGroupsToDelete, wasteGroup);
        log.info("Inactivating " + ldapGroupsToDelete);
        changesCount += ldapGroupsToDelete.size();
    }
    return changesCount;
}

From source file:ru.efo.security.ADUserDetailsService.java

private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles)
        throws NamingException {
    if (memberOf != null) {
        for (int i = 0; i < memberOf.size(); i++) {
            Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN");
            if (attr != null) {
                final String role = attr.get().toString();
                if (rolesMapping != null) {
                    for (String key : rolesMapping.keySet()) {
                        if (role.matches(rolesMapping.get(key))) {
                            if (logger.isLoggable(Level.FINE)) {
                                if (!roles.contains(key)) {
                                    logger.log(Level.FINE, "Role: " + key);
                                }//from   ww w  . jav  a  2s .c o m
                            }
                            roles.add(key);
                        }
                    }
                } else {
                    final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix)
                            + role.toUpperCase().replaceAll("(\\s|-)+", "_");
                    if (logger.isLoggable(Level.FINE)) {
                        if (!roles.contains(role)) {
                            logger.log(Level.FINE, "Role: " + roleWithPrefix);
                        }
                    }
                    roles.add(roleWithPrefix);
                }
                groups.add(role);

                if (recursiveRoleSearch) {
                    SearchControls controls = new SearchControls();
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    NamingEnumeration<SearchResult> renum = context.search(
                            groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")",
                            controls);
                    if (renum.hasMore()) {
                        SearchResult searchResult = renum.next();
                        attr = searchResult.getAttributes().get("memberOf");
                        describeRoles(context, attr, groups, roles);
                    }
                }
            }
        }
    }
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the field value of the specified field for the specified id. 
 * @see IExternalStorage#getField(java.lang.String, java.lang.String)
 *///from  ww w.j a  v a  2 s .  c  o m
public Object getField(String id, String field) throws UserException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    Object oValue = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

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

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attribute '");
            sbFailed.append(field);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_INTERNAL, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration oAttrEnum = oAttributes.getAll();
        if (oAttrEnum.hasMore()) {
            Attribute oAttribute = (Attribute) oAttrEnum.next();
            oValue = oAttribute.get();
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.error("Could not retrieve field: " + field, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return oValue;
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups/* w  ww  .  j  a  v a2s.  c o m*/
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean,
        String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap,
        Map<String, String> groups) throws Exception {
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        LOGGER.debug(
                "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER);
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
    if (baseContext == null) {
        LOGGER.warn("Context is null for baseURL " + baseURL);
        return ldapGroupsMap;
    }
    for (Map.Entry<String, String> groupEntry : groups.entrySet()) {
        String groupName = groupEntry.getKey();
        String groupDN = groupEntry.getValue();
        int index = groupDN.indexOf(",");
        if (index != -1) {
            String searchPart = groupDN.substring(0, index);
            String searchStr = "(" + searchPart + ")";
            String parentDNPart = groupDN.substring(index + 1);
            LdapContext context = (LdapContext) baseContext.lookup(parentDNPart);
            if (context == null) {
                LOGGER.warn("Context is null after lookup for " + parentDNPart);
                continue;
            }
            int recordCount = 0;
            SearchControls ctls = null;
            try {
                // Activate paged results
                int pageSize = 5;
                byte[] cookie = null;
                context.setRequestControls(
                        new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
                int total;
                // Control the search
                ctls = new SearchControls();
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                        + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can
                                                                                                                                                                             // handle anyways
                do {
                    /* perform the search */
                    NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls);
                    /*
                     * for each entry print out name + all attrs and values
                     */
                    while (results != null && results.hasMore()) {
                        SearchResult searchResult = (SearchResult) results.next();
                        // Attributes atrs = sr.getAttributes();
                        Attributes attributes = searchResult.getAttributes();
                        if (attributes == null) {
                            LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                            continue;
                        }
                        TPersonBean personBean = new TPersonBean();
                        try {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                            Attribute memberAttribute = attributes.get(groupMemberAttributName);
                            if (memberAttribute != null) {
                                NamingEnumeration<?> members = memberAttribute.getAll();
                                while (members != null && members.hasMore()) {
                                    String memberSearchResult = (String) members.next();
                                    List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                    if (memberDNList == null) {
                                        memberDNList = new ArrayList<String>();
                                        groupToMemberReferencesMap.put(groupName, memberDNList);
                                    }
                                    LOGGER.debug("Member found: " + memberSearchResult);
                                    memberDNList.add(memberSearchResult);
                                }
                            } else {
                                LOGGER.info("Could not find value(s) for group member attribute "
                                        + groupMemberAttributName + " for group " + groupName);
                            }
                            LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                            LOGGER.debug("Processed group " + groupName);
                        } catch (Exception e) {
                            LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                            LOGGER.warn(
                                    "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Stack trace:", e);
                            }
                        }
                        ++recordCount;
                    }
                    // Examine the paged results control response
                    Control[] controls = context.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) {
                                    LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                            + ") *****************\n");
                                } else {
                                    LOGGER.debug("***************** END-OF-PAGE "
                                            + "(total: unknown) ***************\n");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOGGER.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    context.setRequestControls(
                            new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

                } while (cookie != null);
            } catch (SizeLimitExceededException sle) {
                if (recordCount < ctls.getCountLimit()) {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
                    LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                            + sle.getMessage());
                    LOGGER.error(
                            "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
                } else {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                            + recordCount + ").");
                    LOGGER.error(
                            "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
                }
                LOGGER.error("The LDAP synchronization is most likely incomplete.");
            } catch (NamingException e) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            } catch (IOException ie) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(ie));
            } finally {
                context.close();
            }
        }
    }
    return ldapGroupsMap;
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * //from   w  w w. j  a v  a 2s.  com
 * @see edu.internet2.middleware.subject.provider.BaseSourceAdapter#search(java.lang.String)
 */
@Override
public Set<Subject> search(String searchValue) {
    Set<Subject> result = new HashSet<Subject>();
    Search search = getSearch("search");
    if (search == null) {
        log.error("searchType: \"search\" not defined.");
        return result;
    }
    String[] attributeNames = { this.nameAttributeName, this.subjectIDAttributeName,
            this.descriptionAttributeName };
    NamingEnumeration ldapResults = getLdapResults(search, searchValue, attributeNames);
    if (ldapResults == null) {
        return result;
    }
    try {
        while (ldapResults.hasMore()) {
            SearchResult si = (SearchResult) ldapResults.next();
            Attributes attributes1 = si.getAttributes();
            Subject subject = createSubject(attributes1);
            result.add(subject);
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return result;
}

From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java

protected Attributes getLdapUnique(Search search, String searchValue, String[] attributeNames)
        throws SubjectNotFoundException, SubjectNotUniqueException {
    Attributes attributes = null;
    Iterator<SearchResult> results = getLdapResults(search, searchValue, attributeNames);

    if (results == null || !results.hasNext()) {
        String errMsg = "No results: " + search.getSearchType() + " filter:" + search.getParam("filter")
                + " searchValue: " + searchValue;
        throw new SubjectNotFoundException(errMsg);
    }/*from  ww w . j a  v  a  2  s . c  o m*/

    SearchResult si = (SearchResult) results.next();
    attributes = si.getAttributes();
    if (results.hasNext()) {
        si = (SearchResult) results.next();
        if (!multipleResults) {
            String errMsg = "Search is not unique:" + si.getName() + "\n";
            throw new SubjectNotUniqueException(errMsg);
        }
        Attributes attr = si.getAttributes();
        NamingEnumeration<? extends Attribute> n = attr.getAll();
        try {
            while (n.hasMore()) {
                Attribute a = n.next();
                log.debug("checking attribute " + a.getID());
                if (attributes.get(a.getID()) == null) {
                    log.debug("adding " + a.getID());
                    attributes.put(a);
                }
            }
        } catch (NamingException e) {
            log.error("ldap excp: " + e);
        }
    }
    return attributes;
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 */// w  w  w.  j av  a 2  s .  c om
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private String getStringAttribute(SearchResult searchResult, String name) throws NamingException {
    if (Utils.isNullOrEmpty(name)) {
        return null;
    }/*from   ww  w.  j  av a2  s  .com*/
    Attribute attribute = searchResult.getAttributes().get(name);
    if (attribute != null) {
        return attribute.get().toString();
    }
    return null;
}

From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the values of the specified fields for the supplied id. 
 * @see IExternalStorage#getFields(java.lang.String, java.util.List)
 *///from www .  ja v a2  s  .  c o  m
public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException {
    Hashtable<String, Object> htReturn = new Hashtable<String, Object>();
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] saFields = fields.toArray(new String[0]);
        oScope.setReturningAttributes(saFields);

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes '");
            sbFailed.append(fields);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration neAttributes = oAttributes.getAll();
        while (neAttributes.hasMore()) {
            Attribute oAttribute = (Attribute) neAttributes.next();
            String sAttributeName = oAttribute.getID();

            if (oAttribute.size() > 1) {
                Vector<Object> vValue = new Vector<Object>();
                NamingEnumeration neAttribute = oAttribute.getAll();
                while (neAttribute.hasMore())
                    vValue.add(neAttribute.next());

                htReturn.put(sAttributeName, vValue);
            } else {
                Object oValue = oAttribute.get();
                if (oValue == null)
                    oValue = "";
                htReturn.put(sAttributeName, oValue);
            }
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields: " + fields, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return htReturn;
}

From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java

/**
 * {@inheritDoc}/*from  w  w w  .java2s  .co m*/
 */
@Override
public Set search(String searchValue) {
    Comparator cp = new LdapComparator();
    TreeSet result = new TreeSet(cp);
    Search search = getSearch("search");
    if (search == null) {
        log.error("searchType: \"search\" not defined.");
        return result;
    }
    Search searchA = getSearch("searchAttributes");
    boolean noAttrSearch = true;
    if (searchA != null)
        noAttrSearch = false;

    Iterator<SearchResult> ldapResults = getLdapResults(search, searchValue, allAttributeNames);
    if (ldapResults == null) {
        return result;
    }
    while (ldapResults.hasNext()) {
        SearchResult si = (SearchResult) ldapResults.next();
        Attributes attributes = si.getAttributes();
        Subject subject = createSubject(attributes);
        if (noAttrSearch)
            ((LdapSubject) subject).setAttributesGotten(true);
        result.add(subject);
    }

    log.debug("set has " + result.size() + " subjects");
    if (result.size() > 0)
        log.debug("first is " + ((Subject) result.first()).getName());
    return result;
}