Example usage for javax.naming.directory SearchControls SearchControls

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

Introduction

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

Prototype

public SearchControls() 

Source Link

Document

Constructs a search constraints using defaults.

Usage

From source file:org.projectforge.business.ldap.LdapUserDao.java

public LdapUser findByUsername(final Object username, final String... organizationalUnits) {
    return (LdapUser) new LdapTemplate(ldapConnector) {
        @Override//from   www.ja v a  2s  .  c o m
        protected Object call() throws NameNotFoundException, Exception {
            NamingEnumeration<?> results = null;
            final SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            final String searchBase = getSearchBase(organizationalUnits);
            results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))",
                    controls);
            if (results.hasMore() == false) {
                return null;
            }
            final SearchResult searchResult = (SearchResult) results.next();
            final String dn = searchResult.getName();
            final Attributes attributes = searchResult.getAttributes();
            if (results.hasMore() == true) {
                log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
            }
            return mapToObject(dn, searchBase, attributes);
        }
    }.excecute();
}

From source file:com.dtolabs.rundeck.jetty.jaas.JettyCachingLdapLoginModule.java

private ConcurrentHashMap<String, List<String>> buildRoleMemberOfMap(DirContext dirContext) {
    Object[] filterArguments = { _roleObjectClass };
    SearchControls ctls = new SearchControls();
    ctls.setDerefLinkFlag(true);//from  w ww  . j  av  a2 s .  c o m
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    ConcurrentHashMap<String, List<String>> roleMemberOfMap = new ConcurrentHashMap<String, List<String>>();

    try {
        NamingEnumeration<SearchResult> results = dirContext.search(_roleBaseDn, _roleMemberFilter, ctls);
        while (results.hasMoreElements()) {
            SearchResult result = results.nextElement();
            Attributes attributes = result.getAttributes();

            if (attributes == null) {
                continue;
            }

            Attribute roleAttribute = attributes.get(_roleNameAttribute);
            Attribute memberAttribute = attributes.get(_roleMemberAttribute);

            if (roleAttribute == null || memberAttribute == null) {
                continue;
            }

            NamingEnumeration role = roleAttribute.getAll();
            NamingEnumeration members = memberAttribute.getAll();

            if (!role.hasMore() || !members.hasMore()) {
                continue;
            }

            String roleName = (String) role.next();
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                roleName = roleName.replace(_rolePrefix, "");
            }

            while (members.hasMore()) {
                String member = (String) members.next();
                Matcher roleMatcher = rolePattern.matcher(member);
                if (!roleMatcher.find()) {
                    continue;
                }
                String roleMember = roleMatcher.group(1);
                List<String> memberOf;
                if (roleMemberOfMap.containsKey(roleMember)) {
                    memberOf = roleMemberOfMap.get(roleMember);
                } else {
                    memberOf = new ArrayList<String>();
                }

                memberOf.add(roleName);

                roleMemberOfMap.put(roleMember, memberOf);
            }

        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return roleMemberOfMap;
}

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

/**
 * This method overwrites the method in LDAPUserStoreManager. This implements the functionality
 * of updating user's profile information in LDAP user store.
 *
 * @param userName//from   w  w w. ja  v a  2 s.c  om
 * @param claims
 * @param profileName
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public void doSetUserClaimValues(String userName, Map<String, 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);
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

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

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

    boolean cnModified = false;
    String cnValue = null;

    try {

        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
        returnedUserEntry = returnedResultList.next().getName();

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

    if (profileName == null) {
        profileName = UserCoreConstants.DEFAULT_PROFILE;
    }

    if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) {
        claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);

        String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1
                ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0]
                : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME);
        for (Map.Entry<String, String> claimEntry : claims.entrySet()) {
            String claimURI = claimEntry.getKey();
            // if there is no attribute for profile configuration in LDAP,
            // skip updating it.
            if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                continue;
            }
            // get the claimMapping related to this claimURI
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            //remove user DN from cache if changing username attribute
            if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) {
                userCache.remove(userName);
            }
            // if mapped attribute is CN, then skip treating as a modified
            // attribute -
            // it should be an object rename
            if ("CN".toLowerCase().equals(attributeName.toLowerCase())) {
                cnModified = true;
                cnValue = claimEntry.getValue();
                continue;
            }
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            /* if updated attribute value is null, remove its values. */
            if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                currentUpdatedAttribute.clear();
            } else {
                if (claimEntry.getValue() != null) {
                    String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                    if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                        userAttributeSeparator = claimSeparator;
                    }
                    if (claimEntry.getValue().contains(userAttributeSeparator)) {
                        StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator);
                        while (st.hasMoreElements()) {
                            String newVal = st.nextElement().toString();
                            if (newVal != null && newVal.trim().length() > 0) {
                                currentUpdatedAttribute.add(newVal.trim());
                            }
                        }
                    } else {
                        currentUpdatedAttribute.add(claimEntry.getValue());
                    }
                } else {
                    currentUpdatedAttribute.add(claimEntry.getValue());
                }
            }
            updatedAttributes.put(currentUpdatedAttribute);
        }
        // update the attributes in the relevant entry of the directory
        // store

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

        if (cnModified && cnValue != null) {
            subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue));
        }

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMessage = "Error in obtaining claim mapping for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java

