Example usage for javax.naming.directory SearchControls ONELEVEL_SCOPE

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

Introduction

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

Prototype

int ONELEVEL_SCOPE

To view the source code for javax.naming.directory SearchControls ONELEVEL_SCOPE.

Click Source Link

Document

Search one level of the named context.

Usage

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

/**
 * Optimized method to spare a LDAP request when the caller is a LDAPSession object that has already fetched the
 * LDAP Attribute instances.//from w w w.j  a va  2s .c om
 * <p>
 * This method should return the same results as the sister method: org.nuxeo
 * .ecm.directory.Reference#getTargetIdsForSource(java.lang.String)
 *
 * @return target reference ids
 * @throws DirectoryException
 */
public List<String> getLdapTargetIds(Attributes attributes) throws DirectoryException {

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

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor();
    String emptyRefMarker = ldapTargetDirectory.getDescriptor().getEmptyRefMarker();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        String baseDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());

        // step #1: fetch ids referenced by static attributes
        String staticAttributeId = getStaticAttributeId();
        Attribute staticAttribute = null;
        if (staticAttributeId != null) {
            staticAttribute = attributes.get(staticAttributeId);
        }

        if (staticAttribute != null && !staticAttributeIdIsDn) {
            NamingEnumeration<?> staticContent = staticAttribute.getAll();
            try {
                while (staticContent.hasMore()) {
                    String value = staticContent.next().toString();
                    if (!emptyRefMarker.equals(value)) {
                        targetIds.add(value);
                    }
                }
            } finally {
                staticContent.close();
            }
        }

        if (staticAttribute != null && staticAttributeIdIsDn) {
            NamingEnumeration<?> targetDns = staticAttribute.getAll();
            try {
                while (targetDns.hasMore()) {
                    String targetDn = targetDns.next().toString();

                    if (!pseudoNormalizeDn(targetDn).endsWith(baseDn)) {
                        // optim: avoid network connections when obvious
                        if (log.isTraceEnabled()) {
                            log.trace(String.format("ignoring: dn='%s' (does not match '%s') for '%s'",
                                    targetDn, baseDn, this));
                        }
                        continue;
                    }
                    // find the id of the referenced entry
                    String id = null;

                    if (targetSession.rdnMatchesIdField()) {
                        // optim: do not fetch the entry to get its true id
                        // but
                        // guess it by reading the targetDn
                        LdapName name = new LdapName(targetDn);
                        String rdn = name.get(name.size() - 1);
                        int pos = rdn.indexOf("=");
                        id = rdn.substring(pos + 1);
                    } else {
                        id = getIdForDn(targetSession, targetDn);
                        if (id == null) {
                            log.warn(String.format(
                                    "ignoring target '%s' (missing attribute '%s') while resolving reference '%s'",
                                    targetDn, targetSession.idAttribute, this));
                            continue;
                        }
                    }
                    if (forceDnConsistencyCheck) {
                        // check that the referenced entry is actually part
                        // of
                        // the target directory (takes care of the filters
                        // and
                        // the scope)
                        // this check can be very expensive on large groups
                        // and thus not enabled by default
                        if (!targetSession.hasEntry(id)) {
                            if (log.isTraceEnabled()) {
                                log.trace(String.format(
                                        "ignoring target '%s' when resolving '%s' (not part of target"
                                                + " directory by forced DN consistency check)",
                                        targetDn, this));
                            }
                            continue;
                        }
                    }
                    // NXP-2461: check that id field is filled
                    if (id != null) {
                        targetIds.add(id);
                    }
                }
            } finally {
                targetDns.close();
            }
        }
        // step #2: fetched dynamically referenced ids
        String dynamicAttributeId = this.dynamicAttributeId;
        Attribute dynamicAttribute = null;
        if (dynamicAttributeId != null) {
            dynamicAttribute = attributes.get(dynamicAttributeId);
        }
        if (dynamicAttribute != null) {
            NamingEnumeration<?> rawldapUrls = dynamicAttribute.getAll();
            try {
                while (rawldapUrls.hasMore()) {
                    LdapURL ldapUrl = new LdapURL(rawldapUrls.next().toString());
                    String linkDn = pseudoNormalizeDn(ldapUrl.getDN());
                    String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());
                    int scope = SearchControls.ONELEVEL_SCOPE;
                    String scopePart = ldapUrl.getScope();
                    if (scopePart != null && scopePart.toLowerCase().startsWith("sub")) {
                        scope = SearchControls.SUBTREE_SCOPE;
                    }
                    if (!linkDn.endsWith(directoryDn) && !directoryDn.endsWith(linkDn)) {
                        // optim #1: if the dns do not match, abort
                        continue;
                    } else if (directoryDn.endsWith(linkDn) && linkDn.length() < directoryDn.length()
                            && scope == SearchControls.ONELEVEL_SCOPE) {
                        // optim #2: the link dn is pointing to elements
                        // that at
                        // upperlevel than directory elements
                        continue;
                    } else {

                        // Search for references elements
                        targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDn,
                                ldapUrl.getFilter(), scope));

                    }
                }
            } finally {
                rawldapUrls.close();
            }
        }

        if (dynamicReferences != null && dynamicReferences.length > 0) {

            // Only the first Dynamic Reference is used
            LDAPDynamicReferenceDescriptor dynAtt = dynamicReferences[0];

            Attribute baseDnsAttribute = attributes.get(dynAtt.baseDN);
            Attribute filterAttribute = attributes.get(dynAtt.filter);

            if (baseDnsAttribute != null && filterAttribute != null) {

                NamingEnumeration<?> baseDns = null;
                NamingEnumeration<?> filters = null;

                try {
                    // Get the BaseDN value from the descriptor
                    baseDns = baseDnsAttribute.getAll();
                    String linkDnValue = baseDns.next().toString();
                    baseDns.close();
                    linkDnValue = pseudoNormalizeDn(linkDnValue);

                    // Get the filter value from the descriptor
                    filters = filterAttribute.getAll();
                    String filterValue = filters.next().toString();
                    filters.close();

                    // Get the scope value from the descriptor
                    int scope = "subtree".equalsIgnoreCase(dynAtt.type) ? SearchControls.SUBTREE_SCOPE
                            : SearchControls.ONELEVEL_SCOPE;

                    String directoryDn = pseudoNormalizeDn(targetDirconfig.getSearchBaseDn());

                    // if the dns match, and if the link dn is pointing to
                    // elements that at upperlevel than directory elements
                    if ((linkDnValue.endsWith(directoryDn) || directoryDn.endsWith(linkDnValue))
                            && !(directoryDn.endsWith(linkDnValue)
                                    && linkDnValue.length() < directoryDn.length()
                                    && scope == SearchControls.ONELEVEL_SCOPE)) {

                        // Correct the filter expression
                        filterValue = FilterExpressionCorrector.correctFilter(filterValue,
                                FilterJobs.CORRECT_NOT);

                        // Search for references elements
                        targetIds.addAll(getReferencedElements(attributes, directoryDn, linkDnValue,
                                filterValue, scope));

                    }
                } finally {
                    if (baseDns != null) {
                        baseDns.close();
                    }

                    if (filters != null) {
                        filters.close();
                    }
                }

            }

        }
        // return merged attributes
        return new ArrayList<String>(targetIds);
    } catch (NamingException e) {
        throw new DirectoryException("error computing LDAP references", e);
    }
}

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

