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:net.e2.bw.servicereg.ldap.ServiceInstanceLdapService.java

/** Searches for service instance with the given filter and returns the given attributes */
public List<SearchResult> searchServiceInstances(String filter, Collection<String> attrs)
        throws NamingException {

    return ldapServerService.search(getConfig().getServiceInstanceSearchDN(), filter, attrs,
            SearchControls.ONELEVEL_SCOPE);
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private String performRoleSearch(String location, String roleName) {
    String val = null;
    try {/*w  w w  .  j a va  2 s .  co m*/

        DirContext dc = new InitialDirContext(env);
        SearchControls sc = new SearchControls();
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);

        //String filter = "(" + filterPrefix + roleName + ")";
        NamingEnumeration<SearchResult> ne = dc.search(location, roleName, sc);
        if (ne.hasMore()) {
            val = getAttrValue("memberOf", ne.next());
        }
        ne.close();
        dc.close();
    } catch (NamingException ne) {
        log.warn("Failed LDAP lookup getAttr", ne);
        log.warn("roleName:", roleName);
        log.warn("location:", location);
    }
    return val;

}

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

/**
 * get attribute values of given resource and attributes.
 * //from w ww . ja va  2 s  .  c o m
 * @param scope
 *            scope
 * @param id
 *            id of resource
 * @param attributeName
 *            attribute-name to retrieve
 * 
 * @return String attribute value
 * @throws NamingException
 * @throws IllegalAccessException
 */
public Map<String, String> getResourceAttributes(Scope scope, String id, String[] attributeNames)
        throws NamingException, IllegalAccessException {
    Map<String, String> returnMap = new HashMap<String, String>();
    String baseDn = null;
    String filter = getIdFilter(scope, id);
    int levelScope = 0;
    InitialLdapContext ctx = null;
    NamingEnumeration<SearchResult> results = null;
    if (scope == Scope.ORGANIZATION) {
        baseDn = LDAPConnector.getSingletonInstance().getInstitutionBaseDN();
        levelScope = SearchControls.SUBTREE_SCOPE;
    } else if (scope == Scope.PERSON) {
        baseDn = LDAPConnector.getSingletonInstance().getPersonBaseDN();
        levelScope = SearchControls.ONELEVEL_SCOPE;
    }
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        results = query(ctx, baseDn, filter, attributeNames, levelScope);
        if (results.hasMore()) {
            SearchResult searchResult = results.next();
            if (results.hasMore()) {
                throw new IllegalAccessException("found more than one object with id=" + id);
            }
            Attributes attributes = searchResult.getAttributes();
            for (int i = 0; i < attributeNames.length; i++) {
                Attribute attribute = attributes.get(attributeNames[i]);
                if (attribute == null) {
                    returnMap.put(attributeNames[i], (String) null);
                } else {
                    returnMap.put(attributeNames[i], (String) attribute.get());
                }
            }
            return returnMap;
        } else {
            throw new NameNotFoundException("id not found");
        }

    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
        if (results != null) {
            try {
                results.close();
            } catch (NamingException e) {
                LOG.log(Level.WARNING, null, e);
            }
        }
    }
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'.
 * The user repository must be queried for this because the password is never retrieved from the repository 
 * and the User object does not contain it.  
 * //from   w  w w  .j  a va2s  .  co m
 */
public boolean isPasswordStored(String userId) throws RepositoryException {
    if (StringUtils.isBlank(userId)) {
        logger.debug("Insufficient data for getting user info.");
        throw new IllegalArgumentException();
    }
    String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))";

    final String PASSWD_ATTR_NAME = "userPassword";
    boolean passwordStored = false;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(1);
    ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            if (attrs.get(PASSWD_ATTR_NAME) != null)
                passwordStored = true;
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }

    return passwordStored;
}

From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java

/**
 * {@inheritDoc}/* w w w . ja  va 2s  .com*/
 */
public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException {
    Map<String, String> idNameMap = new LinkedHashMap<String, String>();
    String text = censorHumanoidSearchPhrase(stub);
    String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))";
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setCountLimit(maxCount);
    ctls.setReturningAttributes(new String[] { "cn", "uid" });

    try {
        NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls);
        while (resultEnum.hasMoreElements()) {
            SearchResult result = resultEnum.next();
            Attributes attrs = result.getAttributes();
            idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get());
        }
    } catch (NamingException e) {
        throw new RepositoryException(e);
    }
    return idNameMap;
}

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

/**
 * Performs the specified operation and returns the results.
 *  /*w  w w  .jav  a2  s  .c o  m*/
 * @return - Depending on operation, DEFAULT_RESULT or read/search result (always XML)
 */
