Example usage for javax.naming.directory SearchControls setReturningObjFlag

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

Introduction

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

Prototype

public void setReturningObjFlag(boolean on) 

Source Link

Document

Enables/disables returning objects returned as part of the result.

Usage

From source file:ca.aedwards.ldap.compnent.LdapClConsumer.java

public List<LdapSearchResult> getAllPersonNames() {
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningObjFlag(true);
    AndFilter filter = new AndFilter();
    //filter.and(new EqualsFilter("objectclass", "person"));
    filter.and(new GreaterThanOrEqualsFilter("changeNumber", Long.toString(clLast)));
    List<LdapSearchResult> results = endpoint.getLdapTemplate().search(DistinguishedName.EMPTY_PATH,
            filter.encode(), sc, new LdapResultContextMapper());
    //System.out.println("results: " + results.toString());
    System.out.println("Filter: " + filter.toString());
    return results;
}

From source file:se.inera.axel.shs.broker.directory.internal.LdapDirectoryService.java

/**
 * Finds all entries matching filter, mapped with the mapper.
 * If organization is given, it is used as a search base.
 * For instance: list all addresses under a given organization.
 *
 * At most 'limit' entries are returned.
 *
 * @param organization//w  w w.  j ava 2s  .c  o m
 * @param filter
 * @param mapper
 * @param limit
 * @param dirContextProcessor
 * @param <T>
 * @return
 * @throws DirectoryException
 */
private <T> List<T> findAll(Organization organization, AndFilter filter, ParameterizedContextMapper<T> mapper,
        long limit, DirContextProcessor dirContextProcessor) throws DirectoryException {
    List<T> entries = new ArrayList<T>();
    String base = "";
    try {
        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningObjFlag(true);
        ctrl.setCountLimit(limit);

        if (organization != null) {
            base = "o=" + organization.getOrgName();
        }

        entries = ldapTemplate.search(base, filter.encode(), ctrl, mapper, dirContextProcessor);

        // Remove duplicates...
        HashSet<T> set = new HashSet<T>(entries);
        entries = new ArrayList<T>(set);

    } catch (NameNotFoundException e) {
        log.warn("not found in ldap directory: " + base + "," + filter.encode());
    } catch (RuntimeException e) {
        log.error("error during looking-up", e);
        throw new DirectoryException("error during looking-up", e);
    }

    return entries;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private SearchControls getDefaultSearchControls() {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SUBTREE_SCOPE);
    controls.setReturningAttributes(null);
    controls.setReturningObjFlag(true);
    return controls;
}

From source file:com.teklabs.throng.integration.ldap.Ldap.java

private String getPrincipal(String login) throws NamingException {
    if (baseDN == null) {
        throw new IllegalArgumentException("LDAP BaseDN is not set");
    }/*w  ww .  j ava2 s  .co  m*/
    InitialDirContext context = null;
    String principal;
    try {
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("Search principal: " + login);
        }

        context = ldapContextFactory.getInitialDirContext();
        String request = "(&(objectClass=" + userObjectClass + ")(" + loginAttribute + "={0}))";
        if (LdapHelper.LOG.isDebugEnabled()) {
            LdapHelper.LOG.debug("LDAP request: " + request);
        }

        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        controls.setReturningAttributes(new String[] {});
        controls.setReturningObjFlag(true);
        NamingEnumeration result = context.search(baseDN, request, new String[] { login }, controls);
        String found = null;
        if (result.hasMore()) {
            SearchResult obj = (SearchResult) result.next();
            found = obj.getNameInNamespace();
            if (found != null && result.hasMore()) {
                found = null;
                LdapHelper.LOG.error(
                        "Login \'" + login + "\' is not unique in LDAP (see attribute " + loginAttribute + ")");
            }
        }

        principal = found;
    } finally {
        LdapHelper.closeContext(context);
    }

    return principal;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx)
        throws NamingException {
    String uid;/*ww  w  . j a  v a2  s. c  om*/
    SearchControls ctls = new SearchControls();
    ctls.setReturningObjFlag(true);
    ctls.setSearchScope(searchScope);
    String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login));
    log.debug("Searching LDAP for " + search);
    NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls);
    try {
        if (!answer.hasMore())
            throw new NoSuchElementException();
        log.debug("LDAP returned >=1 record.");
        SearchResult result = answer.next();
        uid = result.getName();
        for (Map.Entry<String, String> e : attributeMap.entrySet()) {
            log.debug("found LDAP attribute: " + e.getKey());
            Attribute a = result.getAttributes().get(e.getKey());
            if (a != null)
                userAttrs.put(e.getValue(), a.get().toString());
        }
    } finally {
        answer.close();
    }
    return uid;
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {//ww  w  .ja v a  2s  .  c  o  m
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

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: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  w w  w  .  ja  v  a2s. 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:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return the user dn of an ldap entry//from   www.j  a v  a  2s  . 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;
    }
}

From source file:org.dcm4che3.conf.dicom.ldap.LdapConfigUtils.java

static NamingEnumeration<SearchResult> searchSubcontextWithClass(
        LdapConfigurationStorage ldapConfigurationStorage, String childObjClass, String dn)
        throws NamingException {
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(1);//from   w ww  . j  a  va  2 s  .c  o m
    ctls.setReturningObjFlag(false);
    return ldapConfigurationStorage.getLdapCtx().search(dn, "(objectclass=" + childObjClass + ")", ctls);
}