@XNode("@scope")
public void setScope(String scope) throws DirectoryException {
    if (scope == null) {
        // default value: onelevel
        this.scope = SearchControls.ONELEVEL_SCOPE;
        return;//from  w  ww  .  j a  v a2s .  c  o  m
    }
    Integer searchScope = LdapScope.getIntegerScope(scope);
    if (searchScope == null) {
        // invalid scope
        throw new DirectoryException(
                "Invalid search scope: " + scope + ". Valid options: object, onelevel, subtree");
    }
    this.scope = searchScope.intValue();
}

From source file:org.nuxeo.wizard.RouterServlet.java

public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Context ctx = Context.instance(req);
    ParamCollector collector = ctx.getCollector();

    String refreshParam = req.getParameter("refresh");
    String directoryType = collector.getConfigurationParam("nuxeo.directory.type");

    if ("true".equals(refreshParam)) {
        currentPage.dispatchToJSP(req, resp);
        return;//w w  w . ja va2  s. com
    }

    if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam)
            || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) {
        try {
            if ("checkNetwork".equals(refreshParam)) {
                bindLdapConnection(collector, false);
                ctx.trackInfo("nuxeo.ldap.url", "info.host.found");
            } else if ("checkAuth".equals(refreshParam)) {
                bindLdapConnection(collector, true);
                ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success");
            } else {
                DirContext dirContext = new InitialDirContext(getContextEnv(collector, true));
                String searchScope;
                String searchBaseDn;
                String searchClass;
                String searchFilter;
                if ("checkUserLdapParam".equals(refreshParam)) {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope");
                    searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter");
                } else {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter");
                    searchClass = "";
                }

                SearchControls scts = new SearchControls();
                if ("onelevel".equals(searchScope)) {
                    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
                } else {
                    scts.setSearchScope(SearchControls.SUBTREE_SCOPE);
                }
                String filter = String.format("(&(%s)(objectClass=%s))",
                        searchFilter.isEmpty() ? "objectClass=*" : searchFilter,
                        searchClass.isEmpty() ? "*" : searchClass);
                NamingEnumeration<SearchResult> results;
                try {
                    results = dirContext.search(searchBaseDn, filter, scts);
                    if (!results.hasMore()) {
                        ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult");
                    } else {
                        SearchResult result = results.next();
                        if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) {
                            // try not to display the root of the search
                            // base DN
                            result = results.next();
                        }
                        ctx.trackInfo("dn", result.getNameInNamespace());
                        Attributes attributes = result.getAttributes();
                        NamingEnumeration<String> ids = attributes.getIDs();
                        String id;
                        StringBuilder sb;
                        while (ids.hasMore()) {
                            id = ids.next();
                            NamingEnumeration<?> values = attributes.get(id).getAll();
                            sb = new StringBuilder();
                            while (values.hasMore()) {
                                sb.append(values.next()).append(" , ");
                            }
                            ctx.trackInfo(id, sb.substring(0, sb.length() - 3));
                        }
                    }
                } catch (NameNotFoundException e) {
                    ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn");
                    log.warn(e);
                }
                dirContext.close();
            }
        } catch (AuthenticationException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.auth.failed");
            log.warn(e);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.url", "error.host.not.found");
            log.warn(e);
        }
    }

    // Form submit
    if (!"default".equals(directoryType) && refreshParam.isEmpty()) {
        // first check bind to LDAP server
        try {
            bindLdapConnection(collector, true);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed");
            log.warn(e);
        }

        // then check mandatory fields
        if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required");
        }
        String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage");
        if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) {
            if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required");
            }
        }
        if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) {
            if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required");
            }
            if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required");
            }
        }
    }

    if (ctx.hasErrors() || ctx.hasInfos()) {
        currentPage.dispatchToJSP(req, resp);
    } else {
        currentPage.next().dispatchToJSP(req, resp, true);
    }
}

