Example usage for javax.naming.directory SearchControls OBJECT_SCOPE

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

Introduction

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

Prototype

int OBJECT_SCOPE

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

Click Source Link

Document

Search the named object.

Usage

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *///from   w w w .  j a  v a2s.  com
@Test
public void testEnableAnonymousBindsOnRootDse() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons);

    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure that if anonymous binds are allowed a user may search
 * within a a partition./*from   w w  w .j  a v  a 2s . co  m*/
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAnonymousBindsEnabledBaseSearch() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("dc=apache,dc=org", "(objectClass=*)", cons);
    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertNotNull(result.getAttributes().get("dc"));
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Reproduces the problem with//ww  w.j  a  v  a2s  .  c  o m
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

private void processParameters(Parameter[] params) {
    Map parameters = new HashMap();
    for (int i = 0; i < params.length; i++) {
        Parameter parameter = params[i];
        parameters.put(parameter.getName(), parameter.getValue());
    }//from   w ww  .  j av a 2 s .  c  o m

    // Quiet param
    Boolean quietParam = (Boolean) parameters.get(QUIET_PARAMETER);
    if (quietParam != null) {
        setQuietEnabled(quietParam.booleanValue());
    }

    // Debug param
    Boolean debugParam = (Boolean) parameters.get(DEBUG_PARAMETER);
    if (debugParam != null) {
        setDebugEnabled(debugParam.booleanValue());
    }

    // Verbose param
    Boolean verboseParam = (Boolean) parameters.get(VERBOSE_PARAMETER);
    if (verboseParam != null) {
        setVerboseEnabled(verboseParam.booleanValue());
    }

    // Install-path param
    String installPathParam = (String) parameters.get(INSTALLPATH_PARAMETER);
    if (installPathParam != null) {
        try {
            setLayout(installPathParam);
            if (!isQuietEnabled()) {
                notifyOutputListener("loading settings from: " + getLayout().getConfigurationFile());
            }
            ApplicationContext factory = null;
            URL configUrl;

            configUrl = getLayout().getConfigurationFile().toURL();
            factory = new FileSystemXmlApplicationContext(configUrl.toString());
            setConfiguration((ServerStartupConfiguration) factory.getBean("configuration"));
        } catch (MalformedURLException e) {
            notifyErrorListener(e.getMessage());
            notifyExceptionListener(e);
        }
    }

    // Host param
    String hostParam = (String) parameters.get(HOST_PARAMETER);
    if (hostParam != null) {
        host = hostParam;
    } else {
        host = DEFAULT_HOST;

        if (isDebugEnabled()) {
            notifyOutputListener("host set to default: " + host);
        }
    }

    // Port param
    Integer portParam = (Integer) parameters.get(PORT_PARAMETER);
    if (portParam != null) {
        port = portParam.intValue();
    }
    // else if ( getConfiguration() != null )
    // {
    // port = getConfiguration().getLdapConfiguration().getIpPort();
    //
    // if ( isDebugEnabled() )
    // {
    // notifyOutputListener( "port overriden by server.xml configuration: " +
    // port );
    // }
    // }
    else {
        port = DEFAULT_PORT;

        if (isDebugEnabled()) {
            notifyOutputListener("port set to default: " + port);
        }
    }

    // User param
    String userParam = (String) parameters.get(USER_PARAMETER);
    if (userParam != null) {
        user = userParam;
    } else {
        user = DEFAULT_USER;

        if (isDebugEnabled()) {
            notifyOutputListener("user set to default: " + user);
        }
    }

    // Password param
    String passwordParam = (String) parameters.get(PASSWORD_PARAMETER);
    if (passwordParam != null) {
        password = passwordParam;
    } else {
        password = DEFAULT_PASSWORD;

        if (isDebugEnabled()) {
            notifyOutputListener("password set to default: " + password);
        }
    }

    // Auth param
    String authParam = (String) parameters.get(AUTH_PARAMETER);
    if (authParam != null) {
        auth = authParam;
    } else {
        auth = DEFAULT_AUTH;

        if (isDebugEnabled()) {
            notifyOutputListener("authentication type set to default: " + auth);
        }
    }

    // Base DN param
    String baseDNParam = (String) parameters.get(BASEDN_PARAMETER);
    if (baseDNParam != null) {
        baseDN = baseDNParam;
    } else {
        baseDN = DEFAULT_BASEDN;

        if (isDebugEnabled()) {
            notifyOutputListener("base DN set to default: " + baseDN);
        }
    }

    // Export Point param
    String exportPointParam = (String) parameters.get(EXPORTPOINT_PARAMETER);
    if (exportPointParam != null) {
        exportPoint = exportPointParam;
    } else {
        exportPoint = DEFAULT_EXPORTPOINT;

        if (isDebugEnabled()) {
            notifyOutputListener("export point set to default: " + exportPoint);
        }
    }

    // scope param
    String scopeParam = (String) parameters.get(SCOPE_PARAMETER);
    if (scopeParam != null) {
        if (scopeParam.equals(SCOPE_OBJECT)) {
            scope = SearchControls.OBJECT_SCOPE;
        } else if (scopeParam.equals(SCOPE_ONELEVEL)) {
            scope = SearchControls.ONELEVEL_SCOPE;
        } else if (scopeParam.equals(SCOPE_SUBTREE)) {
            scope = SearchControls.SUBTREE_SCOPE;
        }
    } else {
        scope = DEFAULT_SCOPE;

        if (isDebugEnabled()) {
            notifyOutputListener("scope set to default: " + scope);
        }
    }

    // LdifFile param
    String ldifFileParam = (String) parameters.get(FILE_PARAMETER);
    if (ldifFileParam != null) {
        ldifFileName = ldifFileParam;
    }
}

