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:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all the groups in the directory.
 * @param dirContext a DirContext/* w  ww.jav a  2s .  c o  m*/
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception if thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, GROUPS_FILTER, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "group.list", required = { "domain" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listGroups(OperationContext opContext) throws NamingException {

    String domain = (String) opContext.getParams().get("domain");

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    DomainDn domainDn = nameHelper.newDomainDnFromDomain(domain);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(nameHelper.getGroupsBaseDn(domainDn),
            "(cn=*)", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);//from  w  w  w . j  a va2s .co m
        }
    }

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

    return response;
}

From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java

/**
 * @return true  = monitoring is enabled
 * @return false = monitoring is not enabled
 * @exception NamingException no conection
 *//*from  w  w  w .  jav  a 2  s  . co  m*/
private boolean hasMonitoringEnabled(Metric metric) throws NamingException {
    NamingEnumeration enumer = null, enumerx = null, enumery = null;

    boolean res = false;
    try {
        String[] a = { "monitorContext" };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search("", "(&(objectClass=*))", cons);
        while (enumer.hasMore() && !res) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            enumerx = attrs.getIDs();
            while (enumerx.hasMore()) {
                String id = (String) enumerx.next();
                Attribute attr = attrs.get(id);
                res = true;
            }
        }
    } finally {
        if (enumer != null) {
            enumer.close();
        }
        if (enumerx != null) {
            enumerx.close();
        }
        if (enumery != null) {
            enumery.close();
        }
    }

    log.debug("[hasMonitoringEnabled] res=" + res + " metric:" + metric);
    return res;
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleLdapCalendarAccountDaoImpl.java

/**
 * //from  w  w w .  j a  v  a2s. c o m
 * @param searchFilter
 * @return
 */
@SuppressWarnings("unchecked")
protected List<ICalendarAccount> executeSearchReturnList(final Filter searchFilter) {
    LOG.debug("searchFilter: " + searchFilter);
    SearchControls searchControls = new SearchControls();
    searchControls.setCountLimit(searchResultsLimit);
    searchControls.setTimeLimit(searchTimeLimit);
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    List<ICalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls,
                new OracleCalendarUserAccountAttributesMapper(this.oracleGUIDSource));
        if (LOG.isDebugEnabled()) {
            LOG.debug("search " + searchFilter + " returned " + results.size() + " results");
        }
        Collections.sort(results, new AccountComparator());
    } catch (SizeLimitExceededException e) {
        LOG.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        LOG.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}

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

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);//from   w  w w .j  a va2 s .c o m
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

/**
 * Performs a search using the supplied filter and returns the values of each named attribute
 * found in all entries matched by the search. Note that one directory entry may have several values for the
 * attribute. Intended for role searches and similar scenarios.
 *
 * @param base the DN to search in//from   ww  w  .java2 s  .  c  o m
 * @param filter search filter to use
 * @param params the parameters to substitute in the search filter
 * @param attributeNames the attributes' values that are to be retrieved.
 *
 * @return the set of String values for each attribute found in all the matching entries.
 * The attribute name is the key for each set of values. In addition each map contains the DN as a String
 * with the key predefined key {@link #DN_KEY}.
 */
public Set<Map<String, String[]>> searchForMultipleAttributeValues(final String base, final String filter,
        final Object[] params, final String[] attributeNames) {
    // Escape the params acording to RFC2254
    Object[] encodedParams = new String[params.length];

    for (int i = 0; i < params.length; i++) {
        encodedParams[i] = LdapEncoder.filterEncode(params[i].toString());
    }

    String formattedFilter = MessageFormat.format(filter, encodedParams);
    logger.debug("Using filter: " + formattedFilter);

    final HashSet<Map<String, String[]>> set = new HashSet<Map<String, String[]>>();

    ContextMapper roleMapper = new ContextMapper() {
        public Object mapFromContext(Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            Map<String, String[]> record = new HashMap<String, String[]>();
            for (String attributeName : attributeNames) {
                String[] values = adapter.getStringAttributes(attributeName);
                if (values == null || values.length == 0) {
                    logger.debug("No attribute value found for '" + attributeName + "'");
                } else {
                    record.put(attributeName, values);
                }
            }
            record.put(DN_KEY, new String[] { adapter.getDn().toString() });
            set.add(record);
            return null;
        }
    };

    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(searchControls.getSearchScope());
    ctls.setReturningAttributes(attributeNames);

    search(base, formattedFilter, ctls, roleMapper);

    return set;
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }/*from  w  w w.j av  a  2s. c  o  m*/
        }
    }

    Collections.sort(users);

    return users;
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test to make sure anonymous binds are allowed on the RootDSE even when disabled
 * in general when going through the wire protocol.
 *
 * @throws Exception if anything goes wrong
 *///w  w  w.  j a v a2 s . c  o  m
@Test
public void testEnableAnonymousBindsOnRootDse() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous
    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put(Context.SECURITY_AUTHENTICATION, "none");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    InitialDirContext ctx = new InitialDirContext(env);
    SearchControls cons = new SearchControls();
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    NamingEnumeration<SearchResult> list = ctx.search("", "(objectClass=*)", cons);

    SearchResult result = null;

    if (list.hasMore()) {
        result = list.next();
    }

    assertFalse(list.hasMore());
    list.close();

    assertNotNull(result);
    assertEquals("", result.getName().trim());
}

From source file:org.jasig.schedassist.impl.ldap.LDAPCalendarAccountDaoImpl.java

/**
 * /*from w ww  . j  a v a2  s. c  o  m*/
 * @param searchFilter
 * @return
 */
@SuppressWarnings("unchecked")
protected List<ICalendarAccount> executeSearchReturnList(final Filter searchFilter) {
    log.debug("executing search filter: " + searchFilter);

    SearchControls sc = new SearchControls();
    sc.setCountLimit(searchResultsLimit);
    sc.setTimeLimit(searchTimeLimit);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    List<ICalendarAccount> results = Collections.emptyList();
    try {
        results = ldapTemplate.search(baseDn, searchFilter.toString(), sc,
                new DefaultContextMapperImpl(ldapAttributesKey));
    } catch (SizeLimitExceededException e) {
        log.debug("search filter exceeded results size limit(" + searchResultsLimit + "): " + searchFilter);
    } catch (TimeLimitExceededException e) {
        log.warn("search filter exceeded time limit (" + searchTimeLimit + " milliseconds): " + searchFilter);
    }
    return results;
}