Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration hasMore.

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 *//*from  w w w  . j a v  a2s. co  m*/
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } catch (SchemaViolationException e) {
                        if (isDynamic()) {
                            // we are editing an entry that has no static
                            // part
                            log.warn(String.format("cannot remove dynamic reference in field %s for target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}

From source file:org.springframework.ldap.core.LdapTemplate.java

/**
 * Perform a search operation, such as a search(), list() or listBindings().
 * This method handles all the plumbing; getting a readonly context; looping
 * through the NamingEnumeration and closing the context and enumeration. It
 * also calls the supplied DirContextProcessor before and after the search,
 * respectively. This enables custom pre-processing and post-processing,
 * like for example when handling paged results or other search controls.
 * <p>//from  ww w . j av a 2s. co m
 * The actual list is delegated to the {@link SearchExecutor} and each
 * {@link NameClassPair} (this might be a NameClassPair or a subclass
 * thereof) is passed to the CallbackHandler. Any encountered
 * NamingException will be translated using the NamingExceptionTranslator.
 * 
 * @param se the SearchExecutor to use for performing the actual list.
 * @param handler the NameClassPairCallbackHandler to which each found entry
 * will be passed.
 * @param processor DirContextProcessor for custom pre- and post-processing.
 * Must not be <code>null</code>. If no custom processing should take place,
 * please use e.g.
 * {@link #search(SearchExecutor, NameClassPairCallbackHandler)}.
 * @throws NamingException if any error occurs. Note that a
 * NameNotFoundException will be ignored. Instead this is interpreted that
 * no entries were found.
 */
public void search(SearchExecutor se, NameClassPairCallbackHandler handler, DirContextProcessor processor) {
    DirContext ctx = contextSource.getReadOnlyContext();

    NamingEnumeration results = null;
    RuntimeException ex = null;
    try {
        processor.preProcess(ctx);
        results = se.executeSearch(ctx);

        while (results.hasMore()) {
            NameClassPair result = (NameClassPair) results.next();
            handler.handleNameClassPair(result);
        }
    } catch (NameNotFoundException e) {
        // It is possible to ignore errors caused by base not found
        if (ignoreNameNotFoundException) {
            log.warn("Base context not found, ignoring: " + e.getMessage());
        } else {
            ex = LdapUtils.convertLdapException(e);
        }
    } catch (PartialResultException e) {
        // Workaround for AD servers not handling referrals correctly.
        if (ignorePartialResultException) {
            log.debug("PartialResultException encountered and ignored", e);
        } else {
            ex = LdapUtils.convertLdapException(e);
        }
    } catch (javax.naming.NamingException e) {
        ex = LdapUtils.convertLdapException(e);
    } finally {
        try {
            processor.postProcess(ctx);
        } catch (javax.naming.NamingException e) {
            if (ex == null) {
                ex = LdapUtils.convertLdapException(e);
            } else {
                // We already had an exception from above and should ignore
                // this one.
                log.debug("Ignoring Exception from postProcess, " + "main exception thrown instead", e);
            }
        }
        closeContextAndNamingEnumeration(ctx, results);
        // If we got an exception it should be thrown.
        if (ex != null) {
            throw ex;
        }
    }
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Get user UID attribute for the given certificate.
 *
 * @param lookupValue value used for credentials lookup
 * @param certificate user certificate/* w w  w.  j ava 2s  .  com*/
 * @param cp credential provider
 * @return user UID
 * @throws NamingException LDAP error obtaining user UID.
 * @throws IOException 
 */
protected String loadUID(String lookupValue, X509Certificate certificate, CredentialProvider cp)
        throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String certificateAttrName = this.getUserCertificateAtrributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN,
                "(&(" + principalLookupAttrName + "={0})(" + certificateAttrName + "={1}))",
                new Object[] { lookupValue, certificate.getEncoded() }, getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug("Found user " + principalUidAttrName + "=" + uidValue);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for certificate '"
                            + certificate.getSubjectX500Principal().getName() + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } catch (CertificateEncodingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Certificate encoding exception", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}

From source file:com.adito.ldap.LdapUserDatabase.java

/**
 * (non-Javadoc)/*w w  w  .j  a  v  a2 s  . c  o  m*/
 *
 * @see com.adito.security.DefaultUserDatabase#deleteRole(java.lang.String)
 */
public void deleteRole(String rolename) throws Exception {
    if (!supportsAccountCreation()) {
        throw new UnsupportedOperationException("User database is read-only");
    }

    LdapTemplate ldapTemplate = new LdapTemplate();
    ldapTemplate.setContextSource(ldapContextSource);

    String dn = ((LdapGroup) getRole(rolename)).getDn();

    int ind = dn.indexOf(baseDn);

    String rdn = dn.substring(0, ind - 1);

    //take the name of user'member of this group
    NamingEnumeration e = (NamingEnumeration) ldapTemplate.lookup(rdn, new AttributesMapper() {
        public Object mapFromAttributes(Attributes attrs) throws NamingException {

            return attrs.get(MEMBER_ATTRIBUTE).getAll();

        }
    });

    //delete the group in database
    ldapTemplate.unbind(rdn);
    groupContainer.removeGroup((LdapGroup) getRole(rolename));

    // delete the group in Ldapuser
    for (; e.hasMore();) {
        LdapUser u = getAccountFromDN(e.next().toString());
        u.setRoles(getGroupsForUser(u.getDn()));
        userContainer.storePrincipal(u);
    }

}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

protected SearchResult getLdapEntry(String id, boolean fetchAllAttributes) throws NamingException {
    if (StringUtils.isEmpty(id)) {
        log.warn(//from ww  w. ja  va2 s .c  o m
                "The application should not " + "query for entries with an empty id " + "=> return no results");
        return null;
    }
    String filterExpr;
    String baseFilter = getDirectory().getBaseFilter();
    if (baseFilter.startsWith("(")) {
        filterExpr = String.format("(&(%s={0})%s)", idAttribute, baseFilter);
    } else {
        filterExpr = String.format("(&(%s={0})(%s))", idAttribute, baseFilter);
    }
    String[] filterArgs = { id };
    SearchControls scts = getDirectory().getSearchControls(fetchAllAttributes);

    if (log.isDebugEnabled()) {
        log.debug(String.format(
                "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' "
                        + " args='%s' scope='%s' [%s]",
                id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), this));
    }
    NamingEnumeration<SearchResult> results;
    try {
        results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts);
    } catch (NameNotFoundException nnfe) {
        // sometimes ActiveDirectory have some query fail with: LDAP:
        // error code 32 - 0000208D: NameErr: DSID-031522C9, problem
        // 2001 (NO_OBJECT).
        // To keep the application usable return no results instead of
        // crashing but log the error so that the AD admin
        // can fix the issue.
        log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe);
        return null;
    }

    if (!results.hasMore()) {
        log.debug("Entry not found: " + id);
        return null;
    }
    SearchResult result = results.next();
    try {
        String dn = result.getNameInNamespace();
        if (results.hasMore()) {
            result = results.next();
            String dn2 = result.getNameInNamespace();
            String msg = String.format("Unable to fetch entry for '%s': found more than one match,"
                    + " for instance: '%s' and '%s'", id, dn, dn2);
            log.error(msg);
            // ignore entries that are ambiguous while giving enough info
            // in the logs to let the LDAP admin be able to fix the issue
            return null;
        }
        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' "
                            + " args='%s' scope='%s' => found: %s [%s]",
                    id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), dn, this));
        }
    } catch (UnsupportedOperationException e) {
        // ignore unsupported operation thrown by the Apache DS server in
        // the tests in embedded mode
    }
    return result;
}

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 w  w w .jav  a  2 s .co 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:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

