Example usage for javax.naming.directory SearchControls setReturningAttributes

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

Introduction

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

Prototype

public void setReturningAttributes(String[] attrs) 

Source Link

Document

Specifies the attributes that will be returned as part of the search.

Usage

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

/**
 * Union the results of two different searches.
 * <ul>/*  w  w  w.  ja v  a2 s. c o m*/
 * <li>Search 1: Search for all roles (aka authorities) starting at <code>ou=groups</code>, looking for objects with
 * <code>objectClass=groupOfUniqueNames</code>, and returning the <code>cn</code> attribute.</li>
 * <li>Search 2: Search for all roles (aka authorities) starting at <code>ou=roles</code>, looking for objects with
 * <code>objectClass=organizationalRole</code>, and returning the <code>cn</code> attribute.</li>
 * </ul>
 */
@Test
public void testGetAllAuthorities3() throws Exception {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "cn" }); //$NON-NLS-1$

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

    Transformer one = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$
    Transformer two = new StringToGrantedAuthority();
    Transformer[] transformers = { one, two };
    Transformer transformer = new ChainedTransformer(transformers);

    LdapSearch rolesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer);

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

    LdapSearchParamsFactory paramsFactory2 = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$
            "(objectClass=groupOfUniqueNames)", con2); //$NON-NLS-1$

    Transformer oneB = new SearchResultToAttrValueList("cn"); //$NON-NLS-1$
    Transformer twoB = new StringToGrantedAuthority();
    Transformer[] transformers2 = { oneB, twoB };
    Transformer transformer2 = new ChainedTransformer(transformers2);

    LdapSearch rolesSearch2 = new GenericLdapSearch(getContextSource(), paramsFactory2, transformer2);

    Set searches = new HashSet();
    searches.add(rolesSearch);
    searches.add(rolesSearch2);
    UnionizingLdapSearch unionSearch = new UnionizingLdapSearch(searches);

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setAllAuthoritiesSearch(unionSearch);

    List res = userRoleListService.getAllRoles();

    assertTrue(res.contains("ROLE_DEVMGR")); //$NON-NLS-1$
    assertTrue(res.contains("ROLE_DEVELOPMENT")); //$NON-NLS-1$

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

}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapImportManagerImpl.java

private void runSearch(NameClassPairCallbackHandler handler, long limit, int connectionId) {
    SearchControls sc = new SearchControls();
    sc.setCountLimit(limit);/*w ww .ja  v  a  2 s  . c o m*/
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

    AttrMap attrMap = m_ldapManager.getAttrMap(connectionId);
    if (!attrMap.verified()) {
        m_ldapManager.verify(m_ldapManager.getConnectionParams(connectionId), attrMap);
    }

    sc.setReturningAttributes(attrMap.getLdapAttributesArray());

    String base = attrMap.getSearchBase();
    String filter = attrMap.getSearchFilter();

    LdapTemplate template = m_templateFactory.getLdapTemplate(m_ldapManager.getConnectionParams(connectionId));
    try {
        template.search(base, filter, sc, handler, LdapManager.NULL_PROCESSOR);
    } catch (Exception e) {
        if (e instanceof SearchLimitExceededException) {
            // See http://forum.springframework.org/archive/index.php/t-27836.html
            LOG.info("Normal overflow, requesting to preview more records then exist");
        } else {
            LOG.error("LDAP search failed", e);
            throw new UserException("LDAP search failed : " + e.getCause().getMessage());
        }
    }
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java

public Schema getSchema(String subschemaSubentry, LdapConnectionParams params) {
    try {//w w  w . j  av  a 2 s . c om
        SearchControls cons = new SearchControls();
        // only interested in the first result
        cons.setCountLimit(1);
        // set time limit for this search to 30 sec, should be sufficient even for large LDAPs
        cons.setTimeLimit(30000);

        SchemaMapper mapper = new SchemaMapper();
        cons.setReturningAttributes(mapper.getReturningAttributes());
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);

        Schema schema = (Schema) m_templateFactory.getLdapTemplate(params).search(subschemaSubentry,
                LdapManager.FILTER_ALL_CLASSES, cons, new SchemaMapper(), LdapManager.NULL_PROCESSOR).get(0);

        return schema;
    } catch (DataIntegrityViolationException e) {
        LOG.debug("Retrieving schema failed.", e);
        throw new UserException("searchSchema.violation.error");
    } catch (UncategorizedLdapException e) {
        LOG.debug("Retrieving schema failed. Anonymous-binding may be disabled", e);
        throw new UserException("searchSchema.anonymousBinding.error");
    }
}

