Example usage for javax.naming.directory SearchControls setTimeLimit

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

Introduction

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

Prototype

public void setTimeLimit(int ms) 

Source Link

Document

Sets the time limit of these SearchControls in milliseconds.

Usage

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.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 v a  2 s.  c o 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.wfp.utils.LDAPUtils.java

public static SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    return searchControls;
}

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

public static SearchControls getSimpleSearchControls(String[] attrIDS) {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    if (attrIDS != null) {
        searchControls.setReturningAttributes(attrIDS);
    }/*from  w  ww . ja v  a 2  s.c  o m*/

    return searchControls;
}

From source file:ldap.ActiveLoginImpl.java

/**
 * Returns whether this user is listed in the admin users role
 *
 * @param login//from  ww w  .  j av a2  s.  c  o m
 * @return
 * @throws Exception
 */
public boolean isAdmin(String login, DirContext context, String DN) throws Exception {
    NamingEnumeration result = null;

    String[] returnAttributes = new String[] { "uniqueMember" };

    /* specify search constraints to search subtree */
    SearchControls constraints = new SearchControls();

    constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
    constraints.setCountLimit(0);
    constraints.setTimeLimit(0);

    constraints.setReturningAttributes(returnAttributes);
    /*
            Entry user = null;
            try {
    user = searcher.getUser(LdapConstants.ldapAttrLogin, login, context);
            } catch (NamingException e) {
               throw new LdapException("getUser NamingException" + e.getMessage(), e);
            }
       String DN = null;
            if (user == null) {
               logger.info("USER DOES NOT EXIST");
               return false;
            } else {
          DN = user.getName().toString();
               if (DN != null) {
      logger.info("DN = " + DN);
               }
       }
    */

    //result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember="+getUserDN(login)+")", constraints);
    result = context.search(LdapConstants.ldapAdminRoleDn, "(uniqueMember=" + DN + ")", constraints);

    if (result.hasMore()) {
        if (debug) {
            SearchResult sResult = (SearchResult) result.next();
            logger.info("Read Admin Roles Object with members: " + sResult.getAttributes().toString());
        }
        return true;
    } else if (debug)
        logger.info("Failed to find admin object with member " + DN);

    return false;
}

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

/**
 * Returns the {@link SearchControls} object associated with the request.
 *
 * @param request/*w  w  w .  j  av a 2  s. com*/
 *      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.nuxeo.ecm.directory.ldap.LDAPDirectory.java

/**
 * Search controls that only fetch attributes defined by the schema
 *
 * @return common search controls to use for all LDAP search queries
 * @throws DirectoryException//from   www  . ja v a2  s .c  o  m
 */
protected SearchControls computeSearchControls() throws DirectoryException {
    LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor();
    SearchControls scts = new SearchControls();
    // respect the scope of the configuration
    scts.setSearchScope(ldapDirectoryDesc.getSearchScope());

    // only fetch attributes that are defined in the schema or needed to
    // compute LDAPReferences
    Set<String> attrs = new HashSet<>();
    for (String fieldName : schemaFieldMap.keySet()) {
        if (!references.containsKey(fieldName)) {
            attrs.add(fieldMapper.getBackendField(fieldName));
        }
    }
    attrs.add("objectClass");

    for (Reference reference : getReferences()) {
        if (reference instanceof LDAPReference) {
            LDAPReference ldapReference = (LDAPReference) reference;
            attrs.add(ldapReference.getStaticAttributeId(fieldMapper));
            attrs.add(ldapReference.getDynamicAttributeId());

            // Add Dynamic Reference attributes filtering
            for (LDAPDynamicReferenceDescriptor dynAtt : ldapReference.getDynamicAttributes()) {
                attrs.add(dynAtt.baseDN);
                attrs.add(dynAtt.filter);
            }

        }
    }

    if (getPasswordField() != null) {
        // never try to fetch the password
        attrs.remove(getPasswordField());
    }

    scts.setReturningAttributes(attrs.toArray(new String[attrs.size()]));

    scts.setCountLimit(ldapDirectoryDesc.getQuerySizeLimit());
    scts.setTimeLimit(ldapDirectoryDesc.getQueryTimeLimit());

    return scts;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int)
 *//*from  w  w w . jav a 2s .c o m*/