public String performOperation(String message, ParameterResolutionContext prc)
        throws SenderException, ParameterException {
    Map paramValueMap = null;
    String entryName = null;
    if (paramList != null && prc != null) {
        paramValueMap = prc.getValueMap(paramList);
        entryName = (String) paramValueMap.get("entryName");
        if (log.isDebugEnabled())
            log.debug("entryName=[" + entryName + "]");
    }
    if ((entryName == null || StringUtils.isEmpty(entryName)) && !getOperation().equals(OPERATION_CHALLENGE)) {
        throw new SenderException(
                "entryName must be defined through params, operation [" + getOperation() + "]");
    }
    if (getOperation().equals(OPERATION_READ)) {
        return performOperationRead(entryName, prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_UPDATE)) {
        return performOperationUpdate(entryName, prc, paramValueMap, parseAttributesFromMessage(message));
    } else if (getOperation().equals(OPERATION_CREATE)) {
        return performOperationCreate(entryName, prc, paramValueMap, parseAttributesFromMessage(message));
    } else if (getOperation().equals(OPERATION_DELETE)) {
        return performOperationDelete(entryName, prc, paramValueMap, parseAttributesFromMessage(message));
    } else if (getOperation().equals(OPERATION_SEARCH)) {
        return performOperationSearch(entryName, prc, paramValueMap, (String) paramValueMap.get(FILTER),
                SearchControls.ONELEVEL_SCOPE);
    } else if (getOperation().equals(OPERATION_DEEP_SEARCH)) {
        return performOperationSearch(entryName, prc, paramValueMap, (String) paramValueMap.get(FILTER),
                SearchControls.SUBTREE_SCOPE);
    } else if (getOperation().equals(OPERATION_SUB_CONTEXTS)) {
        return performOperationGetSubContexts(entryName, prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_GET_TREE)) {
        return performOperationGetTree(entryName, prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_CHALLENGE)) {
        return performOperationChallenge((String) paramValueMap.get("principal"), prc, paramValueMap);
    } else if (getOperation().equals(OPERATION_CHANGE_UNICODE_PWD)) {
        return performOperationChangeUnicodePwd(entryName, prc, paramValueMap);
    } else {
        throw new SenderException("unknown operation [" + getOperation() + "]");
    }
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

/**
 * Helper method to create the SearchControls instance
 *
 * @return the relevant SearchControls/*from  w w w  .j a va 2 s  .  c om*/
 */
protected SearchControls createSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    searchControls.setReturningAttributes(new String[] { "cn" });
    return searchControls;
}

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());
    }//  w ww.java2 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  w  w .j a va2 s .  c o  m
 *
 * @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.connection.core.io.jndi.LdifSearchLogger.java

/**
 * {@inheritDoc}//from  ww w.  ja va  2s .  co m
 */
public void logSearchRequest(Connection connection, String searchBase, String filter,
        SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, Control[] controls,
        long requestNum, NamingException ex) {
    if (!isSearchRequestLogEnabled()) {
        return;
    }

    String scopeAsString = searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "wholeSubtree (2)" //$NON-NLS-1$
            : searchControls.getSearchScope() == SearchControls.ONELEVEL_SCOPE ? "singleLevel (1)" //$NON-NLS-1$
                    : "baseObject (0)"; //$NON-NLS-1$
    String attributesAsString = searchControls.getReturningAttributes() == null ? "*" //$NON-NLS-1$
            : searchControls.getReturningAttributes().length == 0 ? "1.1" //$NON-NLS-1$
                            : StringUtils.join(searchControls.getReturningAttributes(), " ");
    String aliasAsString = aliasesDereferencingMethod == AliasDereferencingMethod.ALWAYS ? "derefAlways (3)" //$NON-NLS-1$
            : aliasesDereferencingMethod == AliasDereferencingMethod.FINDING ? "derefFindingBaseObj (2)" //$NON-NLS-1$
                    : aliasesDereferencingMethod == AliasDereferencingMethod.SEARCH ? "derefInSearching (1)" //$NON-NLS-1$
                            : "neverDerefAliases (0)"; //$NON-NLS-1$

    // build LDAP URL
    LdapUrl url = Utils.getLdapURL(connection, searchBase, searchControls.getSearchScope(), filter,
            searchControls.getReturningAttributes());

    // build command line
    String cmdLine = Utils.getLdapSearchCommandLine(connection, searchBase, searchControls.getSearchScope(),
            aliasesDereferencingMethod, searchControls.getCountLimit(), searchControls.getTimeLimit(), filter,
            searchControls.getReturningAttributes());

    // build 
    Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>();
    lines.add(LdifCommentLine.create("# LDAP URL     : " + url.toString())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# command line : " + cmdLine.toString())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# baseObject   : " + searchBase)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# scope        : " + scopeAsString)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# derefAliases : " + aliasAsString)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# sizeLimit    : " + searchControls.getCountLimit())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# timeLimit    : " + searchControls.getTimeLimit())); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# typesOnly    : " + "False")); //$NON-NLS-1$ //$NON-NLS-2$
    lines.add(LdifCommentLine.create("# filter       : " + filter)); //$NON-NLS-1$
    lines.add(LdifCommentLine.create("# attributes   : " + attributesAsString)); //$NON-NLS-1$
    if (controls != null) {
        for (Control control : controls) {
            lines.add(LdifCommentLine.create("# control      : " + control.getID())); //$NON-NLS-1$
        }
    }
    lines.add(LdifSepLine.create());

    String formattedString = ""; //$NON-NLS-1$
    for (LdifLineBase line : lines) {
        formattedString += line.toFormattedString(LdifFormatParameters.DEFAULT);
    }

    log(formattedString, "SEARCH REQUEST (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$
}