Example usage for javax.naming.directory SearchControls SUBTREE_SCOPE

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

Introduction

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

Prototype

int SUBTREE_SCOPE

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

Click Source Link

Document

Search the entire subtree rooted at the named object.

Usage

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.remove", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> removeUser(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    UserDn userDn = nameHelper.newUserDnFromId(userId);

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(sr.getNameInNamespace());
        dca.removeAttributeValue("uniqueMember", userDn.toString());
        userDirContext.modifyAttributes(sr.getNameInNamespace(), dca.getModificationItems());
    }/*from  w w  w.ja  v  a 2s.  c  o m*/

    userDirContext.unbind(userDn);

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("success", true);

    return response;
}

From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java

/**
 *
 *//*www . j a  v  a  2 s .c  o m*/
public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames, String profileName)
        throws UserStoreException {

    String userAttributeSeparator = ",";
    String userDN = null;
    LdapName ldn = (LdapName) userCache.get(userName);

    if (ldn == null) {
        // read list of patterns from user-mgt.xml
        String patterns = realmConfig.getUserStoreProperty(LDAPConstants.USER_DN_PATTERN);

        if (patterns != null && !patterns.isEmpty()) {

            if (log.isDebugEnabled()) {
                log.debug("Using User DN Patterns " + patterns);
            }

            if (patterns.contains("#")) {
                userDN = getNameInSpaceForUserName(userName);
            } else {
                userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName));
            }
        }
    } else {
        userDN = ldn.toString();
    }

    Map<String, String> values = new HashMap<String, String>();
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }

    DirContext dirContext = this.connectionSource.getContext();
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;
    try {
        if (userDN != null) {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            if (propertyNames != null && propertyNames.length > 0) {
                searchCtls.setReturningAttributes(propertyNames);
            }
            if (log.isDebugEnabled()) {
                try {
                    log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: "
                            + dirContext.getNameInNamespace());
                } catch (NamingException e) {
                    log.debug("Error while getting DN of search base", e);
                }
                if (propertyNames == null) {
                    log.debug("No attributes requested");
                } else {
                    for (String attribute : propertyNames) {
                        log.debug("Requesting attribute :" + attribute);
                    }
                }
            }
            try {
                answer = dirContext.search(escapeDNForSearch(userDN), searchFilter, searchCtls);
            } catch (PartialResultException e) {
                // can be due to referrals in AD. so just ignore error
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (isIgnorePartialResultException()) {
                    if (log.isDebugEnabled()) {
                        log.debug(errorMessage, e);
                    }
                } else {
                    throw new UserStoreException(errorMessage, e);
                }
            } catch (NamingException e) {
                String errorMessage = "Error occurred while searching directory context for user : " + userDN
                        + " searchFilter : " + searchFilter;
                if (log.isDebugEnabled()) {
                    log.debug(errorMessage, e);
                }
                throw new UserStoreException(errorMessage, e);
            }
        } else {
            answer = this.searchForUser(searchFilter, propertyNames, dirContext);
        }
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                for (String name : propertyNames) {
                    if (name != null) {
                        Attribute attribute = attributes.get(name);
                        if (attribute != null) {
                            StringBuffer attrBuffer = new StringBuffer();
                            for (attrs = attribute.getAll(); attrs.hasMore();) {
                                Object attObject = attrs.next();
                                String attr = null;
                                if (attObject instanceof String) {
                                    attr = (String) attObject;
                                } else if (attObject instanceof byte[]) {
                                    //if the attribute type is binary base64 encoded string will be returned
                                    attr = new String(Base64.encodeBase64((byte[]) attObject));
                                }

                                if (attr != null && attr.trim().length() > 0) {
                                    String attrSeparator = realmConfig
                                            .getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                                    if (attrSeparator != null && !attrSeparator.trim().isEmpty()) {
                                        userAttributeSeparator = attrSeparator;
                                    }
                                    attrBuffer.append(attr + userAttributeSeparator);
                                }
                                String value = attrBuffer.toString();

                                /*
                                 * Length needs to be more than userAttributeSeparator.length() for a valid
                                 * attribute, since we
                                 * attach userAttributeSeparator
                                 */
                                if (value != null && value.trim().length() > userAttributeSeparator.length()) {
                                    value = value.substring(0,
                                            value.length() - userAttributeSeparator.length());
                                    values.put(name, value);
                                }

                            }
                        }
                    }
                }
            }
        }

    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user property values for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        // close the naming enumeration and free up resources
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }
    return values;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * For a given name, this method makes ldap search in userBase with filter {@link #userIdAttribute}=name and objectClass={@link #userObjectClass}
 * and builds {@link User} based on search result.
 *
 * @param name//from w w  w  . j  a v a  2s .co m
 *            The userId which should be value of the field {@link #userIdAttribute}
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the user was searched. Return null if such a user was not found.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser searchAndBuildUser(String name) throws NamingException {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { userIdAttribute });
    sc.setCountLimit(1);

    StringBuilder builderFilter = new StringBuilder("(&(");
    builderFilter.append(userIdAttribute).append("=").append(name).append(")").append("(objectClass=")
            .append(userObjectClass).append(")");

    if (StringUtils.isNotEmpty(filter)) {
        builderFilter.append(filter).append(")");
    } else {
        builderFilter.append(")");
    }

    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, builderFilter.toString(), sc);

    if (!sr.hasMore())
        return null;

    SearchResult r = sr.next();
    Attribute userName = r.getAttributes().get(userIdAttribute);

    if (!restriction.isActivated() || userInGroupsMembershipList(r.getNameInNamespace(),
            restriction.getGroupMembershipLists(ldapContext)))
        return new ReadOnlyLDAPUser(userName.get().toString(), r.getNameInNamespace(), ldapContext);

    return null;
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from  ww w .ja  v  a 2 s  .co  m
public void loadGroupByAccountName(DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aGroupBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aGroupBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);
    String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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

/**
 * get attribute values of given resource and attributes.
 * //from  ww w.j av a 2  s.com
 * @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:org.lsc.jndi.JndiServices.java

/**
 * Search for an entry./*from  ww w.j av  a 2s .  c om*/
 *
 * This method is a simple LDAP search operation with SUBTREE search
 * control
 *
 * @param base the base of the search operation
 * @param filter  the filter of the search operation
 * @param sc the search controls
 * @return the entry or null if not found
 * @throws NamingException
 *                 thrown if something goes wrong
 */
public SearchResult getEntry(final String base, final String filter, final SearchControls sc)
        throws NamingException {
    return getEntry(base, filter, sc, SearchControls.SUBTREE_SCOPE);
}

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

/**
 * Returns the {@link SearchControls} object associated with the request.
 *
 * @param request//from  w ww . j  a v  a 2  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.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isValidPassword(String serverName, Object existingCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;/*from w ww .j a  va  2 s  . co  m*/
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    //first search the existing user entry.
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);
        // here we assume only one user
        while (namingEnumeration.hasMore()) {

            SearchResult searchResult = namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);

            NamingEnumeration passwords = userPassword.getAll();

            String passwordHashMethod = null;
            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod));
            }
        }

    } catch (NamingException e) {
        log.error("Failed, validating password. Can not access the directory service", e);
        throw new DirectoryServerManagerException(
                "Failed, validating password. " + "Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }

    return false;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@SuppressWarnings("rawtypes")
@Override//from  www  .  j a va2s .  c om
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        SearchResult searchResult = null;
        String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java

private NamingEnumeration search(ManagedSystemObjectMatch matchObj, LdapContext ctx, String searchValue,
        String[] attrAry) throws NamingException {
    SearchControls searchCtls = new SearchControls();

    searchCtls.setReturningAttributes(attrAry);

    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    String searchFilter = matchObj.getSearchFilter();
    // replace the place holder in the search filter
    searchFilter = searchFilter.replace("?", searchValue);

    System.out.println("Search Filter=" + searchFilter);
    System.out.println("BaseDN=" + matchObj.getBaseDn());

    return ctx.search(matchObj.getSearchBaseDn(), searchFilter, searchCtls);

}