List of usage examples for javax.naming.directory SearchControls setReturningAttributes
public void setReturningAttributes(String[] attrs)
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
/** * Find the user dn with its uid//from w w w . ja va 2s .c o m * * @param uid * @param ctx * @return user's dn */ private String searchUserDN(final String uid, final DirContext ctx) { if (ctx == null) { return null; } final List<String> ldapBases = LDAPLoginModule.getLdapBases(); final String objctClass = LDAPLoginModule.getLdapUserObjectClass(); final String[] serachAttr = { "dn" }; final String ldapUserIDAttribute = LDAPLoginModule .mapOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER); final String filter = "(&(objectClass=" + objctClass + ")(" + ldapUserIDAttribute + "=" + uid + "))"; final SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(serachAttr); String userDN = null; for (final String ldapBase : ldapBases) { try { final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls); while (enm.hasMore()) { final SearchResult result = enm.next(); userDN = result.getNameInNamespace(); } if (userDN != null) { break; } } catch (final NamingException e) { logError("NamingException when trying to bind user with username::" + uid + " on ldapBase::" + ldapBase, e); } } return userDN; }
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 ww . jav a 2s . co m*/ 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.olat.ldap.LDAPLoginManagerImpl.java
private boolean isPagedResultControlSupported(final LdapContext ctx) { try {//from w ww. ja v a 2s .c o m final SearchControls ctl = new SearchControls(); ctl.setReturningAttributes(new String[] { "supportedControl" }); ctl.setSearchScope(SearchControls.OBJECT_SCOPE); /* search for the rootDSE object */ final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl); while (results.hasMore()) { final SearchResult entry = results.next(); final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll(); while (attrs.hasMore()) { final Attribute attr = attrs.next(); final NamingEnumeration<?> vals = attr.getAll(); while (vals.hasMore()) { final String value = (String) vals.next(); if (value.equals(PAGED_RESULT_CONTROL_OID)) { return true; } } } } return false; } catch (final Exception e) { logError("Exception when trying to know if the server support paged results.", e); return false; } }
From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java
private NamingEnumeration search(ManagedSystemObjectMatch matchObj, LdapContext ctx, String searchValue, String[] attrAry) throws NamingException { SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(attrAry); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = matchObj.getSearchFilter(); // replace the place holder in the search filter searchFilter = searchFilter.replace("?", searchValue); System.out.println("Search Filter=" + searchFilter); System.out.println("BaseDN=" + matchObj.getBaseDn()); return ctx.search(matchObj.getSearchBaseDn(), searchFilter, searchCtls); }
From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java
/** * @see org.opentravel.schemacompiler.security.AuthenticationProvider#searchCandidateUsers(java.lang.String, int) */// w w w . j a v 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.orbeon.oxf.processor.LDAPProcessor.java
private List search(DirContext ctx, String rootDN, String scope, String filter, String[] attributes) { try {/*from w ww. ja v a 2 s. c om*/ List listResults = new ArrayList(); SearchControls constraints = new SearchControls(); constraints.setSearchScope(convertSearchScope(scope)); constraints.setReturningAttributes(attributes); try { if (scope != null && scope.toUpperCase().equals("ALLLEVELS")) { String[] levels = rootDN.split(","); for (int i = 0; i < levels.length; i++) { String[] currentLevels = new String[levels.length - i]; System.arraycopy(levels, i, currentLevels, 0, levels.length - i); String levelRootDN = StringUtils.join(currentLevels, ","); if (logger.isDebugEnabled()) logger.debug("LDAP Search on level " + levelRootDN); NamingEnumeration results = ctx.search(levelRootDN, filter, constraints); for (; results.hasMore();) { SearchResult result = (SearchResult) results.next(); listResults.add(result); } } } else { NamingEnumeration results = ctx.search(rootDN, filter, constraints); for (; results.hasMore();) { SearchResult result = (SearchResult) results.next(); listResults.add(result); } } } catch (NameNotFoundException e) { // for example in case of ALLLEVELS scope, if the LDAP database suffix has more than one component, the last iteration would result in NameNotFoundException } return listResults; } catch (NamingException e) { throw new OXFException("LDAP Search Failed", e); } }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Find a user by ID. This id may be a compound ID, like the * LDAP database's DN structure. Otherwise it might be an empoyeeNumber * like this implementation use./*from w ww . ja v a 2s . c o m*/ * <p/> * Tries first to get the user by pegadiID, which is the old method. * * @param id * @return the Userobject if found, or null if not. */ public Person getUserById(String id) { if (id == null || id.equals(0)) return null; Person user = null; String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; try { //int nr = Integer.parseInt(id); //only needed if we can get the dn. SearchControls sc = new SearchControls(); sc.setReturningAttributes(getThese); NamingEnumeration e = ctx.search("ou=people", "employeeNumber=" + id, sc); if (e.hasMore()) { SearchResult sr = (SearchResult) e.next(); user = this.createUser(sr.getAttributes()); } } catch (NamingException e) { log.error("An error occured while trying to getUserById(" + id + ")", e); /*FIXME does not work. * try { Attributes attrs = ctx.getAttributes("dn=" + id,getThese); return createUser(attrs); } catch (NamingException e) { e.printStackTrace(); }*/ } return user; }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Returns an array of users.//from w ww . j a va 2 s. c om * * @param inactive <code>true</code> if inactive users should be included. * @return an array of <code>User</code>s. */ public List<Person> getAllUsers(boolean inactive) { ArrayList<Person> users = new ArrayList<Person>(); try { SearchControls sc = new SearchControls(); String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; sc.setReturningAttributes(getThese); if (inactive) { Attributes attrs = ctx.getAttributes("ou=people", getThese); users.add(this.createUser(attrs)); } else { NamingEnumeration e = ctx.search("ou=people", "(active=1)", sc); while (e.hasMore()) { SearchResult sr = (SearchResult) e.next(); users.add(this.createUser(sr.getAttributes())); } } Collections.sort(users); return users; } catch (NamingException er) { log.error("Could not get users", er); } catch (Exception e) { log.error("Something else", e); } return null; }
From source file:org.pegadi.server.user.LDAPUserServerImpl.java
/** * Returns an array of users having a given role. Either active or * inactive users are returned.//from w ww. jav a 2s. c o m * * @param roleID the role of the users. * @param active specifying whether we want the active or inactive users. * @return an array of <code>User</code>s. */ public List<Person> getUsersByRole(int roleID, int active) { if (roleID <= 0) return null; ArrayList<Person> users = new ArrayList<Person>(); try { SearchControls sc = new SearchControls(); String[] getThese = { "sn", "gn", "mail", "uid", "employeeNumber" }; sc.setReturningAttributes(getThese); NamingEnumeration e = ctx.search("ou=people", "(&(active=" + active + ")(pegadiRole=" + roleID + "*))", sc); while (e.hasMore()) { SearchResult sr = (SearchResult) e.next(); users.add(this.createUser(sr.getAttributes())); } Collections.sort(users); return users; } catch (NamingException er) { log.error("Error, getUsersByRole(" + roleID + "," + active + ")", er); } return null; }
From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java
/** * Search for all users starting at <code>ou=groups</code>, looking for objects with * <code>objectClass=groupOfUniqueNames</code>, and extracting the <code>uid</code> token of the * <code>uniqueMember</code> attribute. *///from w w w .j a v a 2s . c om @Test public void testGetAllUserNames1() throws Exception { SearchControls con1 = new SearchControls(); con1.setReturningAttributes(new String[] { "uniqueMember" }); //$NON-NLS-1$ LdapSearchParamsFactoryImpl paramFactory = new LdapSearchParamsFactoryImpl("ou=groups", //$NON-NLS-1$ "(objectClass=groupOfUniqueNames)", con1); //$NON-NLS-1$ paramFactory.afterPropertiesSet(); Transformer transformer1 = new SearchResultToAttrValueList("uniqueMember", "uid"); //$NON-NLS-1$ //$NON-NLS-2$ GenericLdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1); allUsernamesSearch.afterPropertiesSet(); DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService(); userRoleListService.setAllUsernamesSearch(allUsernamesSearch); List res = userRoleListService.getAllUsers(); assertTrue(res.contains("pat")); //$NON-NLS-1$ assertTrue(res.contains("admin")); //$NON-NLS-1$ if (logger.isDebugEnabled()) { logger.debug("results of getAllUserNames1(): " + res); //$NON-NLS-1$ } }