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.eclipse.skalli.core.user.ldap.LDAPClient.java

@SuppressWarnings("nls")
private SearchControls getSearchControls() {
    SearchControls sc = new SearchControls();
    if ("base".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    } else if ("onelevel".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    } else if ("subtree".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    }/*from   ww w  . j  a  v  a  2 s .  c o m*/
    sc.setReturningAttributes(LDAPAttributeNames.getAll());
    return sc;
}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

/**
 * @param dn       the distinguished name of the entry - may be either relative to the base
 *                 context or a complete DN including the name of the context (either is
 *                 supported)./*from   www. j a  v a2 s.c  o m*/
 * @param username the user whose roles are required.
 * @return the granted authorities returned by the group search
 */
@SuppressWarnings("unchecked")
List<GrantedAuthority> getUserAuthorities(final DistinguishedName dn, final String username) {
    SearchExecutor se = new SearchExecutor() {
        public NamingEnumeration<SearchResult> executeSearch(DirContext ctx) throws NamingException {
            DistinguishedName fullDn = LdapUtils.getFullDn(dn, ctx);
            SearchControls ctrls = new SearchControls();
            ctrls.setReturningAttributes(new String[] { groupRoleAttributeName });

            return ctx.search(groupSearchBase, groupSearchFilter, new String[] { fullDn.toUrl(), username },
                    ctrls);
        }
    };

    AttributesMapperCallbackHandler roleCollector = new AttributesMapperCallbackHandler(roleMapper);

    template.search(se, roleCollector);
    return roleCollector.getList();
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

/**
 * @see {@link AccountDao#findAll()}//from  w w w  .  j a  v a  2 s.  c o m
 */
@Override
public List<Account> findAll() throws DataServiceException {
    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    EqualsFilter filter = new EqualsFilter("objectClass", "person");
    return ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc, attributMapper);
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

@Override
public List<Account> find(final ProtectedUserFilter filterProtected, Filter f) {
    SearchControls sc = new SearchControls();
    sc.setReturningAttributes(UserSchema.ATTR_TO_RETRIEVE);
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    AndFilter and = new AndFilter();
    and.and(new EqualsFilter("objectClass", "person"));
    and.and(f);//ww  w .  j  av a  2s  .co  m
    List<Account> l = ldapTemplate.search(DistinguishedName.EMPTY_PATH, and.encode(), sc, attributMapper);
    return filterProtected.filterUsersList(l);
}

From source file:org.georchestra.console.ds.AccountDaoImpl.java

/**
 * @see {@link AccountDao#findByEmail(String)}
 *//*from  w w w  . j a v a  2 s . c  o 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.georchestra.console.ds.AccountDaoImpl.java

@Override
public List<Account> findByShadowExpire() {

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

    AndFilter filter = new AndFilter();
    filter.and(new EqualsFilter("objectClass", "shadowAccount"));
    filter.and(new EqualsFilter("objectClass", "inetOrgPerson"));
    filter.and(new EqualsFilter("objectClass", "organizationalPerson"));
    filter.and(new EqualsFilter("objectClass", "person"));
    filter.and(new PresentFilter("shadowExpire"));

    return ldapTemplate.search(DistinguishedName.EMPTY_PATH, filter.encode(), sc, attributMapper);

}

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

private MetricValue getMetric(Metric metric, String tree, String attr)
        throws MetricNotFoundException, NamingException {
    NamingEnumeration enumer = null;
    try {/*from   w w  w .  jav a2 s. c o  m*/
        String[] a = { attr };
        SearchControls cons = new SearchControls();
        cons.setSearchScope(SearchControls.OBJECT_SCOPE);
        cons.setReturningAttributes(a);
        enumer = getDirContext(metric.getProperties()).search(tree, "(&(objectClass=*))", cons);
        while (enumer.hasMore()) {
            SearchResult searchresult = (SearchResult) enumer.next();
            Attributes attrs = searchresult.getAttributes();
            Attribute val;
            if (null != (val = attrs.get(attr))) {
                return new MetricValue(new Double(val.get().toString()), System.currentTimeMillis());
            }
        }
        throw new MetricNotFoundException("");
    } finally {
        if (enumer != null) {
            enumer.close();
        }
    }
}

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  www.ja v a 2 s . c  om
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.portal.groups.ldap.LDAPGroupStore.java

