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.lsc.jndi.JndiServices.java

private void doDeleteChildrenRecursively(String distinguishName) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> ne = ctx.search(distinguishName, DEFAULT_FILTER, sc);
    while (ne.hasMore()) {
        SearchResult sr = (SearchResult) ne.next();
        String childrenDn = rewriteBase(sr.getName() + "," + distinguishName);
        deleteChildrenRecursively(childrenDn);
    }//from w  w w  . j a v a2 s .c om
    ctx.destroySubcontext(new LdapName(distinguishName));
}

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

/**
 * Retrieve the elements referenced by the filter/BaseDN/Scope request.
 *
 * @param attributes Attributes of the referencer element
 * @param directoryDn Dn of the Directory
 * @param linkDn Dn specified in the parent
 * @param filter Filter expression specified in the parent
 * @param scope scope for the search/*w w w  . ja  va 2  s  .c  o  m*/
 * @return The list of the referenced elements.
 * @throws DirectoryException
 * @throws NamingException
 */
private Set<String> getReferencedElements(Attributes attributes, String directoryDn, String linkDn,
        String filter, int scope) throws DirectoryException, NamingException {

    Set<String> targetIds = new TreeSet<>();

    LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor();
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();

    // use the most specific scope between the one specified in the
    // Directory and the specified in the Parent
    String dn = directoryDn.endsWith(linkDn) && directoryDn.length() > linkDn.length() ? directoryDn : linkDn;

    // combine the ldapUrl search query with target
    // directory own constraints
    SearchControls scts = new SearchControls();

    // use the most specific scope
    scts.setSearchScope(Math.min(scope, targetDirconfig.getSearchScope()));

    // only fetch the ids of the targets
    scts.setReturningAttributes(new String[] { targetSession.idAttribute });

    // combine the filter of the target directory with the
    // provided filter if any
    String targetFilter = targetDirconfig.getSearchFilter();
    if (filter == null || filter.length() == 0) {
        filter = targetFilter;
    } else if (targetFilter != null && targetFilter.length() > 0) {
        filter = String.format("(&(%s)(%s))", targetFilter, filter);
    }

    // perform the request and collect the ids
    if (log.isDebugEnabled()) {
        log.debug(String.format(
                "LDAPReference.getLdapTargetIds(%s): LDAP search dn='%s' " + " filter='%s' scope='%s' [%s]",
                attributes, dn, dn, scts.getSearchScope(), this));
    }

    Name name = new CompositeName().add(dn);
    NamingEnumeration<SearchResult> results = targetSession.dirContext.search(name, filter, scts);
    try {
        while (results.hasMore()) {
            // NXP-2461: check that id field is filled
            Attribute attr = results.next().getAttributes().get(targetSession.idAttribute);
            if (attr != null) {
                String collectedId = attr.get().toString();
                if (collectedId != null) {
                    targetIds.add(collectedId);
                }
            }

        }
    } finally {
        results.close();
    }

    return targetIds;
}

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

/**
 * Does a case-insensitive search for the given value in an attribute.
 *
 * @param attribute//w  ww.  j  a va2  s  .c om
 *            the attribute
 * @param value
 *            the value to search for
 * @return <code>true</code>, if the value was found
 * @throws NamingException
 *             if there is a problem accessing the attribute values
 */
protected boolean hasAttributeValue(final Attribute attribute, final String value) throws NamingException {
    if (attribute != null) {
        final NamingEnumeration<?> values = attribute.getAll();
        while (values.hasMore()) {
            final Object mappedValue = this.mapAttributeValue(attribute.getID(), values.next());
            if (mappedValue instanceof String && value.equalsIgnoreCase((String) mappedValue)) {
                return true;
            }
        }
    }
    return false;
}

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

protected Collection<Object> mapAttribute(final Attribute attribute) throws NamingException {
    Collection<Object> values;
    if (attribute.isOrdered()) {
        values = new ArrayList<>();
    } else {//from   ww  w  .  j a  v a  2 s .co m
        values = new HashSet<>();
    }
    final NamingEnumeration<?> allAttributeValues = attribute.getAll();
    while (allAttributeValues.hasMore()) {
        final Object next = allAttributeValues.next();
        final Object mappedValue = this.mapAttributeValue(attribute.getID(), next);
        values.add(mappedValue);
    }

    LOGGER.debug("Mapped value of {} to {}", attribute, values);

    return values;
}

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

