Example usage for javax.naming.directory DirContext search

List of usage examples for javax.naming.directory DirContext search

Introduction

In this page you can find the example usage for javax.naming.directory DirContext search.

Prototype

public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons)
        throws NamingException;

Source Link

Document

Searches in the named context or object for entries that satisfy the given search filter.

Usage

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

@Override
public void doDeleteUserClaimValue(String userName, String claimURI, String profileName)
        throws UserStoreException {

    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    try {/*from   www . j a va  2s  .co m*/

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI
        String attributeName = null;
        attributeName = getClaimAtrribute(claimURI, userName, null);

        Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);

        updatedAttributes.put(currentUpdatedAttribute);

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

@Override
public void doDeleteUserClaimValues(String userName, String[] claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    try {//from w w  w  . ja va2 s . c o  m

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        if (returnedResultList.hasMore()) {
            returnedUserEntry = returnedResultList.next().getName();
        }

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);
        // if there is no attribute for profile configuration in LDAP, skip
        // updating it.
        // get the claimMapping related to this claimURI

        for (String claimURI : claims) {
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            updatedAttributes.put(currentUpdatedAttribute);
        }

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes);

    } catch (Exception e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

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

/**
 * Reused methods to search users with various filters
 *
 * @param searchFilter/*from   w  ww  .ja  va  2  s .  com*/
 * @param returningAttributes
 * @param searchScope
 * @return
 */
private NamingEnumeration<SearchResult> searchInUserBase(String searchFilter, String[] returningAttributes,
        int searchScope, DirContext rootContext) throws UserStoreException {

    if (log.isDebugEnabled()) {
        log.debug("Searching user with " + searchFilter);
    }
    String userBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> userSearchResults = null;

    try {
        userSearchResults = rootContext.search(escapeDNForSearch(userBase), searchFilter, userSearchControl);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in user base.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }

    return userSearchResults;

}

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

/**
 * Reused method to search groups with various filters.
 *
 * @param searchFilter//from  w w  w  .ja  va  2  s  . c  o  m
 * @param returningAttributes
 * @param searchScope
 * @return
 */
protected NamingEnumeration<SearchResult> searchInGroupBase(String searchFilter, String[] returningAttributes,
        int searchScope, DirContext rootContext, String searchBase) throws UserStoreException {
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> groupSearchResults = null;
    try {
        groupSearchResults = rootContext.search(escapeDNForSearch(searchBase), searchFilter, userSearchControl);
    } catch (NamingException e) {
        String errorMessage = "Error occurred while searching in group base.";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }

    return groupSearchResults;
}

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.
 *//*from  w  w  w. j  av a  2  s  .com*/
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);
    }
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeActors(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws Exception {
    int changesCount = 0;
    List<Actor> existingActorsList = executorDao.getAllActors(BatchPresentationFactory.ACTORS.createNonPaged());
    Map<String, Actor> existingActorsMap = Maps.newHashMap();
    for (Actor actor : existingActorsList) {
        existingActorsMap.put(actor.getName().toLowerCase(), actor);
    }/*from w  w  w.  j a  va2  s .c o m*/
    Set<Actor> ldapActorsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        ldapActorsToDelete.addAll(executorDao.getGroupActors(importGroup));
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        List<SearchResult> resultList = Lists.newArrayList();
        try {
            NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_USER_FILTER, controls);
            while (list.hasMore()) {
                SearchResult searchResult = list.next();
                resultList.add(searchResult);
            }
            list.close();
        } catch (SizeLimitExceededException e) {
            resultList.clear();
            for (String y : ALPHABETS) {
                NamingEnumeration<SearchResult> list = dirContext.search(ou,
                        MessageFormat.format(LOGIN_FIRST_LETTER_FILTER, ATTR_ACCOUNT_NAME, y, y.toLowerCase(),
                                OBJECT_CLASS_USER_FILTER),
                        controls);
                while (list.hasMore()) {
                    SearchResult searchResult = list.next();
                    resultList.add(searchResult);
                }
                list.close();
            }
        }
        for (SearchResult searchResult : resultList) {
            String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
            String description = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDescriptionAttribute());
            String fullName = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserFullNameAttribute());
            String email = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserEmailAttribute());
            String phone = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserPhoneAttribute());
            String title = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserTitleAttribute());
            String department = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDepartmentAttribute());
            ToStringHelper toStringHelper = MoreObjects.toStringHelper("user info");
            toStringHelper.add("name", name).add("description", description).add("fullName", fullName)
                    .add("email", email);
            toStringHelper.add("phone", phone).add("title", title).add("department", department)
                    .omitNullValues();
            log.debug("Read " + toStringHelper.toString());
            Actor actor = existingActorsMap.get(name.toLowerCase());
            if (actor == null) {
                if (!LdapProperties.isSynchronizationCreateExecutors()) {
                    continue;
                }
                actor = new Actor(name, description, fullName, null, email, phone, title, department);
                log.info("Creating " + actor);
                executorDao.create(actor);
                executorDao.addExecutorsToGroup(Lists.newArrayList(actor), importGroup);
                permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), actor);
                changesCount++;
            } else {
                ldapActorsToDelete.remove(actor);
                if (LdapProperties.isSynchronizationUpdateExecutors()) {
                    List<IChange> changes = Lists.newArrayList();
                    if (isAttributeNeedsChange(description, actor.getDescription())) {
                        changes.add(new AttributeChange("description", actor.getDescription(), description));
                        actor.setDescription(description);
                    }
                    if (isAttributeNeedsChange(fullName, actor.getFullName())) {
                        changes.add(new AttributeChange("fullName", actor.getFullName(), fullName));
                        actor.setFullName(fullName);
                    }
                    if (isAttributeNeedsChange(email, actor.getEmail())) {
                        changes.add(new AttributeChange("email", actor.getEmail(), email));
                        actor.setEmail(email);
                    }
                    if (isAttributeNeedsChange(phone, actor.getPhone())) {
                        changes.add(new AttributeChange("phone", actor.getPhone(), phone));
                        actor.setPhone(phone);
                    }
                    if (isAttributeNeedsChange(title, actor.getTitle())) {
                        changes.add(new AttributeChange("title", actor.getTitle(), title));
                        actor.setTitle(title);
                    }
                    if (isAttributeNeedsChange(department, actor.getDepartment())) {
                        changes.add(new AttributeChange("department", actor.getDepartment(), department));
                        actor.setDepartment(department);
                    }
                    if (!actor.isActive()) {
                        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
                            actor.setActive(true);
                            changes.add(new AttributeChange("active", "false", "true"));
                        }
                        if (executorDao.removeExecutorFromGroup(actor, wasteGroup)) {
                            changes.add(new Change("waste group removal"));
                        }
                        if (executorDao.addExecutorToGroup(actor, importGroup)) {
                            changes.add(new Change("import group addition"));
                        }
                    }
                    if (!changes.isEmpty()) {
                        executorDao.update(actor);
                        log.info("Updating " + actor + ": " + changes);
                        changesCount++;
                    }
                }
            }
            actorsByDistinguishedName.put(searchResult.getNameInNamespace(), actor);
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapActorsToDelete.size() > 0) {
        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
            for (Actor actor : ldapActorsToDelete) {
                actor.setActive(false);
                executorDao.update(actor);
                log.info("Inactivating " + actor);
                changesCount++;
            }
        }
        executorDao.removeExecutorsFromGroup(ldapActorsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapActorsToDelete, wasteGroup);
        changesCount += ldapActorsToDelete.size();
    }
    return changesCount;
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeGroups(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws NamingException {
    int changesCount = 0;
    List<Group> existingGroupsList = executorDao.getAllGroups();
    Map<String, Group> existingGroupsByLdapNameMap = Maps.newHashMap();
    for (Group group : existingGroupsList) {
        if (!Strings.isNullOrEmpty(group.getLdapGroupName())) {
            existingGroupsByLdapNameMap.put(group.getLdapGroupName(), group);
        }/*  w  w  w  .j av a  2 s .co  m*/
    }
    Set<Group> ldapGroupsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        Set<Executor> ldapExecutors = executorDao.getGroupChildren(importGroup);
        for (Executor executor : ldapExecutors) {
            if (executor instanceof Group) {
                ldapGroupsToDelete.add((Group) executor);
            }
        }
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    Map<String, SearchResult> groupResultsByDistinguishedName = Maps.newHashMap();
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_GROUP_FILTER, controls);
        while (list.hasMore()) {
            SearchResult searchResult = list.next();
            if (searchResult.getAttributes().get(ATTR_GROUP_MEMBER) == null) {
                continue;
            }
            groupResultsByDistinguishedName.put(searchResult.getNameInNamespace(), searchResult);
        }
    }
    for (SearchResult searchResult : groupResultsByDistinguishedName.values()) {
        String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
        String description = getStringAttribute(searchResult,
                LdapProperties.getSynchronizationGroupDescriptionAttribute());
        ToStringHelper toStringHelper = MoreObjects.toStringHelper("group info");
        toStringHelper.add("name", name).add("description", description).omitNullValues();
        log.debug("Read " + toStringHelper.toString());
        Group group = existingGroupsByLdapNameMap.get(name);
        if (group == null) {
            if (!LdapProperties.isSynchronizationCreateExecutors()) {
                continue;
            }
            group = new Group(name, description);
            group.setLdapGroupName(name);
            log.info("Creating " + group);
            executorDao.create(group);
            executorDao.addExecutorsToGroup(Lists.newArrayList(group), importGroup);
            permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), group);
            changesCount++;
        } else {
            ldapGroupsToDelete.remove(group);
            if (LdapProperties.isSynchronizationUpdateExecutors()) {
                List<IChange> changes = Lists.newArrayList();
                if (isAttributeNeedsChange(description, group.getDescription())) {
                    changes.add(new AttributeChange("description", group.getDescription(), description));
                    group.setDescription(description);
                    executorDao.update(group);
                }
                if (executorDao.removeExecutorFromGroup(group, wasteGroup)) {
                    changes.add(new Change("waste group removal"));
                }
                if (executorDao.addExecutorToGroup(group, importGroup)) {
                    changes.add(new Change("import group addition"));
                }
                if (!changes.isEmpty()) {
                    log.info("Updating " + group + ": " + changes);
                    changesCount++;
                }
            }
        }

        Set<Actor> actorsToDelete = Sets.newHashSet(executorDao.getGroupActors(group));
        Set<Actor> actorsToAdd = Sets.newHashSet();
        Set<Actor> groupTargetActors = Sets.newHashSet();
        fillTargetActorsRecursively(dirContext, groupTargetActors, searchResult,
                groupResultsByDistinguishedName, actorsByDistinguishedName);
        for (Actor targetActor : groupTargetActors) {
            if (!actorsToDelete.remove(targetActor)) {
                actorsToAdd.add(targetActor);
            }
        }
        if (actorsToAdd.size() > 0) {
            log.info("Adding to " + group + ": " + actorsToAdd);
            executorDao.addExecutorsToGroup(actorsToAdd, group);
            changesCount++;
        }
        if (actorsToDelete.size() > 0) {
            executorDao.removeExecutorsFromGroup(Lists.newArrayList(actorsToDelete), group);
            changesCount++;
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapGroupsToDelete.size() > 0) {
        executorDao.removeExecutorsFromGroup(ldapGroupsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapGroupsToDelete, wasteGroup);
        log.info("Inactivating " + ldapGroupsToDelete);
        changesCount += ldapGroupsToDelete.size();
    }
    return changesCount;
}

From source file:security.AuthenticationManager.java

public static Map<String, String> getUserAttributes(DirContext ctx, String searchBase, String userName,
        String principalDomain, String... attributeNames) throws NamingException {
    if (StringUtils.isBlank(userName)) {
        throw new IllegalArgumentException("Username and password can not be blank.");
    }/*w  w  w . ja  va2 s  . co m*/

    if (attributeNames.length == 0) {
        return Collections.emptyMap();
    }

    Attributes matchAttr = new BasicAttributes(true);
    BasicAttribute basicAttr = new BasicAttribute("userPrincipalName", userName + principalDomain);
    matchAttr.put(basicAttr);

    NamingEnumeration<? extends SearchResult> searchResult = ctx.search(searchBase, matchAttr, attributeNames);

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

    Map<String, String> result = new HashMap<>();

    if (searchResult.hasMore()) {
        NamingEnumeration<? extends Attribute> attributes = searchResult.next().getAttributes().getAll();

        while (attributes.hasMore()) {
            Attribute attr = attributes.next();
            String attrId = attr.getID();
            String attrValue = (String) attr.get();

            result.put(attrId, attrValue);
        }
    }
    return result;
}