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.georchestra.console.ds.AccountDaoImpl.java

/**
 * @see {@link AccountDao#findByEmail(String)}
 *///from  w  w  w. j a v a  2  s.  co  m
@Override
public Account findByEmail(final String email) throws DataServiceException, NameNotFoundException {

    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectClass", "inetOrgPerson"));
    filter.and(new EqualsFilter("objectClass", "organizationalPerson"));
    filter.and(new EqualsFilter("objectClass", "person"));
    filter.and(new EqualsFilter("mail", email));

    List<Account> accountList = ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc,
            attributMapper);
    if (accountList.isEmpty()) {
        throw new NameNotFoundException("There is no user with this email: " + email);
    }
    Account account = accountList.get(0);

    return account;
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Returns an array of users having a given role. Either active or
 * inactive users are returned./*from  w ww  . ja  v a  2  s.  com*/
 *
 * @param roleID the role of the users.
 * @param active specifying whether we want the active or inactive users.
 * @return an array of <code>User</code>s.
 */
public List<Person> getUsersByRole(int roleID, int active) {
    if (roleID <= 0)
        return null;
    ArrayList<Person> users = new ArrayList<Person>();
    try {
        SearchControls sc = new SearchControls();
        String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" };
        sc.setReturningAttributes(getThese);
        NamingEnumeration e = ctx.search("ou=people", "(&(active=" + active + ")(pegadiRole=" + roleID + "*))",
                sc);
        while (e.hasMore()) {
            SearchResult sr = (SearchResult) e.next();
            users.add(this.createUser(sr.getAttributes()));
        }
        Collections.sort(users);
        return users;
    } catch (NamingException er) {
        log.error("Error, getUsersByRole(" + roleID + "," + active + ")", er);
    }
    return null;
}

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

@SuppressWarnings("unchecked")
private List getUserRolesByDn(DirContext dirContext, String userDn, String username)
        throws LoginException, NamingException {
    List<String> roleList = new ArrayList<String>();

    if (dirContext == null || _roleBaseDn == null
            || (_roleMemberAttribute == null && _roleUsernameMemberAttribute == null)
            || _roleObjectClass == null) {
        LOG.warn(//from ww w . ja  v  a2s  .c om
                "JettyCachingLdapLoginModule: No user roles found: roleBaseDn, roleObjectClass and roleMemberAttribute or roleUsernameMemberAttribute must be specified.");
        addSupplementalRoles(roleList);
        return roleList;
    }

    String[] attrIDs = { _roleNameAttribute };
    SearchControls ctls = new SearchControls();
    ctls.setReturningAttributes(attrIDs);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String filter = OBJECT_CLASS_FILTER;
    final NamingEnumeration results;

    if (null != _roleUsernameMemberAttribute) {
        Object[] filterArguments = { _roleObjectClass, _roleUsernameMemberAttribute, username };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    } else {
        Object[] filterArguments = { _roleObjectClass, _roleMemberAttribute, userDn };
        results = dirContext.search(_roleBaseDn, filter, filterArguments, ctls);
    }

    while (results.hasMoreElements()) {
        SearchResult result = (SearchResult) results.nextElement();

        Attributes attributes = result.getAttributes();

        if (attributes == null) {
            continue;
        }

        Attribute roleAttribute = attributes.get(_roleNameAttribute);

        if (roleAttribute == null) {
            continue;
        }

        NamingEnumeration roles = roleAttribute.getAll();
        while (roles.hasMore()) {
            if (_rolePrefix != null && !"".equalsIgnoreCase(_rolePrefix)) {
                String role = (String) roles.next();
                roleList.add(role.replace(_rolePrefix, ""));
            } else {
                roleList.add((String) roles.next());
            }
        }
    }

    addSupplementalRoles(roleList);

    if (_nestedGroups) {
        roleList = getNestedRoles(dirContext, roleList);
    }

    if (roleList.size() < 1) {
        LOG.warn("JettyCachingLdapLoginModule: User '" + username
                + "' has no role membership; role query configuration may be incorrect");
    } else {
        debug("JettyCachingLdapLoginModule: User '" + username + "' has roles: " + roleList);
    }

    return roleList;
}

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

@Override
public <T> List<T> search(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }/*from   w  w  w.j  av  a 2s  . c  o m*/

    LogUtils.debug(LOG, "search " + clazz.getName() + " with filter=" + filter);

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(EntityMetaData.getDefinedAttrNames(clazz));

    List<T> retVal = new ArrayList<T>();
    try {
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                T entity = null;
                if (sessionCache.containsKey(result.getNameInNamespace())) {
                    // guarantee the reference integrity for one search result
                    entity = (T) sessionCache.get(result.getNameInNamespace());
                } else {
                    entity = fromAttributesToEntity(clazz, result.getAttributes());
                    sessionCache.put(result.getNameInNamespace(), entity);
                }
                retVal.add(entity);
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the entity", e);
            }
        }
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
    return retVal;
}

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

/**
 * {@inheritDoc}/*from  w  w  w.j  a va2s . c om*/
 */
