List of usage examples for javax.naming.directory SearchControls setReturningAttributes
public void setReturningAttributes(String[] attrs)
From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java
/** * Note that {@link User.getPassword()} will not give the password from the repository after 'unmarshalling'. * The user repository must be queried for this because the password is never retrieved from the repository * and the User object does not contain it. * /*from w w w . ja v a 2s . co m*/ */ public boolean isPasswordStored(String userId) throws RepositoryException { if (StringUtils.isBlank(userId)) { logger.debug("Insufficient data for getting user info."); throw new IllegalArgumentException(); } String filter = "(&(objectClass=" + getObjectClassName() + ")(uid=" + userId + "))"; final String PASSWD_ATTR_NAME = "userPassword"; boolean passwordStored = false; SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ctls.setCountLimit(1); ctls.setReturningAttributes(new String[] { "uid", PASSWD_ATTR_NAME }); try { NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls); while (resultEnum.hasMoreElements()) { SearchResult result = resultEnum.next(); Attributes attrs = result.getAttributes(); if (attrs.get(PASSWD_ATTR_NAME) != null) passwordStored = true; } } catch (NamingException e) { throw new RepositoryException(e); } return passwordStored; }
From source file:nl.knaw.dans.common.ldap.repo.AbstractLdapUserRepo.java
/** * {@inheritDoc}/*from w w w .j av a2 s . co m*/ */ public Map<String, String> findByCommonNameStub(String stub, long maxCount) throws RepositoryException { Map<String, String> idNameMap = new LinkedHashMap<String, String>(); String text = censorHumanoidSearchPhrase(stub); String filter = "(&(objectClass=" + getObjectClassName() + ")(cn=" + text + "*))"; SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE); ctls.setCountLimit(maxCount); ctls.setReturningAttributes(new String[] { "cn", "uid" }); try { NamingEnumeration<SearchResult> resultEnum = getClient().search(getContext(), filter, ctls); while (resultEnum.hasMoreElements()) { SearchResult result = resultEnum.next(); Attributes attrs = result.getAttributes(); idNameMap.put((String) attrs.get("uid").get(), (String) attrs.get("cn").get()); } } catch (NamingException e) { throw new RepositoryException(e); } return idNameMap; }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/*w w w . j av a 2s .c o m*/ SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { logger.debug("error when closing ldap context", e); } } } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * //from ww w .jav a 2 s . c o m * @param callback * the callback * @param searchBase * the base DN for the search * @param query * the query * @param returningAttributes * the attributes to include in search results * @throws AlfrescoRuntimeException */ private void processQuery(SearchCallback callback, String searchBase, String query, String[] returningAttributes) { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(returningAttributes); if (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Processing query"); LDAPUserRegistry.logger.debug("Search base: " + searchBase); LDAPUserRegistry.logger.debug(" Return result limit: " + searchControls.getCountLimit()); LDAPUserRegistry.logger.debug(" DerefLink: " + searchControls.getDerefLinkFlag()); LDAPUserRegistry.logger.debug(" Return named object: " + searchControls.getReturningObjFlag()); LDAPUserRegistry.logger.debug(" Time limit for search: " + searchControls.getTimeLimit()); LDAPUserRegistry.logger.debug(" Attributes to return: " + returningAttributes.length + " items."); for (String ra : returningAttributes) { LDAPUserRegistry.logger.debug(" Attribute: " + ra); } } InitialDirContext ctx = null; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize); do { searchResults = ctx.search(searchBase, query, searchControls); while (searchResults.hasMore()) { result = searchResults.next(); callback.process(result); // Close the contexts, see ALF-20682 Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } result = null; } } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize)); } catch (NamingException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } catch (ParseException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } finally { if (result != null) { try { Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } searchResults = null; } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } try { callback.close(); } catch (NamingException e) { } } }
From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java
/** * Helper method to create the SearchControls instance * * @return the relevant SearchControls// w w w .j av a 2s . co m */ protected SearchControls createSearchControls() { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE); searchControls.setReturningAttributes(new String[] { "cn" }); return searchControls; }
From source file:org.apache.cloudstack.ldap.ADLdapUserManagerImpl.java
@Override public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException { if (StringUtils.isBlank(groupName)) { throw new IllegalArgumentException("ldap group name cannot be blank"); }/*from w ww. j a v a 2 s .com*/ String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); } final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); NamingEnumeration<SearchResult> results = context.search(basedn, generateADGroupSearchFilter(groupName), searchControls); final List<LdapUser> users = new ArrayList<LdapUser>(); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); users.add(createUser(result)); } return users; }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException { String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute(); final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(new String[] { attributeName }); NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls); final List<LdapUser> users = new ArrayList<LdapUser>(); //Expecting only one result which has all the users if (result.hasMoreElements()) { Attribute attribute = result.nextElement().getAttributes().get(attributeName); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMoreElements()) { String userdn = String.valueOf(values.nextElement()); try { users.add(getUserForDn(userdn, context)); } catch (NamingException e) { s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); }//w ww. j ava2 s . com } } Collections.sort(users); return users; }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
private LdapUser getUserForDn(String userdn, LdapContext context) throws NamingException { final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); NamingEnumeration<SearchResult> result = context.search(userdn, "(objectClass=" + _ldapConfiguration.getUserObject() + ")", controls); if (result.hasMoreElements()) { return createUser(result.nextElement()); } else {/* ww w . j av a 2 s . com*/ throw new NamingException("No user found for dn " + userdn); } }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(_ldapConfiguration.getScope()); searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes()); String basedn = _ldapConfiguration.getBaseDn(); if (StringUtils.isBlank(basedn)) { throw new IllegalArgumentException("ldap basedn is not configured"); }//from w ww . j a v a2s. c o m byte[] cookie = null; int pageSize = _ldapConfiguration.getLdapPageSize(); context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); final List<LdapUser> users = new ArrayList<LdapUser>(); NamingEnumeration<SearchResult> results; do { results = context.search(basedn, generateSearchFilter(username), searchControls); while (results.hasMoreElements()) { final SearchResult result = results.nextElement(); users.add(createUser(result)); } Control[] contextControls = context.getResponseControls(); if (contextControls != null) { for (Control control : contextControls) { if (control instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) control; cookie = prrc.getCookie(); } } } else { s_logger.info("No controls were sent from the ldap server"); } context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); return users; }
From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java
@Override public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException { String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute(); final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(new String[] { attributeName }); NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls); final List<LdapUser> users = new ArrayList<LdapUser>(); //Expecting only one result which has all the users if (result.hasMoreElements()) { Attribute attribute = result.nextElement().getAttributes().get(attributeName); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMoreElements()) { String userdn = String.valueOf(values.nextElement()); try { users.add(getUserForDn(userdn, context)); } catch (NamingException e) { s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); }/*from www. ja v a 2 s . com*/ } } Collections.sort(users); return users; }