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.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java

@Test
public void testGetAllUserNames1ForTenant() throws Exception {
    ITenant defaultTenant = new Tenant("/pentaho/tenant0", true);
    login("suzy", defaultTenant);

    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$

    LdapSearchParamsFactoryImpl paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$
            "(objectClass=groupOfUniqueNames)", con1); //$NON-NLS-1$
    paramFactory.afterPropertiesSet();/*from   www . j a va 2  s .com*/

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

    GenericLdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramFactory,
            transformer1);
    allUsernamesSearch.afterPropertiesSet();

    DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService();

    userRoleListService.setAllUsernamesSearch(allUsernamesSearch);

    List res = userRoleListService.getAllUsers(defaultTenant);

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

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

    try {
        userRoleListService.getAllUsers(new Tenant("/pentaho", true));
    } catch (UnsupportedOperationException uoe) {
        assertNotNull(uoe);
    }

}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private List search(DirContext ctx, String rootDN, String scope, String filter, String[] attributes) {
    try {//from  w ww .  ja va 2 s  .c o  m
        List listResults = new ArrayList();
        SearchControls constraints = new SearchControls();

        constraints.setSearchScope(convertSearchScope(scope));
        constraints.setReturningAttributes(attributes);

        try {
            if (scope != null && scope.toUpperCase().equals("ALLLEVELS")) {
                String[] levels = rootDN.split(",");
                for (int i = 0; i < levels.length; i++) {
                    String[] currentLevels = new String[levels.length - i];
                    System.arraycopy(levels, i, currentLevels, 0, levels.length - i);
                    String levelRootDN = StringUtils.join(currentLevels, ",");
                    if (logger.isDebugEnabled())
                        logger.debug("LDAP Search on level " + levelRootDN);
                    NamingEnumeration results = ctx.search(levelRootDN, filter, constraints);
                    for (; results.hasMore();) {
                        SearchResult result = (SearchResult) results.next();
                        listResults.add(result);
                    }
                }
            } else {
                NamingEnumeration results = ctx.search(rootDN, filter, constraints);
                for (; results.hasMore();) {
                    SearchResult result = (SearchResult) results.next();
                    listResults.add(result);
                }
            }

        } catch (NameNotFoundException e) {
            // for example in case of ALLLEVELS scope, if the LDAP database suffix has more than one component, the last iteration would result in NameNotFoundException
        }
        return listResults;
    } catch (NamingException e) {
        throw new OXFException("LDAP Search Failed", e);
    }
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser getIfValidUser(String cn, String password) {
    LDAPUser user = null;/*from   w w  w.  j  av a  2  s.co  m*/
    NamingEnumeration results = null;
    DirContext ctx = null;
    try {
        ctx = getAuthContext(cn, password);
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf",
                "createTimestamp" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user.setUsername((String) attributes.get("cn").get());
            if (attributes.get("sn") != null)
                user.setSurname((String) attributes.get("sn").get());
            if (attributes.get("givenName") != null)
                user.setGivenname((String) attributes.get("givenName").get());
            if (attributes.get("title") != null)
                user.setTitle((String) attributes.get("title").get());
            if (attributes.get("registeredAddress") != null)
                user.setPreferredMail((String) attributes.get("registeredAddress").get(0));
            if (attributes.get("mail") != null) {
                String mails = "";
                for (int i = 0; i < attributes.get("mail").size(); i++) {
                    if (i != 0)
                        mails = mails + ", ";
                    mails = mails + (String) attributes.get("mail").get(i);
                }
                user.setAdditionalMails(mails);
            }
            if (attributes.get("memberOf") != null) {
                for (int i = 0; i < attributes.get("memberOf").size(); i++) {
                    user.addGroup((String) attributes.get("memberOf").get(i));
                }
            }
            if (attributes.get("createTimestamp") != null) {
                String time = (String) attributes.get("createTimestamp").get();
                DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss");
                user.setCreationTime(ldapData.parse(time));
            }

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } catch (ParseException ex) {
        _log.error(ex);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return user;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from LDAP. */
private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {//  w  w w . ja v a  2 s  .c  o  m
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setCountLimit(numUsersToFetch);
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    LOGGER.info("UserList: " + userList);
    return userList;
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext)
        throws LdapControllerException {
    Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/*from   w w  w .  j  av  a2s. c  om*/

        SearchControls searchControls = new SearchControls();

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

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

        namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            String groupName = searchResult.getName();
            // cn=blabla we only want bla bla
            groupName = StringUtils.substringAfter(groupName, "=");

            Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember");

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    Collection<String> roles = usersWithRoles.get(userName);
                    if (roles == null) {
                        roles = new HashSet<String>();
                    }

                    roles.add(groupName);

                    usersWithRoles.put(userName, roles);

                }
            }

            log.debug("found groupName: '{}' with users: {}", groupName);

        }

        return usersWithRoles;
    } catch (NamingException e) {
        throw new LdapControllerException(e.getMessage(), e);
    }

    finally {

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

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

/**
 * attempts to get the users credentials from the users context
 * <p/>/*from w w  w .  j a va2 s .co  m*/
 * NOTE: this is not an user authenticated operation
 *
 * @param username
 * @return
 * @throws LoginException
 */
@SuppressWarnings("unchecked")
private String getUserCredentials(String username) throws LoginException {
    String ldapCredential = null;

    SearchControls ctls = new SearchControls();
    ctls.setCountLimit(1);
    ctls.setDerefLinkFlag(true);
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    try {
        Object[] filterArguments = { _userObjectClass, _userIdAttribute, username };
        NamingEnumeration results = _rootContext.search(_userBaseDn, OBJECT_CLASS_FILTER, filterArguments,
                ctls);

        debug("Found user?: " + results.hasMoreElements());

        if (!results.hasMoreElements()) {
            throw new LoginException("User not found.");
        }

        SearchResult result = findUser(username);

        Attributes attributes = result.getAttributes();

        setDemographicAttributes(attributes);
        Attribute attribute = attributes.get(_userPasswordAttribute);
        if (attribute != null) {
            try {
                byte[] value = (byte[]) attribute.get();

                ldapCredential = new String(value);
            } catch (NamingException e) {
                LOG.info("no password available under attribute: " + _userPasswordAttribute);
            }
        }
    } catch (NamingException e) {
        throw new LoginException("Root context binding failure.");
    }

    debug("user cred is present: " + (ldapCredential != null));

    return ldapCredential;
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

public void getAttributes(PIPRequest pipRequest, PIPFinder pipFinder, StdMutablePIPResponse mutablePIPResponse,
        LDAPResolver ldapResolver) throws PIPException {
    /*//w w  w . j a v a  2s .  co m
     * Check with the resolver to get the base string
     */
    String stringBase = ldapResolver.getBase(this, pipRequest, pipFinder);
    if (stringBase == null) {
        this.logger.warn(this.getName() + " does not handle " + pipRequest.toString());
        return;
    }

    /*
     * Get the filter string
     */
    String stringFilter = ldapResolver.getFilterString(this, pipRequest, pipFinder);

    /*
     * Check the cache
     */
    Cache<String, PIPResponse> cache = this.getCache();
    String cacheKey = stringBase + "::" + (stringFilter == null ? "" : stringFilter);
    if (cache != null) {
        PIPResponse pipResponse = cache.getIfPresent(cacheKey);
        if (pipResponse != null) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Returning cached response: " + pipResponse);
            }
            mutablePIPResponse.addAttributes(pipResponse.getAttributes());
            return;
        }
    }
    /*
     * Not in the cache, so set up the LDAP query session
     */
    DirContext dirContext = null;
    PIPResponse pipResponse = null;
    try {
        /*
         * Create the DirContext
         */
        dirContext = new InitialDirContext(this.ldapEnvironment);

        /*
         * Set up the search controls
         */
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(this.ldapScope);

        /*
         * Do the search
         */
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(stringBase, stringFilter,
                searchControls);
        if (namingEnumeration != null && namingEnumeration.hasMore()) {
            while (namingEnumeration.hasMore()) {
                List<Attribute> listAttributes = ldapResolver.decodeResult(namingEnumeration.next());
                if (listAttributes != null && listAttributes.size() > 0) {
                    mutablePIPResponse.addAttributes(listAttributes);
                }
            }
        }
        /*
         * Put in the cache
         */
        if (cache != null) {
            cache.put(cacheKey, pipResponse);
        }
    } catch (NamingException ex) {
        this.logger.error("NamingException creating the DirContext: " + ex.getMessage(), ex);
    } finally {
        if (dirContext != null) {
            try {
                dirContext.close();
            } catch (Exception ex) {
                this.logger.warn("Exception closing DirContext: " + ex.getMessage(), ex);
            }
        }
    }
}

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

