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:ldap.SearchUtility.java

/**
 * A utility method to get a conrols object.  May be redundant; the default new Controls() would probably
 * suffice.// w  ww  . j ava2s.c om
 * @return a new SearchControls object that can be modified and passed to a context.search method.
 */
private SearchControls getSearchControls() {
    SearchControls constraints = new SearchControls();
    constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);
    return constraints;
}

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

/**
 * Search for all users starting at <code>ou=roles</code>, looking for objects with
 * <code>(&(objectClass=organizationalRole)(cn={0}))</code>, and extracting the <code>uid</code> token of the
 * <code>roleOccupant</code> attribute. This search implies that the schema is setup such that a user's roles come
 * from that user's DN being present in the <code>roleOccupant</code> attribute of a child object under the
 * <code>ou=roles</code> object.
 *//*from   w ww  .j av  a 2  s  . c o m*/
@Test
public void testGetUsernamesInRole2() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "roleOccupant" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$
            "(&(objectClass=organizationalRole)(cn={0}))", con1); //$NON-NLS-1$

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

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

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

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);

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

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

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

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;/* ww  w  . j a v  a  2s .c om*/

    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()) {

            BasicAttributes basicAttributes = new BasicAttributes(true);

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

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);
            Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential,
                    newCredentials);
            basicAttributes.put(newPasswordAttribute);

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

            dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }

    } catch (NamingException e) {
        log.error("Unable to update server principle password details. Server name - " + serverName);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

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   www.  jav  a2s.  c om*/

    userDirContext.unbind(userDn);

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

    return response;
}

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

private String performRoleSearch(String location, String roleName) {
    String val = null;
    try {//from   w w  w .j  a  v  a  2  s .c o  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:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java

private SearchControls getSearchControls(final String[] attributeIds) {
    final SearchControls constraints = new SearchControls();

    constraints.setSearchScope(this.scope);
    constraints.setReturningAttributes(attributeIds);
    constraints.setTimeLimit(this.timeout);
    constraints.setCountLimit(this.maxNumberResults);

    return constraints;
}

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

/**
 * Search for all users starting at <code>ou=roles</code>, looking for objects with
 * <code>(&(objectClass=organizationalRole)(cn={0}))</code>, and extracting the <code>uid</code> token of the
 * <code>roleOccupant</code> attribute. This search implies that the schema is setup such that a user's roles come
 * from that user's DN being present in the <code>roleOccupant</code> attribute of a child object under the
 * <code>ou=roles</code> object.
 *///from  ww w  .j a v  a  2s . c o m
@Test
public void testGetUsernamesInRole2() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "roleOccupant" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$
            "(&(objectClass=organizationalRole)(cn={0}))", con1); //$NON-NLS-1$

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

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);
    Map<String, String> roleMap = new HashMap<>();
    roleMap.put("DEV", "dev");

    DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(roleMap);

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);

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

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

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

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

/**
 *
 *///  w  w w . j  a va 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  a2 s  . c  om
 *            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 w w w .j  a  va2 s .c  o  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);
}