Example usage for javax.naming.directory SearchControls setReturningAttributes

List of usage examples for javax.naming.directory SearchControls setReturningAttributes

Introduction

In this page you can find the example usage for javax.naming.directory SearchControls setReturningAttributes.

Prototype

public void setReturningAttributes(String[] attrs) 

Source Link

Document

Specifies the attributes that will be returned as part of the search.

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 aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from  ww  w .ja v  a 2 s .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.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }/*from   w w w. j  av a  2  s  .c  o m*/
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query) {
    LOGGER.debug("Building user searcher for query {}", query);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    userSearchCtls.setReturningAttributes(this.userKeys.getFirst());
    // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
    userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);

    return (ctx) -> {
        try {/*www .  j a v a  2  s  .c  o m*/
            final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query,
                    userSearchCtls);
            return results;
        } catch (final NamingException e) {
            throw new AlfrescoRuntimeException("Failed to import people.", e);
        }
    };
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query) {
    LOGGER.debug("Building group searcher for query {}", query);

    final SearchControls groupSearchCtls = new SearchControls();
    groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst());
    // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control
    groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0);

    return (ctx) -> {
        try {//from  w  w  w  .  ja va2  s . c o m
            final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query,
                    groupSearchCtls);
            return results;
        } catch (final NamingException e) {
            throw new AlfrescoRuntimeException("Failed to import groups.", e);
        }
    };
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*from  w  w  w  .  j a v  a 2  s. c  o  m*/
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws AlfrescoRuntimeException
 */
protected void processQuery(final SearchCallback callback, final String searchBase, final String query,
        final String[] returningAttributes) {
    final SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "Processing query {}\nSearch base: {}\n\rReturn result limit: {}\n\tDereflink: {}\n\rReturn named object: {}\n\tTime limit for search: {}\n\tAttributes to return: {} items\n\tAttributes: {}",
                query, searchBase, searchControls.getCountLimit(), searchControls.getDerefLinkFlag(),
                searchControls.getReturningObjFlag(), searchControls.getTimeLimit(),
                String.valueOf(returningAttributes.length), Arrays.toString(returningAttributes));
    }

    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                this.commonCloseSearchResult(result);
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (final NamingException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (final ParseException e) {
        final Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(LookupRequest lookupRequest, LookupResponse lookupResponse) {

    Ldap ldap = null;/*from  w  ww  . j  a  v a 2 s . com*/
    try {
        // will not return AD Range option attrs
        // Attributes attributes = ldap.getAttributes(escapedDn, retAttrs);

        SearchFilter sf = new SearchFilter();
        sf.setFilter("objectclass=*");
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);

        // This lookup requests attributes defined for *all* objects.
        // Perhaps there should be two searches, one for the identifier
        // and a second for attributes.
        String[] retAttrs = getPSP().getNames(getId(), lookupRequest.getReturnData()).toArray(new String[] {});
        sc.setReturningAttributes(retAttrs);

        // TODO logging
        String dn = lookupRequest.getPsoID().getID();
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);

        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(lookupRequest));
        Iterator<SearchResult> searchResults = ldap.search(escapedDn, sf, sc);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(lookupRequest));

        if (!searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
            return;
        }

        SearchResult result = searchResults.next();

        if (searchResults.hasNext()) {
            fail(lookupResponse, ErrorCode.CUSTOM_ERROR, "More than one result found.");
            return;
        }
        Attributes attributes = result.getAttributes();

        // return attributes in order defined by config
        OrderedLdapBeanFactory orderedLdapBeanFactory = new OrderedLdapBeanFactory();
        // sort values
        SortedLdapBeanFactory sortedLdapBeanFactory = new SortedLdapBeanFactory();

        LdapAttributes ldapAttributes = orderedLdapBeanFactory.newLdapAttributes();
        for (String retAttr : retAttrs) {
            Attribute attr = attributes.get(retAttr);
            if (attr != null) {
                LdapAttribute ldapAttribute = sortedLdapBeanFactory.newLdapAttribute();
                ldapAttribute.setAttribute(attr);
                ldapAttributes.addAttribute(ldapAttribute);
            }
        }

        LdapEntry entry = sortedLdapBeanFactory.newLdapEntry();
        entry.setDn(dn);
        entry.setLdapAttributes(ldapAttributes);

        if (this.isLogLdif()) {
            LdapResult lr = sortedLdapBeanFactory.newLdapResult();
            lr.addEntry(entry);
            LdifResultConverter lrc = new LdifResultConverter();
            LOG.info("Target '{}' - LDIF\n{}", getId(), lrc.toLdif(lr));
        }

        // build pso
        lookupResponse.setPso(getPSO(entry, lookupRequest.getReturnData()));

    } catch (NameNotFoundException e) {
        fail(lookupResponse, ErrorCode.NO_SUCH_IDENTIFIER);
    } catch (LdapPoolException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (InvalidNameException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NamingException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (DSMLProfileException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(lookupResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        if (ldap != null) {
            ldapPool.checkIn(ldap);
        }
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

/**
 *
 * {@inheritDoc}//from   ww  w . j av a 2s  .  c  om
 */
@Override
public String resolveDistinguishedName(final String userId, final AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    LOGGER.debug("resolveDistinguishedName userId: {}", userId);

    final SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    final String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName
            + "= userId))";

    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;

    InitialDirContext ctx = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

        // Execute the user query with an additional condition that ensures only the user with the required ID is
        // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

        searchResults = ctx.search(this.userSearchBase,
                "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId },
                userSearchCtls);

        if (searchResults.hasMore()) {
            result = searchResults.next();
            final Attributes attributes = result.getAttributes();
            final Attribute uidAttribute = attributes.get(this.userIdAttributeName);
            if (uidAttribute == null) {
                if (this.errorOnMissingUID) {
                    throw new AlfrescoRuntimeException(
                            "User returned by user search does not have mandatory user id attribute "
                                    + attributes);
                } else {
                    LOGGER.warn("User returned by user search does not have mandatory user id attribute {}",
                            attributes);
                }
            }
            // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
            // only resolve this user if the user ID matches
            else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                final String name = result.getNameInNamespace();

                this.commonCloseSearchResult(result);
                result = null;
                return name;
            }

            this.commonCloseSearchResult(result);
            result = null;
        }

        final Object[] args = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args);

        throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic);
    } catch (final NamingException e) {
        // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory
        final Object[] args1 = { userId, query };
        diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);

        // failed to search
        final Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        this.commonAfterQueryCleanup(searchResults, result, ctx);
    }
}

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

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback//from w  w  w  . jav a2s.c  om
 *            the callback
 * @param searchBase
 *            the base DN for the search
 * @param query
 *            the query
 * @param returningAttributes
 *            the attributes to include in search results
 * @throws org.alfresco.error.AlfrescoRuntimeException
 */