public Map<String, String> getUserPropertyValues(String userName, String[] propertyNames)
        throws UserStoreException {

    String userAttributeSeparator = ",";
    String userDN = null;

    // read list of patterns from user-mgt.xml
    String patterns = userStoreProperties.get(LDAPConstants.USER_DN_PATTERN);

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

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

        if (patterns.contains(CommonConstants.XML_PATTERN_SEPERATOR)) {
            userDN = getNameInSpaceForUserName(userName);
        } else {
            userDN = MessageFormat.format(patterns, escapeSpecialCharactersForDN(userName));
        }
    }

    Map<String, String> values = new HashMap<>();
    DirContext dirContext = this.connectionSource.getContext();
    String userSearchFilter = userStoreProperties.get(LDAPConstants.USER_NAME_SEARCH_FILTER);
    String searchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    NamingEnumeration<?> answer = null;
    NamingEnumeration<?> attrs = null;
    NamingEnumeration<?> allAttrs = null;
    try {
        if (userDN != null) {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            if (propertyNames[0].equals(CommonConstants.WILD_CARD_FILTER)) {
                propertyNames = null;
            }
            searchCtls.setReturningAttributes(propertyNames);

            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);
        }
        assert answer != null;
        while (answer.hasMoreElements()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attributes = sr.getAttributes();
            if (attributes != null) {
                for (allAttrs = attributes.getAll(); allAttrs.hasMore();) {
                    Attribute attribute = (Attribute) allAttrs.next();
                    if (attribute != null) {
                        StringBuilder attrBuffer = new StringBuilder();
                        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), "UTF-8");
                            }

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

                            /*
                             * Length needs to be more than userAttributeSeparator.length() for a valid
                             * attribute, since we
                             * attach userAttributeSeparator
                             */
                            if (value.trim().length() > userAttributeSeparator.length()) {
                                value = value.substring(0, value.length() - userAttributeSeparator.length());
                                values.put(attribute.getID(), 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);
    } catch (UnsupportedEncodingException e) {
        String errorMessage = "Error occurred while Base64 encoding 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 resource
        JNDIUtil.closeNamingEnumeration(attrs);
        JNDIUtil.closeNamingEnumeration(answer);
        // close directory context
        JNDIUtil.closeContext(dirContext);
    }
    return values;
}

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</code>, and extracting the <code>uid</code> token of the
 * <code>roleOccupant</code> attribute.
 *//*  w  w  w  .  j  a v  a 2s.  c  o  m*/
@Test
public void testGetAllUserNames3() {
    SearchControls con3 = new SearchControls();
    con3.setReturningAttributes(new String[] { "roleOccupant" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$
            "(objectClass=organizationalRole)", con3); //$NON-NLS-1$

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

    LdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer3);

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setAllUsernamesSearch(allUsernamesSearch);

    List res = userRoleListService.getAllUsers();

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

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

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id)
        throws OAException {
    String sReturn = null;//from w w w .j  a v a  2 s  .  c  o  m
    NamingEnumeration oNamingEnumeration = null;
    try {
        if (sIDAttribute == null) {
            _logger.error("No attribute name to map from supplied");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbQuery = new StringBuffer("(");
        sbQuery.append(sIDAttribute);
        sbQuery.append("=");
        sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id));
        sbQuery.append(")");
        String sSearchQuery = sbQuery.toString();

        String sSearchFor = sMapperAttribute;
        if (sSearchFor == null)
            sSearchFor = "*";

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        oScope.setReturningAttributes(new String[] { sSearchFor });

        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(sSearchQuery);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        if (!oNamingEnumeration.hasMore()) {
            _logger.debug("No result when searching for: " + sSearchQuery);
        } else {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();

            if (sMapperAttribute == null) {
                sReturn = oSearchResult.getName();
                sReturn += "," + _sDNBase;
            } else {
                Attributes oSearchedAttributes = oSearchResult.getAttributes();
                Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute);
                if (attrMapping == null) {
                    _logger.debug("Mapping attribute not found: " + sMapperAttribute);
                } else {
                    Object oValue = attrMapping.get();
                    if (!(oValue instanceof String)) {
                        StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '");
                        sbError.append(_sMapperAttribute);
                        sbError.append("' has a value which is not of type 'String'");
                        _logger.error(sbError.toString());
                        throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
                    }
                    sReturn = (String) oValue;
                }
            }
        }
    } catch (OAException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch mapping attribute for id: " + id, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for id: " + id, e);
            }
        }
    }
    return sReturn;
}

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 aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from   w w  w .ja va 2  s .  c o m
public void loadUserByAccountName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName");

    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 = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField dataField : aUserBag.getFields()) {
        fieldName = dataField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = dataField.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 userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.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", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

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

public List<T> findAll(final DirContext ctx, final String organizationalUnit) throws NamingException {
    final LinkedList<T> list = new LinkedList<T>();
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnit);
    results = ctx.search(searchBase, "(objectclass=" + getObjectClass() + ")", controls);
    while (results.hasMore()) {
        final SearchResult searchResult = (SearchResult) results.next();
        final String dn = searchResult.getName();
        final Attributes attributes = searchResult.getAttributes();
        list.add(mapToObject(dn, searchBase, attributes));
    }//from w  ww  .  ja v  a2 s. c  o m
    return list;
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }/* w  w w .j  av  a  2s.  c  o m*/
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}