@Override
public List<UserPrincipal> searchCandidateUsers(String searchCriteria, int maxResults)
        throws RepositoryException {
    List<UserPrincipal> userList = new ArrayList<>();

    if ((searchCriteria != null) && (searchCriteria.length() > 0)) {
        List<String> searchAttributes = Arrays.asList(userLastNameAttribute, userFirstNameAttribute,
                userFullNameAttribute);
        StringBuilder searchFilter = new StringBuilder("(&(objectCategory=person)(").append(userIdAttribute)
                .append("=*)(|");
        SearchControls constraints = new SearchControls();
        DirContext context = null;

        for (String searchAttr : searchAttributes) {
            if ((searchAttr != null) && (searchAttr.length() > 0)) {
                searchFilter.append("(").append(searchAttr).append("=*").append(searchCriteria).append("*)");
            }
        }
        searchFilter.append("))");
        constraints.setSearchScope(
                searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
        constraints.setTimeLimit(userSearchTimeout);
        constraints.setCountLimit(maxResults);
        constraints.setReturningAttributes(new String[] { userIdAttribute, userLastNameAttribute,
                userFirstNameAttribute, userEmailAttribute });

        try {
            context = openConnection(connectionPrincipal, connectionPassword);
            NamingEnumeration<SearchResult> searchResults = context.search(userSearchBase,
                    searchFilter.toString(), constraints);

            while (searchResults.hasMore()) {
                SearchResult resultItem = searchResults.next();
                Attributes itemAttrs = resultItem.getAttributes();
                String userId = getAttributeValue(itemAttrs, userIdAttribute);
                String lastName = getAttributeValue(itemAttrs, userLastNameAttribute);
                String firstName = getAttributeValue(itemAttrs, userFirstNameAttribute);
                String email = getAttributeValue(itemAttrs, userEmailAttribute);
                UserPrincipal user = new UserPrincipal();

                user.setUserId(userId);
                user.setLastName(lastName);
                user.setFirstName(firstName);
                user.setEmailAddress(email);
                userList.add(user);
            }

        } catch (PartialResultException | SizeLimitExceededException e) {
            // Ignore - this means we have reached the end of the list and that any remaining
            // items are aliased referrals which cannot be resolved.

        } catch (NamingException e) {
            throw new RepositoryException("Error encountered during directory search.", e);
        }
    }
    return userList;
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Searches the remote directory for the user's entry and returns its distinguished name
 * string./*from w w w .  j a  va 2s . c om*/
 * 
 * @param userId
 *            the ID of the user whose DN is to be retrieved
 * @param context
 *            the directory context from which to retrieve the user's DN
 * @return String
 * @throws NamingException
 */
protected String findUserDn(String userId, DirContext context) throws NamingException {
    String userDn = null;

    for (MessageFormat userSearchPattern : userSearchPatterns) {
        try {
            String searchFilter = userSearchPattern.format(new String[] { userId });
            SearchControls constraints = new SearchControls();

            constraints.setSearchScope(
                    searchUserSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE);
            constraints.setTimeLimit(userSearchTimeout);

            NamingEnumeration<SearchResult> results = context.search(userSearchBase, searchFilter, constraints);
            SearchResult result = null;

            try {
                if ((results != null) && results.hasMore()) {
                    result = results.next();

                    // Make sure only one entry exists for the requested user
                    if (results.hasMore()) {
                        log.warn("Multiple entries found for user: " + userId);
                        result = null;
                    }
                }
            } catch (PartialResultException e) {
                // Ignore partial result errors - most likely due to ActiveDirectory referrals
            }

            if (result != null) {
                userDn = result.getNameInNamespace();
                break;
            }

        } catch (NameNotFoundException e) {
            // Ignore and keep searching
        }
    }
    return userDn;
}