protected <T> Collection<T> mapAttribute(final Attribute attribute, final Class<T> expectedValueClass)
        throws NamingException {
    Collection<T> values;//from  ww  w.j a  v  a2  s  . com
    if (attribute.isOrdered()) {
        values = new ArrayList<>();
    } else {
        values = new HashSet<>();
    }
    final NamingEnumeration<?> allAttributeValues = attribute.getAll();
    while (allAttributeValues.hasMore()) {
        final Object next = allAttributeValues.next();
        final Object mappedValue = this.mapAttributeValue(attribute.getID(), next);
        final T value = DefaultTypeConverter.INSTANCE.convert(expectedValueClass, mappedValue);
        values.add(value);
    }

    LOGGER.debug("Mapped value of {} to {}", attribute, values);

    return values;
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * /*from  w w  w.  j  a  va 2  s. c  om*/
 * Creates list of all OLAT Users which have been deleted out of the LDAP
 * directory but still exits in OLAT
 * 
 * Configuration: Required Attributes = ldapContext.xml (property=reqAttrs)
 * LDAP Base = ldapContext.xml (property=ldapBase)
 * 
 * @param syncTime The time to search in LDAP for changes since this time.
 *          SyncTime has to formatted: JJJJMMddHHmm
 * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is
 *          thrown
 * 
 * @return Returns list of Identity from the user which have been deleted in
 *         LDAP
 * 
 * @throws NamingException
 */
public List<Identity> getIdentitysDeletedInLdap(LdapContext ctx) {
    if (ctx == null)
        return null;
    // Find all LDAP Users
    String userID = syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    String userFilter = syncConfiguration.getLdapUserFilter();
    final List<String> ldapList = new ArrayList<String>();

    ldapDao.searchInLdap(new LDAPVisitor() {
        @Override
        public void visit(SearchResult result) throws NamingException {
            Attributes attrs = result.getAttributes();
            NamingEnumeration<? extends Attribute> aEnum = attrs.getAll();
            while (aEnum.hasMore()) {
                Attribute attr = aEnum.next();
                // use lowercase username
                ldapList.add(attr.get().toString().toLowerCase());
            }
        }
    }, (userFilter == null ? "" : userFilter), new String[] { userID }, ctx);

    if (ldapList.isEmpty()) {
        log.warn("No users in LDAP found, can't create deletionList!!", null);
        return null;
    }

    // Find all User in OLAT, members of LDAPSecurityGroup
    SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    if (ldapGroup == null) {
        log.error("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP
                + "' : group does not exist", null);
        return null;
    }

    List<Identity> identityListToDelete = new ArrayList<Identity>();
    List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup);
    for (Identity ida : olatListIdentity) {
        // compare usernames with lowercase
        if (!ldapList.contains(ida.getName().toLowerCase())) {
            identityListToDelete.add(ida);
        }
    }
    return identityListToDelete;
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

private void writeSearchResults(final XMLBuffer xmlb, final NamingEnumeration<SearchResult> srch)
        throws NamingException {

    final ArrayList<SearchResult> sortedResults = new ArrayList<>(MAX_SORTED_RESULTS);
    final String searchBase = getPropertyAsString(SEARCHBASE);
    final String rootDn = getRootdn();

    // read all sortedResults into memory so we can guarantee ordering
    try {/*  w  w w . j av a 2  s. co m*/
        while (srch.hasMore() && (sortedResults.size() < MAX_SORTED_RESULTS)) {
            final SearchResult sr = srch.next();

            // must be done prior to sorting
            normaliseSearchDN(sr, searchBase, rootDn);
            sortedResults.add(sr);
        }
    } finally { // show what we did manage to retrieve

        sortResults(sortedResults);

        for (final SearchResult sr : sortedResults) {
            writeSearchResult(sr, xmlb);
        }
    }

    while (srch.hasMore()) { // If there's anything left ...
        final SearchResult sr = srch.next();

        normaliseSearchDN(sr, searchBase, rootDn);
        writeSearchResult(sr, xmlb);
    }
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

@Override
public SampleResult sample(Entry e) {
    XMLBuffer xmlBuffer = new XMLBuffer();
    xmlBuffer.openTag("ldapanswer"); // $NON-NLS-1$
    SampleResult res = new SampleResult();
    res.setResponseData("successfull", null);
    res.setResponseMessage("Success"); // $NON-NLS-1$
    res.setResponseCode("0"); // $NON-NLS-1$
    res.setContentType("text/xml");// $NON-NLS-1$
    boolean isSuccessful = true;
    res.setSampleLabel(getName());//from   w  w w  .ja v a  2  s .co m
    DirContext dirContext = ldapContexts.get(getThreadName());

    try {
        xmlBuffer.openTag("operation"); // $NON-NLS-1$
        final String testType = getTest();
        xmlBuffer.tag("opertype", testType); // $NON-NLS-1$
        log.debug("performing test: " + testType);
        if (testType.equals(UNBIND)) {
            res.setSamplerData("Unbind");
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            unbindOp(dirContext, res);
        } else if (testType.equals(BIND)) {
            res.setSamplerData("Bind as " + getUserDN());
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut()); // $NON-NLS-1$
            bindOp(res);
        } else if (testType.equals(SBIND)) {
            res.setSamplerData("SingleBind as " + getUserDN());
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("binddn", getUserDN()); // $NON-NLS-1$
            xmlBuffer.tag("connectionTO", getConnTimeOut()); // $NON-NLS-1$
            singleBindOp(res);
        } else if (testType.equals(COMPARE)) {
            res.setSamplerData(
                    "Compare " + getPropertyAsString(COMPAREFILT) + " " + getPropertyAsString(COMPAREDN));
            xmlBuffer.tag("comparedn", getPropertyAsString(COMPAREDN)); // $NON-NLS-1$
            xmlBuffer.tag("comparefilter", getPropertyAsString(COMPAREFILT)); // $NON-NLS-1$
            NamingEnumeration<SearchResult> cmp = null;
            try {
                res.sampleStart();
                cmp = LdapExtClient.compare(dirContext, getPropertyAsString(COMPAREFILT),
                        getPropertyAsString(COMPAREDN));
                if (!cmp.hasMore()) {
                    res.setResponseCode("5"); // $NON-NLS-1$
                    res.setResponseMessage("compareFalse");
                    isSuccessful = false;
                }
            } finally {
                res.sampleEnd();
                if (cmp != null) {
                    cmp.close();
                }
            }
        } else if (testType.equals(ADD)) {
            res.setSamplerData("Add object " + getBaseEntryDN());
            xmlBuffer.tag("attributes", getArguments().toString()); // $NON-NLS-1$
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            addTest(dirContext, res);
        } else if (testType.equals(DELETE)) {
            res.setSamplerData("Delete object " + getBaseEntryDN());
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            deleteTest(dirContext, res);
        } else if (testType.equals(MODIFY)) {
            res.setSamplerData("Modify object " + getBaseEntryDN());
            xmlBuffer.tag("dn", getBaseEntryDN()); // $NON-NLS-1$
            xmlBuffer.tag("attributes", getLDAPArguments().toString()); // $NON-NLS-1$
            modifyTest(dirContext, res);
        } else if (testType.equals(RENAME)) {
            res.setSamplerData(
                    "ModDN object " + getPropertyAsString(MODDDN) + " to " + getPropertyAsString(NEWDN));
            xmlBuffer.tag("dn", getPropertyAsString(MODDDN)); // $NON-NLS-1$
            xmlBuffer.tag("newdn", getPropertyAsString(NEWDN)); // $NON-NLS-1$
            renameTest(dirContext, res);
        } else if (testType.equals(SEARCH)) {
            final String scopeStr = getScope();
            final int scope = getScopeAsInt();
            final String searchFilter = getPropertyAsString(SEARCHFILTER);
            final String searchBase = getPropertyAsString(SEARCHBASE);
            final String timeLimit = getTimelim();
            final String countLimit = getCountlim();

            res.setSamplerData("Search with filter " + searchFilter);
            xmlBuffer.tag("searchfilter", StringEscapeUtils.escapeXml10(searchFilter)); // $NON-NLS-1$
            xmlBuffer.tag("baseobj", getRootdn()); // $NON-NLS-1$
            xmlBuffer.tag("searchbase", searchBase);// $NON-NLS-1$
            xmlBuffer.tag("scope", scopeStr); // $NON-NLS-1$
            xmlBuffer.tag("countlimit", countLimit); // $NON-NLS-1$
            xmlBuffer.tag("timelimit", timeLimit); // $NON-NLS-1$

            NamingEnumeration<SearchResult> srch = null;
            try {
                res.sampleStart();
                srch = LdapExtClient.searchTest(dirContext, searchBase, searchFilter, scope,
                        getCountlimAsLong(), getTimelimAsInt(), getRequestAttributes(getAttrs()), isRetobj(),
                        isDeref());
                if (isParseFlag()) {
                    try {
                        xmlBuffer.openTag("searchresults"); // $NON-NLS-1$
                        writeSearchResults(xmlBuffer, srch);
                    } finally {
                        xmlBuffer.closeTag("searchresults"); // $NON-NLS-1$
                    }
                } else {
                    xmlBuffer.tag("searchresults", // $NON-NLS-1$
                            "hasElements=" + srch.hasMoreElements()); // $NON-NLS-1$
                }
            } finally {
                if (srch != null) {
                    srch.close();
                }
                res.sampleEnd();
            }

        }

    } catch (NamingException ex) {
        // TODO: tidy this up
        String returnData = ex.toString();
        final int indexOfLDAPErrCode = returnData.indexOf("LDAP: error code");
        if (indexOfLDAPErrCode >= 0) {
            res.setResponseMessage(returnData.substring(indexOfLDAPErrCode + 21, returnData.indexOf(']'))); // $NON-NLS-1$
            res.setResponseCode(returnData.substring(indexOfLDAPErrCode + 17, indexOfLDAPErrCode + 19));
        } else {
            res.setResponseMessage(returnData);
            res.setResponseCode("800"); // $NON-NLS-1$
        }
        isSuccessful = false;
    } finally {
        xmlBuffer.closeTag("operation"); // $NON-NLS-1$
        xmlBuffer.tag("responsecode", res.getResponseCode()); // $NON-NLS-1$
        xmlBuffer.tag("responsemessage", res.getResponseMessage()); // $NON-NLS-1$
        res.setResponseData(xmlBuffer.toString(), null);
        res.setDataType(SampleResult.TEXT);
        res.setSuccessful(isSuccessful);
    }
    return res;
}

From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java

public String searchQueryLDAP() {
    NamingEnumeration results = null;
    ObjectMapper mapper = new ObjectMapper();
    Response response;/* w w w  .j  a  va 2s . c o m*/
    String resultOutput = new String();
    List<Map<String, String>> attributesList = new LinkedList<>();

    String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES));
    try {
        ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL),
                allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME),
                allLDAPClientParameters.get(ARG_PASSWORD));
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (attributesToReturn.length > 0) {
            controls.setReturningAttributes(attributesToReturn);
        }
        results = ldapConnection.search(
                getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE),
                        allLDAPClientParameters.get(ARG_SEARCH_BASE)),
                allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls);

        // Iterate through all attributes in the result of search query
        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();

            if (attributes != null && attributes.size() > 0) {
                NamingEnumeration ae = attributes.getAll();
                Map<String, String> attributesMap = new HashMap<>();
                while (ae.hasMore()) {
                    Attribute attribute = (Attribute) ae.next();
                    attributesMap.put(attribute.getID(), attribute.get().toString());
                }
                attributesList.add(attributesMap);
            }
        }
        response = new LDAPResponse("Ok", attributesList);
    } catch (Exception e) {
        response = new ErrorResponse("Error", e.toString());
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ldapConnection != null) {
            try {
                ldapConnection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        resultOutput = mapper.writeValueAsString(response);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return resultOutput;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

protected boolean organizationExists(String orgId) throws ExecutionException {
    NamingEnumeration<SearchResult> searchResults = null;
    try {//from   w  w w  .j  a va  2  s.  c  o m
        searchResults = this.query(LDAPConnector.getSingletonInstance().getInstitutionBaseDN(),
                new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                        .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
        if (searchResults.hasMore()) {
            return true;
        } else {
            return false;
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (NamingException e) {
            }
        }
    }
}