Example usage for javax.naming.directory SearchResult getObject

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

Introduction

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

Prototype


public Object getObject() 

Source Link

Document

Retrieves the object bound to the name of this binding.

Usage

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Retrieves the roles for the from the identity provider.
 *
 * @param username the user to get the roles for
 * @return the list of roles for the user
 * @throws PortalServiceException for any errors encountered
 */// w  w w.j  av a  2  s . c o m
@SuppressWarnings("rawtypes")
public List<String> findRoles(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // Search for groups the user belongs to in order to get their names
        // Create the search controls
        SearchControls groupsSearchCtls = new SearchControls();

        // Specify the search scope
        groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Specify the attributes to return
        String groupsReturnedAtts[] = { "cn" };
        groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);

        String userDn = MessageFormat.format(userDNPattern, username);
        // Search for objects using the filter
        NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase,
                MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls);

        List<String> groups = new ArrayList<String>();
        // Loop through the search results
        while (groupsAnswer.hasMoreElements()) {

            SearchResult sr = (SearchResult) groupsAnswer.next();
            Attributes attrs = sr.getAttributes();

            if (attrs != null) {
                groups.add((String) attrs.get("cn").get());
            }

            if (sr.getObject() instanceof Context) {
                closeContext((Context) sr.getObject());
            }
        }
        return groups;
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

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

protected void commonCloseSearchResult(final SearchResult result) throws NamingException {
    // Close the contexts, see ALF-20682
    final Context context = (Context) result.getObject();
    if (context != null) {
        context.close();//w ww .j av a  2  s  .  c  om
    }
}

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

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*from ww w.java2s  .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 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:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }/* w  w  w  . j a  v  a 2 s  . c o  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);
}

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

public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic)
        throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("resolveDistinguishedName userId:" + userId);
    }// ww w. ja v a 2  s . c o  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 });

    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();
            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 {
                    LDAPUserRegistry.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;
        }

        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 (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);

        // failed to search
        Object[] args = { e.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e);
    } finally {
        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);
            }
        }
    }
}

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

/**
 * Invokes the given callback on each entry returned by the given query.
 * //from  w  w w.  j  a v  a  2  s .  c  om
 * @param callback
 *            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           
 */
private void processQuery(SearchCallback callback, String searchBase, String query,
        String[] returningAttributes) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(returningAttributes);
    if (LDAPUserRegistry.logger.isDebugEnabled()) {
        LDAPUserRegistry.logger.debug("Processing query");
        LDAPUserRegistry.logger.debug("Search base: " + searchBase);
        LDAPUserRegistry.logger.debug("    Return result limit: " + searchControls.getCountLimit());
        LDAPUserRegistry.logger.debug("    DerefLink: " + searchControls.getDerefLinkFlag());
        LDAPUserRegistry.logger.debug("    Return named object: " + searchControls.getReturningObjFlag());
        LDAPUserRegistry.logger.debug("    Time limit for search: " + searchControls.getTimeLimit());
        LDAPUserRegistry.logger.debug("    Attributes to return: " + returningAttributes.length + " items.");
        for (String ra : returningAttributes) {
            LDAPUserRegistry.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);
            }
            searchResults = null;
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
            }
        }
        try {
            callback.close();
        } catch (NamingException e) {
        }
    }
}

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

/**
 * Internal method extracted to avoid code duplication in AD search.
 *//* ww  w .  j av  a  2  s. c  om*/
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
        String base, String filter, Object[] params) throws NamingException {
    final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
    final DistinguishedName searchBaseDn = new DistinguishedName(base);
    final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params,
            buildControls(searchControls));

    if (logger.isDebugEnabled()) {
        logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn
                + "', filter = '" + filter + "'");
    }

    Set<DirContextOperations> results = new HashSet<DirContextOperations>();
    try {
        while (resultsEnum.hasMore()) {
            SearchResult searchResult = resultsEnum.next();
            DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
            Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");

            if (logger.isDebugEnabled()) {
                logger.debug("Found DN: " + dca.getDn());
            }
            results.add(dca);
        }
    } catch (PartialResultException e) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.info("Ignoring PartialResultException");
    }

    if (results.size() == 0) {
        throw new IncorrectResultSizeDataAccessException(1, 0);
    }

    if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }

    return results.iterator().next();
}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static void logLdap(Log plog, int level, int nth, Object dirEntry) throws NamingException {
    try {//from w  ww  .  j  a v a  2  s.  c  om
        if (dirEntry instanceof NamingEnumeration) {
            NamingEnumeration nameEnum = (NamingEnumeration) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "Naming Enumeration: " + nameEnum);
            try {
                int nthThis = 0;
                List nameList = new Vector(Collections.list(nameEnum));
                Collections.sort(nameList, new Comparator() {
                    public int compare(Object o1, Object o2) {
                        if (o1 instanceof Attribute) {
                            return String.CASE_INSENSITIVE_ORDER.compare(((Attribute) o1).getID(),
                                    ((Attribute) o2).getID());
                        }
                        return 0;
                    }
                });
                Iterator nameIter = nameList.iterator();
                while (nameIter.hasNext()) {
                    logLdap(plog, level + 1, nthThis++, nameIter.next());
                }
            } catch (NamingException ex) {
                plog.error("Exception iterating thru NamingEnumeration: " + ex.getMessage());
            }
        } else if (dirEntry instanceof Attribute) {
            Attribute dirAttr = (Attribute) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "Attribute: [" + dirAttr + "]");
        } else if (dirEntry instanceof DirContext) {
            DirContext lctx = (DirContext) dirEntry;
            JndiHelper.logLevel(plog, level, nth,
                    "LDAP Context: DN [" + lctx.getNameInNamespace() + "]" + " Attributes ==>");
            logLdap(plog, level, nth, lctx.getAttributes("").getAll());
        } else if (dirEntry instanceof SearchResult) {
            SearchResult sr = (SearchResult) dirEntry;
            JndiHelper.logLevel(plog, level, nth, "SearchResult: ClassName of Bound Object ["
                    + sr.getClassName() + "]" + " Name: [" + sr.getName() + "]" + " Bound Object ==>");
            //                sr.s
            logLdap(plog, level, nth, sr.getObject());
            logLdap(plog, level, nth, sr.getAttributes().getAll());
        } else {
            JndiHelper.logLevel(plog, level, nth, "(?) class of entry: [" + dirEntry + "]");
        }
        nth++;
    } catch (NamingException e1) {
        plog.error("Naming Exception (will try to continue): " + e1.getMessage());
    }
}

From source file:org.springframework.security.ldap.SpringSecurityLdapTemplate.java

/**
 * Internal method extracted to avoid code duplication in AD search.
 *///  ww w.j av  a 2  s  .  c  om
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
        String base, String filter, Object[] params) throws NamingException {
    final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
    final DistinguishedName searchBaseDn = new DistinguishedName(base);
    final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params,
            buildControls(searchControls));

    if (logger.isDebugEnabled()) {
        logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn
                + "', filter = '" + filter + "'");
    }

    Set<DirContextOperations> results = new HashSet<>();
    try {
        while (resultsEnum.hasMore()) {
            SearchResult searchResult = resultsEnum.next();
            DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
            Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");

            if (logger.isDebugEnabled()) {
                logger.debug("Found DN: " + dca.getDn());
            }
            results.add(dca);
        }
    } catch (PartialResultException e) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.info("Ignoring PartialResultException");
    }

    if (results.size() == 0) {
        throw new IncorrectResultSizeDataAccessException(1, 0);
    }

    if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }

    return results.iterator().next();
}