From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java

/**
 * Converts the search scope.//from  w  ww.j  a v  a 2s . c  om
 *
 * @param searchControls
 *      the search controls
 * @return
 *      the associated search scope
 */
private SearchScope convertSearchScope(SearchControls searchControls) {
    int scope = searchControls.getSearchScope();
    if (scope == SearchControls.OBJECT_SCOPE) {
        return SearchScope.OBJECT;
    } else if (scope == SearchControls.ONELEVEL_SCOPE) {
        return SearchScope.ONELEVEL;
    } else if (scope == SearchControls.SUBTREE_SCOPE) {
        return SearchScope.SUBTREE;
    } else {
        return SearchScope.SUBTREE;
    }
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java

/**
 * Returns the {@link SearchControls} object associated with the request.
 *
 * @param request// w w w . j  a v a2  s . c  o m
 *      the search request
 * @return
 *      the associated {@link SearchControls} object
 */
private SearchControls getSearchControls(SearchRequest request) {
    SearchControls controls = new SearchControls();

    // Scope
    switch (request.getScope()) {
    case OBJECT:
        controls.setSearchScope(SearchControls.OBJECT_SCOPE);
        break;
    case ONELEVEL:
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        break;
    case SUBTREE:
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        break;
    default:
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }

    // Returning attributes
    List<String> returningAttributes = new ArrayList<String>();
    for (String attribute : request.getAttributes()) {
        returningAttributes.add(attribute);
    }
    // If the returning attributes are empty, we need to return the user attributes
    // [Cf. RFC 2251 - "There are two special values which may be used: an empty 
    //  list with no attributes, and the attribute description string '*'.  Both of 
    //  these signify that all user attributes are to be returned."]
    if (returningAttributes.size() == 0) {
        returningAttributes.add("*"); //$NON-NLS-1$
    }

    controls.setReturningAttributes(returningAttributes.toArray(new String[0]));

    // Size Limit
    controls.setCountLimit(request.getSizeLimit());

    // Time Limit
    controls.setTimeLimit(request.getTimeLimit());

    return controls;
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

@Override
public void configure(String id, Properties properties) throws PIPException {
    /*//from w w w . j  a va 2  s  .c o m
     * Handle the standard properties
     */
    super.configure(id, properties);
    String propertyPrefix = id + ".";

    /*
     * Configure the LDAP environment: I think the only required property is the provider_url
     */
    if (!this.configureStringProperty(propertyPrefix, Context.PROVIDER_URL, properties, null)) {
        throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                + propertyPrefix + Context.PROVIDER_URL);
    }
    this.configureStringProperty(propertyPrefix, Context.AUTHORITATIVE, properties, null);
    this.configureIntegerProperty(propertyPrefix, Context.BATCHSIZE, properties, null);
    this.configureStringProperty(propertyPrefix, Context.DNS_URL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.INITIAL_CONTEXT_FACTORY, properties,
            DEFAULT_CONTEXT_FACTORY);
    this.configureStringProperty(propertyPrefix, Context.LANGUAGE, properties, null);
    this.configureStringProperty(propertyPrefix, Context.OBJECT_FACTORIES, properties, null);
    this.configureStringProperty(propertyPrefix, Context.REFERRAL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_AUTHENTICATION, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_CREDENTIALS, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_PRINCIPAL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_PROTOCOL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.STATE_FACTORIES, properties, null);
    this.configureStringProperty(propertyPrefix, Context.URL_PKG_PREFIXES, properties, null);

    String ldapScopeValue = properties.getProperty(propertyPrefix + PROP_LDAP_SCOPE, DEFAULT_SCOPE);
    if (LDAP_SCOPE_SUBTREE.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.SUBTREE_SCOPE;
    } else if (LDAP_SCOPE_OBJECT.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.OBJECT_SCOPE;
    } else if (LDAP_SCOPE_ONELEVEL.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.ONELEVEL_SCOPE;
    } else {
        this.logger.warn("Invalid LDAP Scope value '" + ldapScopeValue + "'; using " + DEFAULT_SCOPE);
        this.ldapScope = SearchControls.SUBTREE_SCOPE;
    }

    /*
     * Get list of resolvers defined for this LDAP Engine
     */
    String resolversList = properties.getProperty(propertyPrefix + PROP_RESOLVERS);
    if (resolversList == null || resolversList.isEmpty()) {
        throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                + propertyPrefix + PROP_RESOLVERS);
    }

    /*
     * Iterate the resolvers
     */
    for (String resolver : Splitter.on(',').trimResults().omitEmptyStrings().split(resolversList)) {
        /*
         * Get the LDAPResolver for this LDAPEngine
         */
        String resolverClassName = properties
                .getProperty(propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname");
        if (resolverClassName == null) {
            throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                    + propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname");
        }

        LDAPResolver ldapResolverNew = null;
        try {
            Class<?> classResolver = Class.forName(resolverClassName);
            if (!LDAPResolver.class.isAssignableFrom(classResolver)) {
                this.logger.error("LDAPResolver class " + resolverClassName + " does not implement "
                        + LDAPResolver.class.getCanonicalName());
                throw new PIPException("LDAPResolver class " + resolverClassName + " does not implement "
                        + LDAPResolver.class.getCanonicalName());
            }
            ldapResolverNew = LDAPResolver.class.cast(classResolver.newInstance());
        } catch (Exception ex) {
            this.logger.error("Exception instantiating LDAPResolver for class '" + resolverClassName + "': "
                    + ex.getMessage(), ex);
            throw new PIPException("Exception instantiating LDAPResolver for class '" + resolverClassName + "'",
                    ex);
        }
        assert ldapResolverNew != null;
        ldapResolverNew.configure(propertyPrefix + PROP_RESOLVER + "." + resolver, properties,
                this.getIssuer());

        this.ldapResolvers.add(ldapResolverNew);
    }

}

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

/**
 * Performs an LDAP compare operation of the value of an attribute for a particular directory entry.
 *
 * @param dn the entry who's attribute is to be used
 * @param attributeName the attribute who's value we want to compare
 * @param value the value to be checked against the directory value
 *
 * @return true if the supplied value matches that in the directory
 *//*from  ww  w  .  j av a 2  s . com*/
public boolean compare(final String dn, final String attributeName, final Object value) {
    final String comparisonFilter = "(" + attributeName + "={0})";

    class LdapCompareCallback implements ContextExecutor {

        public Object executeWithContext(DirContext ctx) throws NamingException {
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(NO_ATTRS);
            ctls.setSearchScope(SearchControls.OBJECT_SCOPE);

            NamingEnumeration<SearchResult> results = ctx.search(dn, comparisonFilter, new Object[] { value },
                    ctls);

            Boolean match = Boolean.valueOf(results.hasMore());
            LdapUtils.closeEnumeration(results);

            return match;
        }
    }

    Boolean matches = (Boolean) executeReadOnly(new LdapCompareCallback());

    return matches.booleanValue();
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

@SuppressWarnings("nls")
private SearchControls getSearchControls() {
    SearchControls sc = new SearchControls();
    if ("base".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    } else if ("onelevel".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    } else if ("subtree".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    }/*from   w w w.j  a  v a2  s  .c  o  m*/
    sc.setReturningAttributes(LDAPAttributeNames.getAll());
    return sc;
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

private MetricValue getMetric(Metric metric, String tree, String attr)
        throws MetricNotFoundException, NamingException {
    NamingEnumeration enumer = null;
    try {/*from  www .jav  a  2s .c om*/
        String[] a = { attr };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons);
        while (enumer.hasMore()) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            Attribute val;
            if (null != (val = attrs.get(attr))) {
                return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis());
            }
        }
        throw new MetricNotFoundException("");
    } finally {
        if (enumer != null) {
            enumer.close();
        }
    }
}