From source file:org.opennms.web.springframework.security.UserGroupLdapAuthoritiesPopulator.java

@Override
public void setSearchSubtree(boolean searchSubtree) {
    super.setSearchSubtree(searchSubtree);
    int searchScope = searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE;
    this.searchControls.setSearchScope(searchScope);
}

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

/**
 * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int)
 *///from   ww w.  j a  v  a  2 s .com
@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:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Searches the remote directory for the user's entry and returns its distinguished name
 * string./*from w w w .jav  a  2s. c o  m*/
 * 
 * @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.orbeon.oxf.processor.LDAPProcessor.java

private int convertSearchScope(String scope) {
    if (scope != null && scope.toUpperCase().equals("SUBTREE")) {
        return SearchControls.SUBTREE_SCOPE;
    } else if (scope != null && scope.toUpperCase().equals("OBJECT")) {
        return SearchControls.OBJECT_SCOPE;
    } else if (scope != null
            && (scope.toUpperCase().equals("ALLLEVELS") || scope.toUpperCase().equals("ONELEVEL"))) {
        return SearchControls.ONELEVEL_SCOPE;
    } else {//  ww  w  .  j  ava 2s . c  o m
        return SearchControls.SUBTREE_SCOPE;
    }
}

From source file:org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator.java

/**
 * If set to true, a subtree scope search will be performed. If false a single-level
 * search is used./*www  . j a v a  2 s  .  c o  m*/
 *
 * @param searchSubtree set to true to enable searching of the entire tree below the
 * <tt>groupSearchBase</tt>.
 */
public void setSearchSubtree(boolean searchSubtree) {
    int searchScope = searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE;
    this.searchControls.setSearchScope(searchScope);
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Check if organizational unit is created in tenant.
 *
 * @param orgName           Organization name.
 * @param initialDirContext The directory connection.
 * @throws UserStoreException If an error occurred while searching.
 *//*  ww w.j av a 2  s  .  c  o m*/
protected boolean isOrganizationalUnitCreated(String orgName, DirContext initialDirContext)
        throws UserStoreException {

    //construct search filter,eg. (&(objectClass=organizationalUnit)(ou=wso2.com))
    String partitionDN = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ROOT_PARTITION);
    String organizationalObjectClass = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_OBJECT_CLASS);
    String organizationalAttribute = tenantMgtConfig.getTenantStoreProperties()
            .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_ATTRIBUTE);
    String searchFilter = "(&(objectClass=" + organizationalObjectClass + ")(" + organizationalAttribute + "="
            + orgName + "))";

    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    NamingEnumeration<SearchResult> userSearchResults = null;

    try {
        userSearchResults = initialDirContext.search(partitionDN, searchFilter, userSearchControl);
        return userSearchResults.hasMore();
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in root partition for organization : " + orgName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
}