/**
 * Invokes the given callback on each entry returned by the given query.
 *
 * @param callback/*from www.j  av  a 2s.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:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id)
        throws OAException {
    String sReturn = null;//from  ww  w  .  j  a  va  2s  .co  m
    NamingEnumeration oNamingEnumeration = null;
    try {
        if (sIDAttribute == null) {
            _logger.error("No attribute name to map from supplied");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbQuery = new StringBuffer("(");
        sbQuery.append(sIDAttribute);
        sbQuery.append("=");
        sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id));
        sbQuery.append(")");
        String sSearchQuery = sbQuery.toString();

        String sSearchFor = sMapperAttribute;
        if (sSearchFor == null)
            sSearchFor = "*";

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        oScope.setReturningAttributes(new String[] { sSearchFor });

        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(sSearchQuery);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        if (!oNamingEnumeration.hasMore()) {
            _logger.debug("No result when searching for: " + sSearchQuery);
        } else {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();

            if (sMapperAttribute == null) {
                sReturn = oSearchResult.getName();
                sReturn += "," + _sDNBase;
            } else {
                Attributes oSearchedAttributes = oSearchResult.getAttributes();
                Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute);
                if (attrMapping == null) {
                    _logger.debug("Mapping attribute not found: " + sMapperAttribute);
                } else {
                    Object oValue = attrMapping.get();
                    if (!(oValue instanceof String)) {
                        StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '");
                        sbError.append(_sMapperAttribute);
                        sbError.append("' has a value which is not of type 'String'");
                        _logger.error(sbError.toString());
                        throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
                    }
                    sReturn = (String) oValue;
                }
            }
        }
    } catch (OAException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch mapping attribute for id: " + id, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for id: " + id, e);
            }
        }
    }
    return sReturn;
}

From source file:org.lsc.jndi.JndiServices.java

private SearchResult doReadEntry(final String base, final String filter, final boolean allowError,
        final SearchControls sc) throws NamingException {
    NamingEnumeration<SearchResult> ne = null;
    sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    try {/*  w w  w.  j  a  v a  2 s .  c om*/
        ne = ctx.search(rewriteBase(base), filter, sc);
    } catch (NamingException nex) {
        if (nex instanceof CommunicationException || nex instanceof ServiceUnavailableException) {
            throw nex;
        }
        if (!allowError) {
            LOGGER.error("Error while reading entry {}: {}", base, nex);
            LOGGER.debug(nex.toString(), nex);
        }
        return null;
    }

    SearchResult sr = null;
    if (ne.hasMore()) {
        sr = (SearchResult) ne.next();
        if (ne.hasMore()) {
            LOGGER.error("Too many entries returned (base: \"{}\")", base);
        } else {
            return sr;
        }
    }
    return sr;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Obtains the roles for the given user.
 *
 * @param username the user name to fetch user data.
 * @return the list of roles to which the user is associated to.
 * @throws NamingException LDAP error obtaining roles fro the given user
 * @throws IOException /* www. j av  a  2s . co m*/
 */