/**
 * @param roleID the ID of a role// w w  w .  jav a 2 s .c  o m
 * @param userID the ID of a user
 * @return <code>true</code> if the user has that role.
 */
public boolean hasRole(Integer roleID, Long userID) {
    try {
        SearchControls sc = new SearchControls();
        NamingEnumeration e = ctx.search("ou=people",
                "(&(employeeNumber=" + userID + ")(pegadiRole=" + roleID + ":*))", sc);
        if (e.hasMore())
            return true;

    } catch (NamingException er) {
        log.error("Error checking for role: " + roleID + "for userID " + userID, er);
    } catch (Exception e) {
        log.error("Something else", e);
    }
    return false;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchFromUsers(DirContext context, Map filters) throws NamingException {

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

    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    searchResultEnum = context.search(userBase, filter, searchControls);
    //roop of retrieval result

    List users = new ArrayList();
    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        String dn = searchResult.getName() + "," + userBase;
        LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
        users.add(user);/*from  ww  w  .j a v  a 2 s.c o  m*/
    }
    return users;
}

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

/**
 * Same as above except sorted./*ww w .ja v a2s .c  o m*/
 */
@Test
public void testGetAllUserNames1Sorted() throws Exception {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$

    LdapSearchParamsFactoryImpl paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$
            "(objectClass=groupOfUniqueNames)", con1); //$NON-NLS-1$
    paramFactory.afterPropertiesSet();

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

    GenericLdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramFactory,
            transformer1);
    allUsernamesSearch.afterPropertiesSet();

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setAllUsernamesSearch(allUsernamesSearch);
    userRoleListService.setUsernameComparator(new DefaultUsernameComparator());

    List res = userRoleListService.getAllUsers();

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

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