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.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

public LdapUser searchUser(final String basedn, final String searchString, final LdapContext context)
        throws NamingException, IOException {
    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    NamingEnumeration<SearchResult> results = context.search(basedn, searchString, searchControls);
    final List<LdapUser> users = new ArrayList<LdapUser>();
    while (results.hasMoreElements()) {
        final SearchResult result = results.nextElement();
        users.add(createUser(result));/*  w  ww  . j a  v a  2 s . co m*/
    }

    if (users.size() == 1) {
        return users.get(0);
    } else {
        throw new NamingException("No user found for basedn " + basedn + " and searchString " + searchString);
    }
}

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

@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context)
        throws NamingException, IOException {

    final SearchControls searchControls = new SearchControls();

    searchControls.setSearchScope(_ldapConfiguration.getScope());
    searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());

    String basedn = _ldapConfiguration.getBaseDn();
    if (StringUtils.isBlank(basedn)) {
        throw new IllegalArgumentException("ldap basedn is not configured");
    }// ww  w  .  j  av a  2 s . c  o  m
    byte[] cookie = null;
    int pageSize = _ldapConfiguration.getLdapPageSize();
    context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
    final List<LdapUser> users = new ArrayList<LdapUser>();
    NamingEnumeration<SearchResult> results;
    do {
        results = context.search(basedn, generateSearchFilter(username), searchControls);
        while (results.hasMoreElements()) {
            final SearchResult result = results.nextElement();
            if (!isUserDisabled(result)) {
                users.add(createUser(result));
            }
        }
        Control[] contextControls = context.getResponseControls();
        if (contextControls != null) {
            for (Control control : contextControls) {
                if (control instanceof PagedResultsResponseControl) {
                    PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
                    cookie = prrc.getCookie();
                }
            }
        } else {
            s_logger.info("No controls were sent from the ldap server");
        }
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } while (cookie != null);

    return users;
}

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

/**
 * Reproduces the problem with//from   w w w  . j a v a 2s.  c o  m
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java

/**
 * Returns the {@link SearchControls} object associated with the request.
 *
 * @param request//from w ww  .  ja v  a 2  s  . c  om
 *      the search request
 * @return
 *      the associated {@link SearchControls} object
 */
private SearchControls getSearchControls(SearchRequest request) {
    SearchControls controls = new SearchControls();

    // Scope
    switch (request.getScope()) {
    case OBJECT:
        controls.setSearchScope(SearchControls.OBJECT_SCOPE);
        break;
    case ONELEVEL:
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        break;
    case SUBTREE:
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        break;
    default:
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    }

    // Returning attributes
    List<String> returningAttributes = new ArrayList<String>();
    for (String attribute : request.getAttributes()) {
        returningAttributes.add(attribute);
    }
    // If the returning attributes are empty, we need to return the user attributes
    // [Cf. RFC 2251 - "There are two special values which may be used: an empty 
    //  list with no attributes, and the attribute description string '*'.  Both of 
    //  these signify that all user attributes are to be returned."]
    if (returningAttributes.size() == 0) {
        returningAttributes.add("*"); //$NON-NLS-1$
    }

    controls.setReturningAttributes(returningAttributes.toArray(new String[0]));

    // Size Limit
    controls.setCountLimit(request.getSizeLimit());

    // Time Limit
    controls.setTimeLimit(request.getTimeLimit());

    return controls;
}

From source file:org.apache.geronimo.security.realm.providers.GenericHttpHeaderLdapLoginModule.java