public EntityIdentifier[] searchForEntities(String query, int method, Class type) throws GroupsException {
    if (type != group && type != iperson)
        return new EntityIdentifier[0];
    ArrayList ids = new ArrayList();
    switch (method) {
    case STARTS_WITH:
        query = query + "*";
        break;//ww w .  j  a v  a2 s  .  co  m
    case ENDS_WITH:
        query = "*" + query;
        break;
    case CONTAINS:
        query = "*" + query + "*";
        break;
    }
    query = namefield + "=" + query;
    DirContext context = getConnection();
    NamingEnumeration userlist = null;
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(new String[] { keyfield });
    try {
        userlist = context.search(usercontext, query, sc);
    } catch (NamingException nex) {
        log.error("LDAPGroupStore: Unable to perform filter " + query, nex);
    }
    ArrayList keys = new ArrayList();
    processLdapResults(userlist, keys);
    String[] k = (String[]) keys.toArray(new String[0]);
    for (int i = 0; i < k.length; i++) {
        ids.add(new EntityIdentifier(k[i], iperson));
    }
    return (EntityIdentifier[]) ids.toArray(new EntityIdentifier[0]);
}

From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java

/**
 * Authenticates the user./* w w  w .  j av a 2 s.  co  m*/
 */
public synchronized void authenticate() throws PortalSecurityException {
    this.isauth = false;
    ILdapServer ldapConn;

    String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME);
    if (propFile != null && propFile.length() > 0)
        ldapConn = LdapServices.getLdapServer(propFile);
    else
        ldapConn = LdapServices.getDefaultLdapServer();

    String creds = new String(this.myOpaqueCredentials.credentialstring);
    if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("")
            && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) {
        DirContext conn = null;
        NamingEnumeration results = null;
        StringBuffer user = new StringBuffer("(");
        String first_name = null;
        String last_name = null;

        user.append(ldapConn.getUidAttribute()).append("=");
        user.append(this.myPrincipal.UID).append(")");
        if (log.isDebugEnabled())
            log.debug("SimpleLdapSecurityContext: Looking for " + user.toString());

        try {
            conn = ldapConn.getConnection();

            // set up search controls
            SearchControls searchCtls = new SearchControls();
            searchCtls.setReturningAttributes(attributes);
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            // do lookup
            if (conn != null) {
                try {
                    results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls);
                    if (results != null) {
                        if (!results.hasMore())
                            log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID);
                        while (results != null && results.hasMore()) {
                            SearchResult entry = (SearchResult) results.next();
                            StringBuffer dnBuffer = new StringBuffer();
                            dnBuffer.append(entry.getName()).append(", ");
                            dnBuffer.append(ldapConn.getBaseDN());
                            Attributes attrs = entry.getAttributes();
                            first_name = getAttributeValue(attrs, ATTR_FIRSTNAME);
                            last_name = getAttributeValue(attrs, ATTR_LASTNAME);
                            // re-bind as user
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL);
                            conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS);
                            conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString());
                            conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS,
                                    this.myOpaqueCredentials.credentialstring);
                            searchCtls = new SearchControls();
                            searchCtls.setReturningAttributes(new String[0]);
                            searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

                            String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)";
                            log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for "
                                    + attrSearch);
                            conn.search(dnBuffer.toString(), attrSearch, searchCtls);

                            this.isauth = true;
                            this.myPrincipal.FullName = first_name + " " + last_name;
                            log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " ("
                                    + this.myPrincipal.FullName + ") is authenticated");

                            // Since LDAP is case-insensitive with respect to uid, force
                            // user name to lower case for use by the portal
                            this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase();
                        } // while (results != null && results.hasMore())
                    } else {
                        log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID);
                    }
                } catch (AuthenticationException ae) {
                    log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID);
                } catch (Exception e) {
                    log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ",
                            e);
                    throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e
                            + " with user: " + this.myPrincipal.UID);
                } finally {
                    ldapConn.releaseConnection(conn);
                }
            } else {
                log.error("LDAP Server Connection unavalable");
            }
        } catch (final NamingException ne) {
            log.error("Error geting connection to LDAP server.", ne);
        }
    } else {
        log.error("Principal or OpaqueCredentials not initialized prior to authenticate");
    }
    // Ok...we are now ready to authenticate all of our subcontexts.
    super.authenticate();
    return;
}