Java Code Examples for javax.naming.directory.SearchControls#setCountLimit()
The following examples show how to use
javax.naming.directory.SearchControls#setCountLimit() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LdapService.java From ctsms with GNU Lesser General Public License v2.1 | 6 votes |
public List<LdapEntryVO> search(final Integer limit, String... filterArgs) { SearchControls searchControls = new SearchControls(); Integer defaultLimit; if (limit != null) { if (limit >= 0) { searchControls.setCountLimit(limit); } else { searchControls.setCountLimit(0l); } } else if ((defaultLimit = Settings.getIntNullable(SettingCodes.LDAP_ENTRIES_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.LDAP_ENTRIES_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT)) != null) { if (defaultLimit >= 0) { searchControls.setCountLimit(defaultLimit); } else { searchControls.setCountLimit(0l); } } else { searchControls.setCountLimit(0l); } return ldapTemplate.search(getBase(), getSearchFilter(filterArgs), searchControls, getAttributeMapper()); }
Example 2
Source File: LdapTemplate.java From spring-ldap with Apache License 2.0 | 6 votes |
private SearchControls searchControlsForQuery(LdapQuery query, boolean returnObjFlag) { SearchControls searchControls = getDefaultSearchControls( defaultSearchScope, returnObjFlag, query.attributes()); if(query.searchScope() != null) { searchControls.setSearchScope(query.searchScope().getId()); } if(query.countLimit() != null) { searchControls.setCountLimit(query.countLimit()); } if(query.timeLimit() != null) { searchControls.setTimeLimit(query.timeLimit()); } return searchControls; }
Example 3
Source File: SearchFirstActiveDirectoryRealm.java From centraldogma with Apache License 2.0 | 5 votes |
/** * Finds a distinguished name(DN) of a user by querying the active directory LDAP context for the * specified username. * * @return the DN of the user, or {@code null} if there's no such user */ @Nullable protected String findUserDn(LdapContextFactory ldapContextFactory, String username) throws NamingException { LdapContext ctx = null; try { // Binds using the system username and password. ctx = ldapContextFactory.getSystemLdapContext(); final SearchControls ctrl = new SearchControls(); ctrl.setCountLimit(1); ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE); ctrl.setTimeLimit(searchTimeoutMillis); final String filter = searchFilter != null ? USERNAME_PLACEHOLDER.matcher(searchFilter) .replaceAll(username) : username; final NamingEnumeration<SearchResult> result = ctx.search(searchBase, filter, ctrl); try { if (!result.hasMore()) { return null; } return result.next().getNameInNamespace(); } finally { result.close(); } } finally { LdapUtils.closeContext(ctx); } }
Example 4
Source File: JNDIProviderImpl.java From ldapchai with GNU Lesser General Public License v2.1 | 5 votes |
private SearchControls makeSearchControls() { final SearchControls searchControls = new SearchControls(); searchControls.setReturningObjFlag( false ); searchControls.setReturningAttributes( new String[0] ); searchControls.setSearchScope( searchHelper.getSearchScope().getJndiScopeInt() ); final String[] returnAttributes = searchHelper.getAttributes() == null ? null : searchHelper.getAttributes().toArray( new String[searchHelper.getAttributes().size()] ); searchControls.setReturningAttributes( returnAttributes ); searchControls.setTimeLimit( searchHelper.getTimeLimit() ); searchControls.setCountLimit( searchHelper.getMaxResults() ); return searchControls; }
Example 5
Source File: ShiroAuthenticationService.java From zeppelin with Apache License 2.0 | 5 votes |
/** Function to extract users from LDAP. */ private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) { List<String> userList = new ArrayList<>(); String userDnTemplate = r.getUserDnTemplate(); String userDn[] = userDnTemplate.split(",", 2); String userDnPrefix = userDn[0].split("=")[0]; String userDnSuffix = userDn[1]; JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory(); try { LdapContext ctx = cf.getSystemLdapContext(); SearchControls constraints = new SearchControls(); constraints.setCountLimit(numUsersToFetch); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); String[] attrIDs = {userDnPrefix}; constraints.setReturningAttributes(attrIDs); NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints); while (result.hasMore()) { Attributes attrs = ((SearchResult) result.next()).getAttributes(); if (attrs.get(userDnPrefix) != null) { String currentUser = attrs.get(userDnPrefix).toString(); userList.add(currentUser.split(":")[1].trim()); } } } catch (Exception e) { LOGGER.error("Error retrieving User list from Ldap Realm", e); } LOGGER.info("UserList: " + userList); return userList; }
Example 6
Source File: ActiveDirectoryGroupRealm.java From zeppelin with Apache License 2.0 | 5 votes |
public List<String> searchForUserName(String containString, LdapContext ldapContext, int numUsersToFetch) throws NamingException { List<String> userNameList = new ArrayList<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(numUsersToFetch); String searchFilter = String.format("(&(objectClass=*)(%s=*%s*))", this.getUserSearchAttributeName(), containString); Object[] searchArguments = new Object[]{containString}; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]"); } Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().toLowerCase().equals(this.getUserSearchAttributeName().toLowerCase())) { userNameList.addAll(LdapUtils.getAllAttributeValues(attr)); } } } } return userNameList; }
Example 7
Source File: ReadOnlyLDAPUsersDAO.java From james-project with Apache License 2.0 | 5 votes |
/** * For a given name, this method makes ldap search in userBase with filter {@link LdapRepositoryConfiguration#userIdAttribute}=name * and objectClass={@link LdapRepositoryConfiguration#userObjectClass} and builds {@link User} based on search result. * * @param name * The userId which should be value of the field {@link LdapRepositoryConfiguration#userIdAttribute} * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the * userId of this user and ldap connection information with which * the user was searched. Return null if such a user was not found. * @throws NamingException * Propagated by the underlying LDAP communication layer. */ private ReadOnlyLDAPUser searchAndBuildUser(Username name) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[] { ldapConfiguration.getUserIdAttribute() }); sc.setCountLimit(1); String filterTemplate = "(&({0}={1})(objectClass={2})" + StringUtils.defaultString(ldapConfiguration.getFilter(), "") + ")"; String sanitizedFilter = FilterEncoder.format( filterTemplate, ldapConfiguration.getUserIdAttribute(), name.asString(), ldapConfiguration.getUserObjectClass()); NamingEnumeration<SearchResult> sr = ldapContext.search(ldapConfiguration.getUserBase(), sanitizedFilter, sc); if (!sr.hasMore()) { return null; } SearchResult r = sr.next(); Attribute userName = r.getAttributes().get(ldapConfiguration.getUserIdAttribute()); if (!ldapConfiguration.getRestriction().isActivated() || userInGroupsMembershipList(r.getNameInNamespace(), ldapConfiguration.getRestriction().getGroupMembershipLists(ldapContext))) { return new ReadOnlyLDAPUser(Username.of(userName.get().toString()), r.getNameInNamespace(), ldapContext); } return null; }
Example 8
Source File: LdapManager.java From CloverETL-Engine with GNU Lesser General Public License v2.1 | 5 votes |
/** * Method that calls the actual search on the jndi context. * * @param searchbase the domain name (relative to initial context in ldap) to search from. * @param filter the non-null filter to use for the search * @param scope the scope level of the search, one off "SearchControls.ONELEVEL_SCOPE * @param limit the maximum number of results to return * @param timeout the maximum time to wait before abandoning the search * @param returnAttributes an array of strings containing the names of attributes to search. (null = all, empty array = none) * @return * @throws NamingException */ public NamingEnumeration search(String searchbase, String filter, String[] returnAttributes, int scope, int limit, int timeout) throws NamingException { SearchControls constraints = new SearchControls(); if (SearchControls.ONELEVEL_SCOPE == scope) { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else if (SearchControls.SUBTREE_SCOPE == scope) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else if (SearchControls.OBJECT_SCOPE == scope) { constraints.setSearchScope(SearchControls.OBJECT_SCOPE); } else { throw new NamingException("Unknown search scope: " + scope); } if (returnAttributes != null && returnAttributes.length == 0) returnAttributes = new String[] { "objectClass" }; constraints.setCountLimit(limit); constraints.setTimeLimit(timeout); constraints.setReturningAttributes(returnAttributes); Name n = new CompositeName().add(searchbase); NamingEnumeration results = ctx.search(n, filter, constraints); return results; }
Example 9
Source File: LdapTemplate.java From spring-ldap with Apache License 2.0 | 5 votes |
private SearchControls getDefaultSearchControls(int searchScope, boolean returningObjFlag, String[] attrs) { SearchControls controls = new SearchControls(); controls.setSearchScope(searchScope); controls.setTimeLimit(defaultTimeLimit); controls.setCountLimit(defaultCountLimit); controls.setReturningObjFlag(returningObjFlag); controls.setReturningAttributes(attrs); return controls; }
Example 10
Source File: LdapTemplateTest.java From spring-ldap with Apache License 2.0 | 5 votes |
@Test public void verifyThatDefaultSearchControlParametersAreAutomaticallyAppliedInSearch() throws Exception { tested.setDefaultSearchScope(SearchControls.ONELEVEL_SCOPE); tested.setDefaultCountLimit(5000); tested.setDefaultTimeLimit(500); expectGetReadOnlyContext(); SearchControls controls = new SearchControls(); controls.setReturningObjFlag(false); controls.setCountLimit(5000); controls.setTimeLimit(500); controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); BasicAttributes expectedAttributes = new BasicAttributes(); SearchResult searchResult = new SearchResult("", null, expectedAttributes); singleSearchResult(controls, searchResult); Object expectedResult = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); List list = tested.search(nameMock, "(ou=somevalue)", attributesMapperMock); verify(namingEnumerationMock).close(); verify(dirContextMock).close(); assertThat(list).isNotNull(); assertThat(list).hasSize(1); assertThat(list.get(0)).isSameAs(expectedResult); }
Example 11
Source File: SimpleLDAPAuthenticationManagerImpl.java From qpid-broker-j with Apache License 2.0 | 4 votes |
private String getNameFromId(final String id, final Subject gssapiIdentity) throws NamingException { if (!isBindWithoutSearch()) { InitialDirContext ctx = createSearchInitialDirContext(gssapiIdentity); try { SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(new String[]{}); searchControls.setCountLimit(1L); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); LOGGER.debug("Searching for '{}'", id); NamingEnumeration<?> namingEnum = invokeContextOperationAs(gssapiIdentity, (PrivilegedExceptionAction<NamingEnumeration<?>>) () -> ctx.search( _searchContext, _searchFilter, new String[]{id}, searchControls)); if (namingEnum.hasMore()) { SearchResult result = (SearchResult) namingEnum.next(); String name = result.getNameInNamespace(); LOGGER.debug("Found '{}' DN '{}'", id, name); return name; } else { LOGGER.debug("Not found '{}'", id); return null; } } finally { closeSafely(ctx); } } else { return id; } }
Example 12
Source File: LdapAccessServiceBean.java From development with Apache License 2.0 | 4 votes |
private <T> List<T> searchByLimit(Properties properties, String baseDN, String filter, ILdapResultMapper<T> mapper, boolean checkAttribute, int searchLimit) throws NamingException { List<T> list = new ArrayList<T>(); NamingEnumeration<SearchResult> namingEnum = null; DirContext ctx = getDirContext(properties); SearchControls ctls = new SearchControls(); String[] attrIds = mapper.getAttributes(); ctls.setReturningAttributes(attrIds); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit(searchLimit); try { namingEnum = ctx.search(baseDN, escapeLDAPSearchFilter(filter), ctls); int count = 0; while (count++ < searchLimit && hasMoreEnum(namingEnum)) { SearchResult res = namingEnum.next(); Attributes ldapAttributes = res.getAttributes(); String[] values = new String[attrIds.length]; for (int i = 0; i < values.length; i++) { Attribute ldapAttr = ldapAttributes .get(escapeLDAPSearchFilter(attrIds[i])); if (checkAttribute && ldapAttr == null) { NamingException e = new NamingException( "Unknown LDAP attribute " + attrIds[i]); throw e; } if (ldapAttr != null && ldapAttr.get() != null) { values[i] = ldapAttr.get().toString(); } } T t = mapper.map(values); if (t != null) { list.add(t); } } } finally { if (namingEnum != null) { try { namingEnum.close(); } finally { closeContext(ctx); } } closeContext(ctx); } return list; }
Example 13
Source File: ShiroAuthenticationService.java From zeppelin with Apache License 2.0 | 4 votes |
/** 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 { 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; }
Example 14
Source File: LdapConnection.java From scriptella-etl with Apache License 2.0 | 4 votes |
/** * Creates a connnection to a directory. * * @param parameters parameters to establish connection. */ public LdapConnection(ConnectionParameters parameters) { super(Driver.DIALECT, parameters); Hashtable<String, Object> env = new Hashtable<String, Object>(); //Put default settings env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //Put connection settings if (parameters.getUrl() == null) { throw new LdapProviderException("Connection URL is required"); } env.put(Context.PROVIDER_URL, parameters.getUrl()); if (parameters.getUser() != null) { env.put(Context.SECURITY_PRINCIPAL, parameters.getUser()); } if (parameters.getPassword() != null) { env.put(Context.SECURITY_CREDENTIALS, parameters.getPassword()); } //Override env with user specified connection properties env.putAll(parameters.getProperties()); //Set the search controls used for queries searchControls = new SearchControls(); String scope = parameters.getStringProperty(SEARCH_SCOPE_KEY); if (scope != null) { if ("object".equalsIgnoreCase(scope)) { searchControls.setSearchScope(SearchControls.OBJECT_SCOPE); } else if ("onelevel".equalsIgnoreCase(scope)) { searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else if ("subtree".equalsIgnoreCase(scope)) { searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { throw new LdapProviderException("Unsupported " + SEARCH_SCOPE_KEY + "=" + scope); } } String baseDn = parameters.getStringProperty(SEARCH_BASEDN_KEY); this.baseDn = baseDn == null ? "" : baseDn; Integer tl = parameters.getIntegerProperty(SEARCH_TIMELIMIT_KEY); if (tl != null) { searchControls.setTimeLimit(tl); } Integer cl = parameters.getIntegerProperty(SEARCH_COUNTLIMIT_KEY); if (cl != null) { searchControls.setCountLimit(cl); } Number mfl = parameters.getNumberProperty(FILE_MAXLENGTH_KEY, null); maxFileLength = mfl == null ? null : mfl.longValue(); driverContext = parameters.getContext(); initializeContext(env); //Initializing context }
Example 15
Source File: LdapPrincipalDaoImpl.java From rice with Educational Community License v2.0 | 4 votes |
protected SearchControls getSearchControls() { SearchControls retval = new SearchControls(); retval.setCountLimit(getSearchResultsLimit(PersonImpl.class).longValue()); retval.setSearchScope(SearchControls.SUBTREE_SCOPE); return retval; }