protected boolean authenticate(String username) throws Exception {
    DirContext context = open();/*from w ww  .  j a va2s.c o m*/
    try {

        String filter = userSearchMatchingFormat.format(new String[] { username });
        SearchControls constraints = new SearchControls();
        if (userSearchSubtreeBool) {
            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        } else {
            constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        }

        // setup attributes
        String[] attribs;
        if (userRoleName == null) {
            attribs = new String[] {};
        } else {
            attribs = new String[] { userRoleName };
        }
        constraints.setReturningAttributes(attribs);

        NamingEnumeration results = context.search(userBase, filter, constraints);

        if (results == null || !results.hasMore()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        }

        SearchResult result = (SearchResult) results.next();

        if (results.hasMore()) {
            // ignore for now
        }
        NameParser parser = context.getNameParser("");
        Name contextName = parser.parse(context.getNameInNamespace());
        Name baseName = parser.parse(userBase);
        Name entryName = parser.parse(result.getName());
        Name name = contextName.addAll(baseName);
        name = name.addAll(entryName);
        String dn = name.toString();

        Attributes attrs = result.getAttributes();
        if (attrs == null) {
            return false;
        }
        ArrayList<String> roles = null;
        if (userRoleName != null) {
            roles = addAttributeValues(userRoleName, attrs, roles);
        }
        // check the credentials by binding to server
        // bindUser(context, dn);
        // if authenticated add more roles
        roles = getRoles(context, dn, username, roles);
        for (String role : roles) {
            groups.add(role);
        }
        if (groups.isEmpty()) {
            log.error("No roles associated with user " + username);
            loginSucceeded = false;
            throw new FailedLoginException();
        } else
            loginSucceeded = true;

    } catch (CommunicationException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    } catch (NamingException e) {
        close(context);
        throw (LoginException) new FailedLoginException().initCause(e);
    }
    return true;
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * Gets all the user entities taken from the LDAP server, as taken from the
 * search-context given by the value of the attribute {@link #userBase}.
 *
 * @return A set containing all the relevant users found in the LDAP
 *         directory./*from  w  ww .j  a va2 s.  c  o m*/
 * @throws NamingException
 *             Propagated from the LDAP communication layer.
 */
private Set<String> getAllUsersFromLDAP() throws NamingException {
    Set<String> result = new HashSet<String>();

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { "distinguishedName" });
    NamingEnumeration<SearchResult> sr = ldapContext.search(userBase, "(objectClass=" + userObjectClass + ")",
            sc);
    while (sr.hasMore()) {
        SearchResult r = sr.next();
        result.add(r.getNameInNamespace());
    }

    return result;
}

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   www  . j a v a2 s .c  o m
 *            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:org.apache.syncope.fit.core.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty");
    DerSchemaTO modified = SerializationUtils.clone(orig);
    modified.setExpression("icon + '_' + show");

    GroupTO groupTO = GroupITCase.getSampleTO("lastGroup");
    try {/* w ww.  j a va 2 s  .c  om*/
        schemaService.update(SchemaType.DERIVED, modified);

        // 0. create group
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getResources().clear();

        groupTO = createGroup(groupTO).getEntity();
        assertNotNull(groupTO);

        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPriority(0);

        for (ProvisionTO provision : newLDAP.getProvisions()) {
            provision.getVirSchemas().clear();
        }

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).get().getMapping();

        ItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntAttrName("displayProperty");
        connObjectKey.setPurpose(MappingPurpose.PROPAGATION);
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        ItemTO description = new ItemTO();
        description.setIntAttrName("key");
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.PROPAGATION);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. update group and give the resource created above
        GroupPatch patch = new GroupPatch();
        patch.setKey(groupTO.getKey());
        patch.getResources().add(
                new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build());

        groupTO = updateGroup(patch).getEntity();
        assertNotNull(groupTO);

        // 3. update the group
        GroupPatch groupPatch = new GroupPatch();
        groupPatch.setKey(groupTO.getKey());
        groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon"));

        groupTO = updateGroup(groupPatch).getEntity();
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        schemaService.update(SchemaType.DERIVED, orig);
        if (groupTO.getKey() != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apache.syncope.fit.core.reference.GroupITCase.java

@Test
public void issueSYNCOPE632() {
    GroupTO groupTO = null;/*w w  w. j  a  va  2  s .com*/
    try {
        // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);

        MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).getMapping();

        MappingItemTO connObjectKey = mapping.getConnObjectKeyItem();
        connObjectKey.setIntMappingType(IntMappingType.GroupDerivedSchema);
        connObjectKey.setIntAttrName("displayProperty");
        mapping.setConnObjectKeyItem(connObjectKey);
        mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.GroupKey);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        mapping.add(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a group and give the resource created above
        groupTO = getSampleTO("lastGroup" + getUUIDString());
        groupTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        groupTO.getPlainAttrs().add(attrTO("show", "true"));
        groupTO.getDerAttrs().add(attrTO("displayProperty", null));
        groupTO.getResources().clear();
        groupTO.getResources().add("new-ldap");

        groupTO = createGroup(groupTO);
        assertNotNull(groupTO);

        // 3. update the group
        GroupMod groupMod = new GroupMod();
        groupMod.setKey(groupTO.getKey());
        groupMod.getPlainAttrsToRemove().add("icon");
        groupMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        groupTO = updateGroup(groupMod);
        assertNotNull(groupTO);

        // 4. check that a single group exists in LDAP for the group created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + groupTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (groupTO != null) {
            groupService.delete(groupTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}

From source file:org.apache.syncope.fit.core.reference.RoleITCase.java

@Test
public void issueSYNCOPE632() {
    RoleTO roleTO = null;//from   w  w w  . ja v a 2 s .  c om
    try {
        // 1. create new LDAP resource having account id mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);
        MappingItemTO accountId = newLDAP.getRmapping().getAccountIdItem();
        accountId.setIntMappingType(IntMappingType.RoleDerivedSchema);
        accountId.setIntAttrName("displayProperty");
        newLDAP.getRmapping().setAccountIdItem(accountId);
        newLDAP.getRmapping().setAccountLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.RoleId);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        newLDAP.getRmapping().addItem(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a role and give the resource created above
        roleTO = buildRoleTO("lastRole");
        roleTO.getRPlainAttrTemplates().add("icon");
        roleTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        roleTO.getRPlainAttrTemplates().add("show");
        roleTO.getPlainAttrs().add(attrTO("show", "true"));
        roleTO.getRDerAttrTemplates().add("displayProperty");
        roleTO.getDerAttrs().add(attrTO("displayProperty", null));
        roleTO.getResources().clear();
        roleTO.getResources().add("new-ldap");

        roleTO = createRole(roleTO);
        assertNotNull(roleTO);

        // 3. update the role
        RoleMod roleMod = new RoleMod();
        roleMod.setKey(roleTO.getKey());
        roleMod.getPlainAttrsToRemove().add("icon");
        roleMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        roleTO = updateRole(roleMod);
        assertNotNull(roleTO);

        // 4. check that a single group exists in LDAP for the role created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + roleTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (roleTO != null) {
            roleService.delete(roleTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}