From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java

/**
 * Connects to LDAP to retrieve the namingContexts attribute from root. Good
 * way to verify if LDAP is accessible. Command line anologue is:
 *
 * ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts
 *
 * @param attrNames//from   w  w  w .  j av a  2 s .c  o  m
 *            TODO
 *
 * @return namingContext value - can be used as the search base for user if
 *         nothing more specific is provided
 * @throws NamingException
 */
private Map<String, String> retrieveDefaultSearchBase(LdapConnectionParams params, String[] attrNames)
        throws NamingException {

    SearchControls cons = new SearchControls();

    cons.setReturningAttributes(attrNames);
    cons.setSearchScope(SearchControls.OBJECT_SCOPE);
    cons.setTimeLimit(30000);

    List<Map<String, String>> results = m_templateFactory.getLdapTemplate(params).search("", FILTER_ALL_CLASSES,
            cons, new AttributesToValues(attrNames), NULL_PROCESSOR);
    // only interested in the first result
    if (results.size() > 0) {
        return results.get(0);
    }
    return null;
}

From source file:org.springframework.ldap.core.LdapTemplate.java

private SearchControls getDefaultSearchControls(int searchScope, boolean returningObjFlag, String[] attrs) {

    SearchControls controls = new SearchControls();
    controls.setSearchScope(searchScope);
    controls.setReturningObjFlag(returningObjFlag);
    controls.setReturningAttributes(attrs);
    return controls;
}

From source file:org.springframework.security.ldap.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./*from  w ww .  j a  v a2s . c o m*/
 *
 * @param base the DN to search in
 * @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, List<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, List<String>>> set = new HashSet<Map<String, List<String>>>();

    ContextMapper roleMapper = new ContextMapper() {
        public Object mapFromContext(Object ctx) {
            DirContextAdapter adapter = (DirContextAdapter) ctx;
            Map<String, List<String>> record = new HashMap<String, List<String>>();
            if (attributeNames == null || attributeNames.length == 0) {
                try {
                    for (NamingEnumeration ae = adapter.getAttributes().getAll(); ae.hasMore();) {
                        Attribute attr = (Attribute) ae.next();
                        extractStringAttributeValues(adapter, record, attr.getID());
                    }
                } catch (NamingException x) {
                    org.springframework.ldap.support.LdapUtils.convertLdapException(x);
                }
            } else {
                for (String attributeName : attributeNames) {
                    extractStringAttributeValues(adapter, record, attributeName);
                }
            }
            record.put(DN_KEY, Arrays.asList(getAdapterDN(adapter)));
            set.add(record);
            return null;
        }
    };

    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(searchControls.getSearchScope());
    ctls.setReturningAttributes(attributeNames != null && attributeNames.length > 0 ? attributeNames : null);

    search(base, formattedFilter, ctls, roleMapper);

    return set;
}

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  om*/

    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.swordess.ldap.odm.core.SessionImpl.java

@Override
public List<Map<String, Object>> search(Class<?> clazz, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*w  ww.j  a  va  2s.com*/

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

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(clazz, result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

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

@Override
public List<Map<String, Object>> search(String context, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*from w  w  w . j  a v  a 2 s.  c o  m*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", context, filter,
            Arrays.toString(returningAttrs)));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

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

public List<String> lookup(String context, String filter) {
    if (null == filter) {
        return null;
    }/*from w  w  w. j a v  a2 s . co  m*/

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

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

    try {
        List<String> retVal = new ArrayList<String>();
        NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl);
        while (results.hasMore()) {
            retVal.add(results.next().getNameInNamespace());
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}