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:nl.nn.adapterframework.ldap.LdapSender.java

private XmlBuilder searchResultsToXml(NamingEnumeration entries) throws NamingException {

    XmlBuilder entriesElem = new XmlBuilder("entries");
    int row = 0;//from  www  .  j  a v  a  2 s .c om
    while ((getMaxEntriesReturned() == 0 || row < getMaxEntriesReturned()) && entries.hasMore()) {
        SearchResult searchResult = (SearchResult) entries.next();
        XmlBuilder entryElem = new XmlBuilder("entry");

        entryElem.addAttribute("name", searchResult.getName());
        entryElem.addSubElement(attributesToXml(searchResult.getAttributes()));

        entriesElem.addSubElement(entryElem);
        row++;
    }
    return entriesElem;
}

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

/**
 * Delete all subcontexts including the current one recursively.
 * /* w w  w .ja  v  a2s.c  om*/
 * @param ctx The context to use for deleting.
 * @param name The starting point to delete recursively.
 * @throws NamingException if any error occurs
 */
protected void deleteRecursively(DirContext ctx, DistinguishedName name) {

    NamingEnumeration enumeration = null;
    try {
        enumeration = ctx.listBindings(name);
        while (enumeration.hasMore()) {
            Binding binding = (Binding) enumeration.next();
            DistinguishedName childName = new DistinguishedName(binding.getName());
            childName.prepend((DistinguishedName) name);
            deleteRecursively(ctx, childName);
        }
        ctx.unbind(name);
        if (log.isDebugEnabled()) {
            log.debug("Entry " + name + " deleted");
        }
    } catch (javax.naming.NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        try {
            enumeration.close();
        } catch (Exception e) {
            // Never mind this
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

/** 
 * Return a list of all of the subcontexts of the current context, which is relative to parentContext. 
 * @return an array of Strings containing a list of the subcontexts for a current context.
 *///w w w .  jav a 2  s .  c  o  m
public String[] getSubContextList(DirContext parentContext, String relativeContext,
        ParameterResolutionContext prc) {
    String[] retValue = null;

    try {
        // Create a vector object and add the names of all of the subcontexts
        //  to it
        Vector n = new Vector();
        NamingEnumeration list = parentContext.list(relativeContext);
        if (log.isDebugEnabled())
            log.debug("getSubCOntextList(context) : context = " + relativeContext);
        for (int x = 0; list.hasMore(); x++) {
            NameClassPair nc = (NameClassPair) list.next();
            n.addElement(nc);
        }

        // Create a string array of the same size as the vector object
        String contextList[] = new String[n.size()];
        for (int x = 0; x < n.size(); x++) {
            // Add each name to the array
            contextList[x] = ((NameClassPair) (n.elementAt(x))).getName();
        }
        retValue = contextList;

    } catch (NamingException e) {
        storeLdapException(e, prc);
        log.error("Exception in operation [" + getOperation() + "] ", e);
    }

    return retValue;
}

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

/**
 * Obtain the properties for the user associated with the given uid using the
 * configured user properties query string.
 *
 * @param uid the user id of the user for whom its user properties are required.
 * @return the hash map containing user properties as name/value pairs.
 * @throws NamingException LDAP error obtaining user properties.
 * @throws IOException //w ww  .java 2s. c  o  m
 */
protected HashMap selectUserProperties(String uid) throws NamingException, IOException {
    HashMap userPropertiesResultSet = new HashMap();

    InitialLdapContext ctx = null;
    try {
        ctx = createLdapInitialContext(getUseBindCredentials());
    } catch (NamingException e) {
        if (getUseBindCredentials()) {
            // in case we are using virtual identity store
            return userPropertiesResultSet;
        } else {
            throw e;
        }
    }

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

    BasicAttributes matchAttrs = new BasicAttributes(true);

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

    matchAttrs.put(principalUidAttrName, uid);

    String userPropertiesQueryString = getUserPropertiesQueryString();
    HashMap userPropertiesQueryMap = parseQueryString(userPropertiesQueryString);

    Iterator i = userPropertiesQueryMap.keySet().iterator();
    List propertiesAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        propertiesAttrList.add(o);
    }

    String[] propertiesAttr = (String[]) propertiesAttrList.toArray(new String[propertiesAttrList.size()]);

    try {

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            for (int j = 0; j < propertiesAttr.length; j++) {

                Attribute attribute = attrs.get(propertiesAttr[j]);

                if (attribute == null) {
                    logger.warn("Invalid user property attribute '" + propertiesAttr[j] + "'");
                    continue;
                }

                Object propertyObject = attrs.get(propertiesAttr[j]).get();

                if (propertyObject == null) {
                    logger.warn("Found a 'null' value for user property '" + propertiesAttr[j] + "'");
                    continue;
                }

                String propertyValue = propertyObject.toString();
                String propertyName = (String) userPropertiesQueryMap.get(propertiesAttr[j]);

                userPropertiesResultSet.put(propertyName, propertyValue);

                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user property '" + propertyName + "' with value '" + propertyValue + "'");
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return userPropertiesResultSet;
}

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

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes/*from   ww  w .  j av  a  2 s .c o  m*/
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws javax.naming.NamingException
 *             the naming exception
 */
private Attribute getRangeRestrictedAttribute(Attributes attributes, String attributeName)
        throws NamingException {
    Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    NamingEnumeration<? extends Attribute> i = attributes.getAll();
    String searchString = attributeName.toLowerCase() + ';';
    while (i.hasMore()) {
        Attribute attribute = i.next();
        if (attribute.getID().toLowerCase().startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int)
 *//*from   w ww  .  j  a  v  a  2s  . co m*/
@Override
public List<UserPrincipal> searchCandidateUsers(String searchCriteria, int maxResults)
        throws RepositoryException {
    List<UserPrincipal> userList = new ArrayList<>();

    if ((searchCriteria != null) && (searchCriteria.length() > 0)) {
        List<String> searchAttributes = Arrays.asList(userLastNameAttribute, userFirstNameAttribute,
                userFullNameAttribute);
        StringBuilder searchFilter = new StringBuilder("(&(objectCategory=person)(").append(userIdAttribute)
                .append("=*)(|");
        SearchControls constraints = new SearchControls();
        DirContext context = null;

        for (String searchAttr : searchAttributes) {
            if ((searchAttr != null) && (searchAttr.length() > 0)) {
                searchFilter.append("(").append(searchAttr).append("=*").append(searchCriteria).append("*)");
            }
        }
        searchFilter.append("))");
        constraints.setSearchScope(
                searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        constraints.setTimeLimit(userSearchTimeout);
        constraints.setCountLimit(maxResults);
        constraints.setReturningAttributes(new String[] { userIdAttribute, userLastNameAttribute,
                userFirstNameAttribute, userEmailAttribute });

        try {
            context = openConnection(connectionPrincipal, connectionPassword);
            NamingEnumeration<SearchResult> searchResults = context.search(userSearchBase,
                    searchFilter.toString(), constraints);

            while (searchResults.hasMore()) {
                SearchResult resultItem = searchResults.next();
                Attributes itemAttrs = resultItem.getAttributes();
                String userId = getAttributeValue(itemAttrs, userIdAttribute);
                String lastName = getAttributeValue(itemAttrs, userLastNameAttribute);
                String firstName = getAttributeValue(itemAttrs, userFirstNameAttribute);
                String email = getAttributeValue(itemAttrs, userEmailAttribute);
                UserPrincipal user = new UserPrincipal();

                user.setUserId(userId);
                user.setLastName(lastName);
                user.setFirstName(firstName);
                user.setEmailAddress(email);
                userList.add(user);
            }

        } catch (PartialResultException | SizeLimitExceededException e) {
            // Ignore - this means we have reached the end of the list and that any remaining
            // items are aliased referrals which cannot be resolved.

        } catch (NamingException e) {
            throw new RepositoryException("Error encountered during directory search.", e);
        }
    }
    return userList;
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {//from   w w  w.  j a v a 2s .c  om
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", 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/*ww w  .ja v  a2  s  . 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 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:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Searches the remote directory for the user's entry and returns its distinguished name
 * string./*  ww w.jav a 2s .  com*/
 * 
 * @param userId
 *            the ID of the user whose DN is to be retrieved
 * @param context
 *            the directory context from which to retrieve the user's DN
 * @return String
 * @throws NamingException
 */
protected String findUserDn(String userId, DirContext context) throws NamingException {
    String userDn = null;

    for (MessageFormat userSearchPattern : userSearchPatterns) {
        try {
            String searchFilter = userSearchPattern.format(new String[] { userId });
            SearchControls constraints = new SearchControls();

            constraints.setSearchScope(
                    searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
            constraints.setTimeLimit(userSearchTimeout);

            NamingEnumeration<SearchResult> results = context.search(userSearchBase, searchFilter, constraints);
            SearchResult result = null;

            try {
                if ((results != null) && results.hasMore()) {
                    result = results.next();

                    // Make sure only one entry exists for the requested user
                    if (results.hasMore()) {
                        log.warn("Multiple entries found for user: " + userId);
                        result = null;
                    }
                }
            } catch (PartialResultException e) {
                // Ignore partial result errors - most likely due to ActiveDirectory referrals
            }

            if (result != null) {
                userDn = result.getNameInNamespace();
                break;
            }

        } catch (NameNotFoundException e) {
            // Ignore and keep searching
        }
    }
    return userDn;
}

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

/**
 * Fetch the Ldap user attributes to be used as credentials.
 *
 * @param uid the user id (or lookup value) for whom credentials are required
 * @return the hash map containing user credentials as name/value pairs
 * @throws NamingException LDAP error obtaining user credentials.
 * @throws IOException // ww w  .  j a  v  a2s. c o m
 */
protected HashMap selectCredentials(String uid, CredentialProvider cp) throws NamingException, IOException {
    HashMap credentialResultSet = new HashMap();

    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 usersCtxDN = this.getUsersCtxDN();

    // BasicAttributes matchAttrs = new BasicAttributes(true);
    // matchAttrs.put(principalUidAttrName, uid);

    String credentialQueryString = getCredentialQueryString();
    HashMap credentialQueryMap = parseQueryString(credentialQueryString);

    Iterator i = credentialQueryMap.keySet().iterator();
    List credentialAttrList = new ArrayList();
    while (i.hasNext()) {
        String o = (String) i.next();
        credentialAttrList.add(o);
    }

    String[] credentialAttr = (String[]) credentialAttrList.toArray(new String[credentialAttrList.size()]);

    try {

        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, credentialAttr);

        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalLookupAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();

            String userDN = sr.getNameInNamespace();
            if (logger.isDebugEnabled())
                logger.debug("Processing results for entry '" + userDN + "'");

            for (int j = 0; j < credentialAttr.length; j++) {
                if (attrs.get(credentialAttr[j]) == null)
                    continue;

                //Object credentialObject = attrs.get(credentialAttr[j]).get();
                String credentialName = (String) credentialQueryMap.get(credentialAttr[j]);
                String credentialValue = null;

                Attribute attr = attrs.get(credentialAttr[j]);
                NamingEnumeration attrEnum = attr.getAll();
                while (attrEnum.hasMore()) {
                    Object credentialObject = attrEnum.next();
                    if (credentialObject == null)
                        continue;

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' of type '"
                                + credentialObject.getClass().getName() + ""
                                + (credentialObject.getClass().isArray()
                                        ? "[" + Array.getLength(credentialObject) + "]"
                                        : "")
                                + "'");

                    // if the attribute value is an array, cast it to byte[] and then convert to
                    // String using proper encoding
                    if (credentialObject.getClass().isArray()) {

                        try {
                            // Try to create a UTF-8 String, we use java.nio to handle errors in a better way.
                            // If the byte[] cannot be converted to UTF-8, we're using the credentialObject as is.
                            byte[] credentialData = (byte[]) credentialObject;
                            ByteBuffer in = ByteBuffer.allocate(credentialData.length);
                            in.put(credentialData);
                            in.flip();

                            Charset charset = Charset.forName("UTF-8");
                            CharsetDecoder decoder = charset.newDecoder();
                            CharBuffer charBuffer = decoder.decode(in);

                            credentialValue = charBuffer.toString();

                        } catch (CharacterCodingException e) {
                            if (logger.isDebugEnabled())
                                logger.debug("Can't convert credential value to String using UTF-8");
                        }

                    } else if (credentialObject instanceof String) {
                        // The credential value must be a String ...
                        credentialValue = (String) credentialObject;

                    }

                    // Check what do we have ...
                    List credentials = (List) credentialResultSet.get(credentialName);
                    if (credentials == null) {
                        credentials = new ArrayList();
                    }
                    if (credentialValue != null) {
                        // Remove any schema information from the credential value, like the {md5} prefix for passwords.
                        credentialValue = getSchemeFreeValue(credentialValue);
                        credentials.add(credentialValue);
                    } else {
                        // We have a binary credential, leave it as it is ... probably binary value.
                        credentials.add(credentialObject);
                    }
                    credentialResultSet.put(credentialName, credentials);

                    if (logger.isDebugEnabled())
                        logger.debug("Found user credential '" + credentialName + "' with value '"
                                + (credentialValue != null ? credentialValue : credentialObject) + "'");
                }
            }

        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return credentialResultSet;
}