private void processQuery(SearchCallback callback, String searchBase, String query,
        String[] returningAttributes) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);
    if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
        LDAPMultiBaseUserRegistry.logger.debug("Processing query");
        LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPMultiBaseUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPMultiBaseUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPMultiBaseUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPMultiBaseUserRegistry.logger
                .debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPMultiBaseUserRegistry.logger.debug("        Attribute: " + ra);
        }
    }
    InitialDirContext ctx = null;
    NamingEnumeration<SearchResult> searchResults = null;
    SearchResult result = null;
    try {
        ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize);
        do {
            searchResults = ctx.search(searchBase, query, searchControls);

            while (searchResults.hasMore()) {
                result = searchResults.next();
                callback.process(result);

                // Close the contexts, see ALF-20682
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
                result = null;
            }
        } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize));
    } catch (NamingException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } catch (ParseException e) {
        Object[] params = { e.getLocalizedMessage() };
        throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e);
    } finally {
        if (result != null) {
            try {
                Context resultCtx = (Context) result.getObject();
                if (resultCtx != null) {
                    resultCtx.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
    }
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(SearchRequest searchRequest, SearchResponse searchResponse) {

    // query//w w  w  . j a  va 2 s . com
    Query query = searchRequest.getQuery();

    // query filter
    // TODO support QueryClause other than our own
    String filter = null;
    for (QueryClause queryClause : query.getQueryClauses()) {
        if (queryClause instanceof HasReference) {
            HasReference hasReference = (HasReference) queryClause;
            if (hasReference.getTypeOfReference() != null && hasReference.getToPsoID() != null
                    && hasReference.getToPsoID().getID() != null) {
                filter = "(" + hasReference.getTypeOfReference() + "=" + hasReference.getToPsoID().getID()
                        + ")";
                // TODO what do we do with hasReference.getReferenceData(); ?
            }
        } else if (queryClause instanceof Filter) {
            FilterItem filterItem = ((Filter) queryClause).getItem();
            if (filterItem instanceof EqualityMatch) {
                String name = ((EqualityMatch) filterItem).getName();
                String value = ((EqualityMatch) filterItem).getValue().getValue();
                filter = "(" + name + "=" + value + ")";
            }
        } else {
            fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "Unsupported query.");
            return;
        }
    }
    if (DatatypeHelper.isEmpty(filter)) {
        fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "A filter is required.");
        return;
    }

    // query base
    if (query.getBasePsoID() == null || query.getBasePsoID().getID() == null) {
        fail(searchResponse, ErrorCode.MALFORMED_REQUEST, "A basePsoID is required.");
        return;
    }
    String base = query.getBasePsoID().getID();

    SearchControls searchControls = new SearchControls();

    // query scope
    Scope scope = query.getScope();
    if (scope != null) {
        searchControls.setSearchScope(PSPUtil.getScope(scope));
    }

    ReturnData returnData = searchRequest.getReturnData();
    if (returnData == null) {
        returnData = ReturnData.EVERYTHING;
    }

    // attributes to return
    String[] retAttrs = getPSP().getNames(getId(), returnData).toArray(new String[] {});
    searchControls.setReturningAttributes(retAttrs);

    Ldap ldap = null;
    try {
        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Search will return attributes '{}'", getId(), Arrays.asList(retAttrs));
        LOG.debug("Target '{}' - Searching '{}'", getId(), PSPUtil.toString(searchRequest));
        Iterator<SearchResult> searchResults = ldap.search(base, new SearchFilter(filter), searchControls);
        LOG.debug("Target '{}' - Searched '{}'", getId(), PSPUtil.toString(searchRequest));

        SortedLdapBeanFactory ldapBeanFactory = new SortedLdapBeanFactory();
        LdapResult ldapResult = ldapBeanFactory.newLdapResult();
        ldapResult.addEntries(searchResults);

        Collection<LdapEntry> entries = ldapResult.getEntries();
        LOG.debug("Target '{}' - Search found {} entries.", getId(), entries.size());
        for (LdapEntry entry : entries) {
            searchResponse.addPSO(getPSO(entry, returnData));
        }

        if (logLdif) {
            Ldif ldif = new Ldif();
            LOG.info("Target '{}' - LDIF\n{}", getId(), ldif.createLdif(ldapResult));
        }

    } catch (NameNotFoundException e) {
        fail(searchResponse, ErrorCode.NO_SUCH_IDENTIFIER, e);
    } catch (NamingException e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (LdapPoolException e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (Spml2Exception e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(searchResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        ldapPool.checkIn(ldap);
    }

}

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

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/*from  w  w  w . ja v  a 2s.co m*/
    SearchControls userSearchCtls = new SearchControls();
    userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868
    userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName });

    InitialDirContext ctx = null;

    for (String userSearchBase : this.userSearchBases) {

        String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))";

        NamingEnumeration<SearchResult> searchResults = null;
        SearchResult result = null;

        try {
            ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic);

            // Execute the user query with an additional condition that ensures only the user with the required ID is
            // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation

            searchResults = ctx.search(userSearchBase,
                    "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))",
                    new Object[] { userId }, userSearchCtls);

            if (searchResults.hasMore()) {
                result = searchResults.next();
                Attributes attributes = result.getAttributes();
                Attribute uidAttribute = attributes.get(this.userIdAttributeName);
                if (uidAttribute == null) {
                    if (this.errorOnMissingUID) {
                        throw new AlfrescoRuntimeException(
                                "User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    } else {
                        LDAPMultiBaseUserRegistry.logger
                                .warn("User returned by user search does not have mandatory user id attribute "
                                        + attributes);
                    }
                }
                // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will
                // only resolve this user if the user ID matches
                else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) {
                    String name = result.getNameInNamespace();

                    // Close the contexts, see ALF-20682
                    Context context = (Context) result.getObject();
                    if (context != null) {
                        context.close();
                    }
                    result = null;
                    return name;
                }

                // Close the contexts, see ALF-20682
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
                result = null;
            }
        } catch (NamingException e) {
            // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory

            Object[] args1 = { userId, query };
            diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1);
        }

        if (result != null) {
            try {
                Context context = (Context) result.getObject();
                if (context != null) {
                    context.close();
                }
            } catch (Exception e) {
                logger.debug("error when closing result block context", e);
            }
        }
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (Exception e) {
                logger.debug("error when closing searchResults context", e);
            }
        }
    }

    if (ctx != null) {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.debug("error when closing ldap context", e);
        }
    }

    // failed to search
    //        Object[] args = {e.getLocalizedMessage()};
    throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic);
}