/**
 * Same as above except sorted.//from   w ww .  j av a 2s  .c om
 */
@Test
public void testGetUsernamesInRole1Sorted() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=users", //$NON-NLS-1$
            "(businessCategory=cn={0}*)", con1); //$NON-NLS-1$

    Transformer transformer1 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);
    userRoleListService.setUsernameComparator(new DefaultUsernameComparator());

    List<String> res = userRoleListService.getUsersInRole(null, "DEV"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    assertTrue(res.indexOf("pat") < res.indexOf("tiffany"));

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole1Sorted(): " + res); //$NON-NLS-1$
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public <T> List<T> searchIndirections(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }//  ww w  .ja v  a 2  s. c  om

    LogUtils.debug(LOG, String.format("search %s with filter=%s", clazz.getName(), filter));

    OneMetaData oneMetaData = IndirectionsMetaData.get(clazz).getOne();

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(new String[] { oneMetaData.getIdAttr(), oneMetaData.getIndirectionAttr() });

    try {
        List<T> retVal = new ArrayList<T>();
        NamingEnumeration<SearchResult> results = ctx.search(oneMetaData.getContext(), filter, ctrl);
        while (results.hasMore()) {
            SearchResult result = results.next();
            retVal.add(fromAttributesToIndirections(clazz, result.getAttributes()));
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

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

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

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java

/**
 * Same as above except sorted./*w  w  w.ja v  a 2 s  .co  m*/
 */
@Test
public void testGetUsernamesInRole1Sorted() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=users", //$NON-NLS-1$
            "(businessCategory=cn={0}*)", con1); //$NON-NLS-1$

    Transformer transformer1 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);

    DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);
    userRoleListService.setUsernameComparator(new DefaultUsernameComparator());

    List<String> res = userRoleListService.getUsersInRole(null, "DEV"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    assertTrue(res.indexOf("pat") < res.indexOf("tiffany"));

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole1Sorted(): " + res); //$NON-NLS-1$
    }
}

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

/**
 * Gets all the user entities taken from the LDAP server, as taken from the
 * search-context given by the value of the attribute {@link #userBase}.
 *
 * @return A set containing all the relevant users found in the LDAP
 *         directory./*  www .j a v a 2 s  .  c o  m*/
 * @throws NamingException
 *             Propagated from the LDAP communication layer.
 */
private Set<String> getAllUsersFromLDAP() throws NamingException {
    Set<String> result = new HashSet<String>();

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { "distinguishedName" });
    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")",
            sc);
    while (sr.hasMore()) {
        SearchResult r = sr.next();
        result.add(r.getNameInNamespace());
    }

    return result;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException {
    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        return false;
    }/*from ww w.  j  ava  2 s. com*/

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();
            Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember());
            if (attribute != null) {
                BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
                basicAttribute.add(this.userIdAttribute + "=" + username + "," + getGroupsDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute) });
            }
            return true;
        }

        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * {@inheritDoc}/* w  ww . java  2  s .c om*/
 */
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }

    int givenMax;
    int searchTime;

    try {
        givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = CommonConstants.MAX_USER_LIST;
    }

    try {
        searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = CommonConstants.MAX_SEARCH_TIME;
    }

    if (maxItemLimit <= 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);
    searchCtls.setTimeLimit(searchTime);

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user search. Please enter valid sequence.");
    }

    StringBuilder searchFilter = new StringBuilder(
            userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE);

    String serviceNameAttribute = "sn";

    StringBuilder finalFilter = new StringBuilder();

    // read the display name attribute - if provided
    String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);

    String[] returnedAtts;

    if (StringUtils.isNotEmpty(displayNameAttribute)) {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    } else {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    }

    if (debug) {
        log.debug(
                "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString());
        log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime);
    }

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    List<String> list = new ArrayList<>();

    try {
        dirContext = connectionSource.getContext();
        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);

        for (String searchBase : searchBaseArray) {

            answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (sr.getAttributes() != null) {
                    log.debug("Result found ..");
                    Attribute attr = sr.getAttributes().get(userNameProperty);

                    // If this is a service principle, just ignore and
                    // iterate rest of the array. The entity is a service if
                    // value of surname is Service

                    Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                    if (attrSurname != null) {
                        if (debug) {
                            log.debug(serviceNameAttribute + " : " + attrSurname);
                        }
                        String serviceName = (String) attrSurname.get();
                        if (serviceName != null
                                && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                            continue;
                        }
                    }

                    if (attr != null) {
                        String name = (String) attr.get();
                        list.add(name);
                    }
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        Arrays.sort(userNames);

        if (debug) {
            for (String username : userNames) {
                log.debug("result: " + username);
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userNames;
}