protected String[] selectRolesByUsername(String username) throws NamingException, IOException {
    List userRoles = new ArrayList();

    InitialLdapContext ctx = null;
    try {
        ctx = createLdapInitialContext(getUseBindCredentials());
    } catch (NamingException e) {
        if (getUseBindCredentials()) {
            // in case we are using virtual identity store
            return (String[]) userRoles.toArray(new String[userRoles.size()]);
        } else {
            throw e;
        }
    }

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String rolesCtxDN = getRolesCtxDN();

    // Search for any roles associated with the user
    if (rolesCtxDN != null) {

        // The attribute where user DN is stored in roles :
        String uidAttributeID = getUidAttributeID();
        if (uidAttributeID == null)
            uidAttributeID = "uniquemember";

        // The attribute that identifies the role name 
        String roleAttrName = getRoleAttributeID();
        if (roleAttrName == null)
            roleAttrName = "roles";

        String userDN;
        if ("UID".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = username;
        } else {
            // Default behaviour: Match the role using the User DN, not just the username :
            userDN = selectUserDN(username);
        }

        if (userDN != null) {
            if (logger.isDebugEnabled())
                logger.debug("Searching Roles for user '" + userDN + "' in Uid attribute name '"
                        + uidAttributeID + "'");

            try {
                if (userDN.contains("\\")) {
                    logger.debug("Escaping '\\' character");
                    userDN = userDN.replace("\\", "\\\\\\");
                }

                NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))",
                        getSearchControls());

                if (logger.isDebugEnabled())
                    logger.debug("Search Name:  " + rolesCtxDN);

                if (logger.isDebugEnabled())
                    logger.debug("Search Filter:  (&(" + uidAttributeID + "=" + userDN + "))");

                if (!answer.hasMore())
                    logger.info("No role where found for user " + username);

                while (answer.hasMore()) {
                    SearchResult sr = (SearchResult) answer.next();
                    Attributes attrs = sr.getAttributes();
                    Attribute roles = attrs.get(roleAttrName);
                    for (int r = 0; r < roles.size(); r++) {
                        Object value = roles.get(r);
                        String roleName = null;
                        // The role attribute value is the role name
                        roleName = value.toString();

                        if (roleName != null) {
                            if (logger.isDebugEnabled())
                                logger.debug("Saving role '" + roleName + "' for user '" + username + "'");
                            userRoles.add(roleName);
                        }
                    }
                }
            } catch (NamingException e) {
                if (logger.isDebugEnabled())
                    logger.debug("Failed to locate roles", e);
            }
        }
    }
    // Close the context to release the connection
    if (tls != null) {
        tls.close();
    }
    ctx.close();
    return (String[]) userRoles.toArray(new String[userRoles.size()]);
}