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:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java

/**
 * Returns the values of the specified fields for the supplied id. 
 * @see IExternalStorage#getFields(java.lang.String, java.util.List)
 *///w  ww . j  a v a2s . c o  m
public Hashtable<String, Object> getFields(String id, List<String> fields) throws UserException {
    Hashtable<String, Object> htReturn = new Hashtable<String, Object>();
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] saFields = fields.toArray(new String[0]);
        oScope.setReturningAttributes(saFields);

        String searchFilter = resolveSearchQuery(id);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes '");
            sbFailed.append(fields);
            sbFailed.append("' for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.error("User unknown: " + id);
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        }

        if (!oNamingEnumeration.hasMore()) {
            StringBuffer sbFailed = new StringBuffer("User with id '");
            sbFailed.append(id);
            sbFailed.append("' not found after LDAP search with filter: ");
            sbFailed.append(searchFilter);
            _logger.error(sbFailed.toString());
            throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
        Attributes oAttributes = oSearchResult.getAttributes();
        NamingEnumeration neAttributes = oAttributes.getAll();
        while (neAttributes.hasMore()) {
            Attribute oAttribute = (Attribute) neAttributes.next();
            String sAttributeName = oAttribute.getID();

            if (oAttribute.size() > 1) {
                Vector<Object> vValue = new Vector<Object>();
                NamingEnumeration neAttribute = oAttribute.getAll();
                while (neAttribute.hasMore())
                    vValue.add(neAttribute.next());

                htReturn.put(sAttributeName, vValue);
            } else {
                Object oValue = oAttribute.get();
                if (oValue == null)
                    oValue = "";
                htReturn.put(sAttributeName, oValue);
            }
        }
    } catch (UserException e) {
        throw e;
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields: " + fields, e);
        throw new UserException(SystemErrors.ERROR_INTERNAL, e);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + id, e);
            }
        }
    }
    return htReturn;
}

From source file:net.jolm.JolmLdapTemplate.java

private SearchControls getDefaultSearchControls(int searchScope, boolean returnObjFlag, String[] attributes) {
    SearchControls controls = new SearchControls();

    controls.setSearchScope(searchScope);
    controls.setReturningObjFlag(returnObjFlag);
    controls.setReturningAttributes(attributes);
    controls.setTimeLimit(this.searchTimeoutInMs);

    return controls;
}

From source file:org.jasig.cas.adaptors.ldap.LdapPasswordPolicyEnforcer.java

private SearchControls getSearchControls(final String[] attributeIds) {
    final SearchControls constraints = new SearchControls();

    constraints.setSearchScope(this.scope);
    constraints.setReturningAttributes(attributeIds);
    constraints.setTimeLimit(this.timeout);
    constraints.setCountLimit(this.maxNumberResults);

    return constraints;
}

From source file:com.alfaariss.oa.engine.attribute.gather.processor.jndi.JNDIGatherer.java

/**
 * Gathers attributes from JNDI storage to the supplied attributes object.
 * @see com.alfaariss.oa.engine.core.attribute.gather.processor.IProcessor#process(java.lang.String, com.alfaariss.oa.api.attribute.IAttributes)
 *//*from   ww  w. j  a  v a2 s  .  c o m*/
