List of usage examples for javax.naming.directory SearchControls setCountLimit
public void setCountLimit(long limit)
From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java
/** Function to extract users from Zeppelin LdapRealm. */ private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) { List<String> userList = new ArrayList<>(); LOGGER.debug("SearchText: " + searchText); String userAttribute = r.getUserSearchAttributeName(); String userSearchRealm = r.getUserSearchBase(); String userObjectClass = r.getUserObjectClass(); JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory(); try {//w w w. java2s. co m LdapContext ctx = cf.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); constraints.setCountLimit(numUsersToFetch); String[] attrIDs = { userAttribute }; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userSearchRealm, "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userAttribute) != null) { String currentUser; if (r.getUserLowerCase()) { LOGGER.debug("userLowerCase true"); currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase(); } else { LOGGER.debug("userLowerCase false"); currentUser = (String) attrs.get(userAttribute).get(); } LOGGER.debug("CurrentUser: " + currentUser); userList.add(currentUser.trim()); } } } catch (Exception e) { LOGGER.error("Error retrieving User list from Ldap Realm", e); } return userList; }
From source file:org.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java
public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException { PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s; if (!config.getBoolean("ldap.bind.authenticator.enabled") || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false) && StringUtils.isEmpty(source.getPassword()))) { return new AuthenticationResult(false, source.getPrincipal(), null); }/* w w w. ja va 2s . com*/ SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setDerefLinkFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")" + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute() + "=" + source.getPrincipal() + "))"; log.info("Searching for users with filter: \'{}\'" + " from base dn: {}", filter, mapper.getUserBaseDn()); LdapConnection ldapConnection = getLdapConnection(); LdapConnection authLdapConnection = null; NamingEnumeration<SearchResult> results = null; try { // check the cache for user's userDn in the ldap server String userDn = ldapCacheService.getLdapUserDn(source.getPrincipal()); if (userDn == null) { log.debug("userDn for user {} not found in cache. Retrieving from ldap server..", source.getPrincipal()); DirContext context = ldapConnection.getDirContext(); results = context.search(mapper.getUserBaseDn(), filter, ctls); log.info("Found user?: {}", results.hasMoreElements()); if (results.hasMoreElements()) { SearchResult result = results.nextElement(); userDn = result.getNameInNamespace(); log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getPrincipal()); // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server ldapCacheService.addLdapUserDn(source.getPrincipal(), userDn); } else { return new AuthenticationResult(false, source.getPrincipal(), null); } } log.info("Attempting Authenication: + {}", userDn); authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword()); return new AuthenticationResult(true, source.getPrincipal(), null); } catch (LdapException e) { return new AuthenticationResult(false, source.getPrincipal(), e); } catch (NamingException e) { return new AuthenticationResult(false, source.getPrincipal(), e); } finally { closeNamingEnumeration(results); closeLdapConnection(ldapConnection); if (authLdapConnection != null) { closeLdapConnection(authLdapConnection); } } }
From source file:org.eurekastreams.server.persistence.mappers.ldap.LdapLookup.java
/** * Execute an ldap query based on {@link LdapLookupRequest} parameters and this DAO's configuration. * LdapLookupRequest is used for search upper bound, the {@link LdapTemplate}, and the search string. The rest of * ldap query functionality is determined by DAO configuration. * /*w w w. j a v a 2 s. c o m*/ * @param inRequest * {@link LdapLookupRequest}. * @return List of objects found as as result of ldap query. * */ @Override public List<Type> execute(final LdapLookupRequest inRequest) { // get ldap template. LdapTemplate template = ldapTemplateRetriever.getLdapTemplate(inRequest); // set up search controls. SearchControls searchControls = new SearchControls(); searchControls.setCountLimit(inRequest.getSearchUpperBound()); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // add passed in attribute criteria to filter. AbstractFilter abstractFilter = filterCreator.getFilter(inRequest.getQueryString()); // get the configured CollectingNameClassPairCallbackHandler to use for query. CollectingNameClassPairCallbackHandler collectingHandler = handlerFactory.getCallbackHandler(); // execute query. ldapSearchStrategy.searchLdap(template, abstractFilter.encode(), searchControls, collectingHandler); // get results gathered by CollectingNameClassPairCallbackHandler. List<Type> rawResults = collectingHandler.getList(); // Results contain nulls if the context/attribute mappers were unable to create objects, so pull them out. List<Type> results = new ArrayList<Type>(); for (Type t : rawResults) { if (t != null) { results.add(t); } } return results; }
From source file:org.kuali.rice.kim.dao.impl.LdapPrincipalDaoImpl.java
protected SearchControls getSearchControls() { SearchControls retval = new SearchControls(); retval.setCountLimit(getSearchResultsLimit(PersonImpl.class).longValue()); retval.setSearchScope(SearchControls.SUBTREE_SCOPE); return retval; }
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 w w w .j ava2 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.olat.ldap.LDAPLoginManagerImpl.java
private void searchInLdap(final LdapVisitor visitor, final String filter, final String[] returningAttrs, final LdapContext ctx) { final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(returningAttrs); ctls.setCountLimit(0); // set no limits final boolean paging = isPagedResultControlSupported(ctx); for (final String ldapBase : LDAPLoginModule.getLdapBases()) { int counter = 0; try {//from w w w.j a va2 s . com if (paging) { byte[] cookie = null; ctx.setRequestControls( new Control[] { new PagedResultsControl(PAGE_SIZE, Control.NONCRITICAL) }); do { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } cookie = getCookie(ctx); } while (cookie != null); } else { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { visitor.visit(enm.next()); } counter++; } } catch (final SizeLimitExceededException e) { logError("SizeLimitExceededException after " + counter + " records when getting all users from LDAP, reconfigure your LDAP server, hints: http://www.ldapbrowser.com/forum/viewtopic.php?t=14", null); } catch (final NamingException e) { logError("NamingException when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } catch (final Exception e) { logError("Exception when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase + " on row::" + counter, e); } } }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int) *//*from ww w .j av a 2 s . 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.sipfoundry.sipxconfig.bulk.ldap.LdapImportManagerImpl.java
private void runSearch(NameClassPairCallbackHandler handler, long limit, int connectionId) { SearchControls sc = new SearchControls(); sc.setCountLimit(limit); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); AttrMap attrMap = m_ldapManager.getAttrMap(connectionId); if (!attrMap.verified()) { m_ldapManager.verify(m_ldapManager.getConnectionParams(connectionId), attrMap); }/*w ww .java 2s . c o m*/ sc.setReturningAttributes(attrMap.getLdapAttributesArray()); String base = attrMap.getSearchBase(); String filter = attrMap.getSearchFilter(); LdapTemplate template = m_templateFactory.getLdapTemplate(m_ldapManager.getConnectionParams(connectionId)); try { template.search(base, filter, sc, handler, LdapManager.NULL_PROCESSOR); } catch (Exception e) { if (e instanceof SearchLimitExceededException) { // See http://forum.springframework.org/archive/index.php/t-27836.html LOG.info("Normal overflow, requesting to preview more records then exist"); } else { LOG.error("LDAP search failed", e); throw new UserException("LDAP search failed : " + e.getCause().getMessage()); } } }
From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java
public Schema getSchema(String subschemaSubentry, LdapConnectionParams params) { try {// w w w . j ava2 s .c om SearchControls cons = new SearchControls(); // only interested in the first result cons.setCountLimit(1); // set time limit for this search to 30 sec, should be sufficient even for large LDAPs cons.setTimeLimit(30000); SchemaMapper mapper = new SchemaMapper(); cons.setReturningAttributes(mapper.getReturningAttributes()); cons.setSearchScope(SearchControls.OBJECT_SCOPE); Schema schema = (Schema) m_templateFactory.getLdapTemplate(params).search(subschemaSubentry, LdapManager.FILTER_ALL_CLASSES, cons, new SchemaMapper(), LdapManager.NULL_PROCESSOR).get(0); return schema; } catch (DataIntegrityViolationException e) { LOG.debug("Retrieving schema failed.", e); throw new UserException("searchSchema.violation.error"); } catch (UncategorizedLdapException e) { LOG.debug("Retrieving schema failed. Anonymous-binding may be disabled", e); throw new UserException("searchSchema.anonymousBinding.error"); } }
From source file:org.tolven.gatekeeper.bean.LdapBean.java
private List<TolvenPerson> findTolvenPerson(LdapContext ctx, String peopleBaseName, String principalLdapName, String realm, int maxResults, int timeLimit) { NamingEnumeration<SearchResult> namingEnum = null; SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit(maxResults); ctls.setTimeLimit(timeLimit);/*www . ja v a2 s . c o m*/ ArrayList<TolvenPerson> searchResults = new ArrayList<TolvenPerson>(10); try { namingEnum = ctx.search(peopleBaseName, principalLdapName, ctls); while (namingEnum.hasMore()) { SearchResult rslt = namingEnum.next(); searchResults.add(new TolvenPerson(rslt)); } } catch (GatekeeperSecurityException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException( "Could not search for TolvenPerson: " + principalLdapName + " in realm: " + realm + ": ", ex); } return searchResults; }