public void process(String sUserId, IAttributes oAttributes) throws AttributeException {
    DirContext oDirContext = null;
    NamingEnumeration oNamingEnumeration = null;
    try {
        try {
            oDirContext = new InitialDirContext(_htJNDIEnvironment);
        } catch (NamingException e) {
            _logger.error("Could not create the connection: " + _htJNDIEnvironment);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_CONNECT, e);
        }

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (_listGather.size() > 0) {
            String[] saAttributes = _listGather.toArray(new String[0]);
            oScope.setReturningAttributes(saAttributes);
        }

        String searchFilter = resolveSearchQuery(sUserId);
        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(searchFilter);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(sUserId);
            _logger.error(sbFailed.toString(), e);
            throw new AttributeException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e);
        } catch (NamingException e) {
            _logger.debug("User unknown: " + sUserId);
            return;
        }

        if (oNamingEnumeration.hasMore()) {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();
            Attributes oSearchedAttributes = oSearchResult.getAttributes();
            NamingEnumeration neAttributes = oSearchedAttributes.getAll();
            while (neAttributes.hasMore()) {
                Attribute oAttribute = (Attribute) neAttributes.next();
                String sAttributeName = oAttribute.getID();
                String sMappedName = _htMapper.get(sAttributeName);
                if (sMappedName != null)
                    sAttributeName = sMappedName;

                if (oAttribute.size() > 1) {
                    Vector<Object> vValue = new Vector<Object>();
                    NamingEnumeration neAttribute = oAttribute.getAll();
                    while (neAttribute.hasMore())
                        vValue.add(neAttribute.next());

                    oAttributes.put(sAttributeName, vValue);
                } else {
                    Object oValue = oAttribute.get();
                    if (oValue == null)
                        oValue = "";
                    oAttributes.put(sAttributeName, oValue);
                }
            }
        }
    } catch (AttributeException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch attributes for user: " + sUserId, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for user with id: " + sUserId, e);
        throw new AttributeException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for user with id: " + sUserId,
                        e);
            }
        }
        if (oDirContext != null) {
            try {
                oDirContext.close();
            } catch (NamingException e) {
                _logger.error("Could not close Dir Context after searching for user with id: " + sUserId, e);
            }
        }
    }
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Retrieves the roles for the from the identity provider.
 *
 * @param username the user to get the roles for
 * @return the list of roles for the user
 * @throws PortalServiceException for any errors encountered
 *//*from   w w  w  .  j a v a 2  s  .c o  m*/
@SuppressWarnings("rawtypes")
public List<String> findRoles(String username) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);

        // Search for groups the user belongs to in order to get their names
        // Create the search controls
        SearchControls groupsSearchCtls = new SearchControls();

        // Specify the search scope
        groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Specify the attributes to return
        String groupsReturnedAtts[] = { "cn" };
        groupsSearchCtls.setReturningAttributes(groupsReturnedAtts);

        String userDn = MessageFormat.format(userDNPattern, username);
        // Search for objects using the filter
        NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase,
                MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls);

        List<String> groups = new ArrayList<String>();
        // Loop through the search results
        while (groupsAnswer.hasMoreElements()) {

            SearchResult sr = (SearchResult) groupsAnswer.next();
            Attributes attrs = sr.getAttributes();

            if (attrs != null) {
                groups.add((String) attrs.get("cn").get());
            }

            if (sr.getObject() instanceof Context) {
                closeContext((Context) sr.getObject());
            }
        }
        return groups;
    } catch (NamingException e) {
        throw new PortalServiceConfigurationException("Unable to get groups.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java

private boolean bindSearchX(String username, String password, Hashtable<String, String> env, boolean bind)
        throws AuthenticationException, NamingException {

    env.put(Context.SECURITY_PRINCIPAL, ldapSecurityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, ldapSecurityCredentials);

    DirContext ctx = null;/*from www  . j  a  va2s  . co  m*/
    try {
        ctx = new InitialDirContext(env);
    } catch (NamingException ne) {
        log.error("Failed to bind as: {}", ldapSecurityPrincipal);
    }

    // ensure we have the userPassword attribute at a minimum
    String[] attributeList = new String[] { "userPassword" };

    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(attributeList);
    sc.setDerefLinkFlag(true);
    sc.setReturningObjFlag(false);
    sc.setTimeLimit(5000);

    String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")";
    // Do the search
    NamingEnumeration<SearchResult> results = ctx.search(baseDn, filter, sc);
    if (!results.hasMore()) {
        log.warn("no valid user found.");
        return false;
    }

    SearchResult result = results.next();
    log.debug("authenticating user: {}", result.getNameInNamespace());

    if (bind) {
        // setup user context for binding
        Hashtable<String, String> userEnv = new Hashtable<String, String>();
        userEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        userEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
        userEnv.put(Context.PROVIDER_URL, baseUrl);
        userEnv.put(Context.SECURITY_PRINCIPAL, result.getNameInNamespace());
        userEnv.put(Context.SECURITY_CREDENTIALS, password);

        try {
            new InitialDirContext(userEnv);
        } catch (NamingException ne) {
            log.error("failed to authenticate user: " + result.getNameInNamespace());
            throw ne;
        }
    } else {
        // get userPassword attribute
        Attribute up = result.getAttributes().get("userPassword");
        if (up == null) {
            log.error("unable to read userPassword attribute for: {}", result.getNameInNamespace());
            return false;
        }

        byte[] userPasswordBytes = (byte[]) up.get();
        String userPassword = new String(userPasswordBytes);

        // compare passwords - also handles encodings
        if (!passwordsMatch(password, userPassword)) {
            return false;
        }
    }

    return true;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

public NamingEnumeration<SearchResult> query(DirContext ctx, String pBaseDn, String filter,
        String[] attributeFilter, Integer pScope) throws NamingException, IllegalAccessException {
    NamingEnumeration<SearchResult> vResult;
    SearchControls sControl = new SearchControls();
    if (attributeFilter != null) {
        sControl.setReturningAttributes(attributeFilter);
    }//from w  w w. ja va 2s . com
    int vScope = SearchControls.SUBTREE_SCOPE;
    if (pScope != null) {
        vScope = pScope.intValue();
    }
    sControl.setSearchScope(vScope);
    vResult = ctx.search(((pBaseDn != null) && (pBaseDn.length() > 0) ? pBaseDn
            : LDAPConnector.getSingletonInstance().getBaseDn()), filter, sControl);
    return vResult;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Search the LDAP based on default inputs. This method searches for <b>memberOf </b>
 * @return/* w ww .j ava 2 s.  c  om*/
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults() {

    // Specify the attributes to return
    String returnedAtts[] = { PROPERTY_MEMBER_OF };
    // Specify the search scope
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(returnedAtts);
    // Search for objects using the filter
    try {
        return getSearchResults(getLDAPContext(), searchCtls, SEARCH_FILTER, LDAP_BASE);
    } catch (NamingException e) {
        Logger.error("Error occured while searching results : 181: getSearchResults():["
                + e.getLocalizedMessage() + "]", LDAPUtils.class);
    }
    return null;
}

From source file:com.wfp.utils.LDAPUtils.java

/**
 * Overloaded method for searching the LDAP based on the searchfilter & searchbase with contraint as "cn"
 * @param searchFilter/*from w  w  w  . j  a v  a  2s  .c om*/
 * @param searchBase
 * @return
 * @throws NamingException
 */
@SuppressWarnings("unchecked")
public static NamingEnumeration getSearchResults(String searchFilter, String searchBase) {

    // Specify the attributes to return
    String returnedAtts[] = { PROPERTY_CN };
    // Specify the search scope
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setReturningAttributes(returnedAtts);
    // Search for objects using the filter
    try {
        return getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase);
    } catch (NamingException e) {
        Logger.error(
                " Error occured while searching results 206: getSearchResults(String searchFilter, String searchBase):["
                        + e.getLocalizedMessage() + "]",
                LDAPUtils.class);
    }
    return null;
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return the user dn of an ldap entry//www.  j av a2 s  .  c  o  m
 * 
 * search: base, filter, attrs, user, pass
 * @return
 */
protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter,
        String[] attributes) {
    SearchResult ret = null;
    Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11);
    bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    bindEnv.put(Context.PROVIDER_URL, getLdapUrl());

    // remove null attributes
    List<String> goodAttributes = new ArrayList<String>();
    for (String s : attributes) {
        if (s != null) {
            goodAttributes.add(s);
        }
    }

    // get the DN 
    DirContext authenticationContext;
    try {
        SearchControls ctls = new SearchControls();
        ctls.setCountLimit(1);
        ctls.setReturningObjFlag(true);
        ctls.setReturningAttributes(goodAttributes.toArray(new String[0]));
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Authenticate as  User and password  
        if (bindUser != null && bindPass != null) {
            log.debug("NBinding with credential as user: " + bindUser);
            bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser);
            bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass);
        }
        authenticationContext = new InitialDirContext(bindEnv);
        // %u, %d in baseDN are still expanded 
        NamingEnumeration<SearchResult> answer;
        try {
            answer = authenticationContext.search(base, filter, ctls);

            if (answer.hasMore()) {
                ret = (SearchResult) answer.next();
            }
        } catch (NamingException e) {
            log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage());
        }
        authenticationContext.close();
        return ret;

    } catch (NamingException e) {
        log.error("Error while creating context: " + e.getMessage());
        if (e.getCause() != null) {
            log.error("Error is: " + e.getCause().getMessage());
        }
        return null;
    }
}