List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Retrieve the elements referenced by the filter/BaseDN/Scope request. * * @param attributes Attributes of the referencer element * @param directoryDn Dn of the Directory * @param linkDn Dn specified in the parent * @param filter Filter expression specified in the parent * @param scope scope for the search/* w w w. j a va 2 s. com*/ * @return The list of the referenced elements. * @throws DirectoryException * @throws NamingException */ private Set<String> getReferencedElements(Attributes attributes, String directoryDn, String linkDn, String filter, int scope) throws DirectoryException, NamingException { Set<String> targetIds = new TreeSet<>(); LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor(); LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); // use the most specific scope between the one specified in the // Directory and the specified in the Parent String dn = directoryDn.endsWith(linkDn) && directoryDn.length() > linkDn.length() ? directoryDn : linkDn; // combine the ldapUrl search query with target // directory own constraints SearchControls scts = new SearchControls(); // use the most specific scope scts.setSearchScope(Math.min(scope, targetDirconfig.getSearchScope())); // only fetch the ids of the targets scts.setReturningAttributes(new String[] { targetSession.idAttribute }); // combine the filter of the target directory with the // provided filter if any String targetFilter = targetDirconfig.getSearchFilter(); if (filter == null || filter.length() == 0) { filter = targetFilter; } else if (targetFilter != null && targetFilter.length() > 0) { filter = String.format("(&(%s)(%s))", targetFilter, filter); } // perform the request and collect the ids if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getLdapTargetIds(%s): LDAP search dn='%s' " + " filter='%s' scope='%s' [%s]", attributes, dn, dn, scts.getSearchScope(), this)); } Name name = new CompositeName().add(dn); NamingEnumeration<SearchResult> results = targetSession.dirContext.search(name, filter, scts); try { while (results.hasMore()) { // NXP-2461: check that id field is filled Attribute attr = results.next().getAttributes().get(targetSession.idAttribute); if (attr != null) { String collectedId = attr.get().toString(); if (collectedId != null) { targetIds.add(collectedId); } } } } finally { results.close(); } return targetIds; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doDeleteUserClaimValues(String userName, String[] claims, String profileName) throws UserStoreException { // get the LDAP Directory context DirContext dirContext = this.connectionSource.getContext(); DirContext subDirContext = null; // search the relevant user entry by user name String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER); userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName)); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(null); NamingEnumeration<SearchResult> returnedResultList = null; String returnedUserEntry = null; try {//from ww w . j a v a 2 s . co m returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter, searchControls); // assume only one user is returned from the search // TODO:what if more than one user is returned if (returnedResultList.hasMore()) { returnedUserEntry = returnedResultList.next().getName(); } } catch (NamingException e) { String errorMessage = "Results could not be retrieved from the directory context for user : " + userName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(returnedResultList); } try { Attributes updatedAttributes = new BasicAttributes(true); // if there is no attribute for profile configuration in LDAP, skip // updating it. // get the claimMapping related to this claimURI for (String claimURI : claims) { String attributeName = getClaimAtrribute(claimURI, userName, null); Attribute currentUpdatedAttribute = new BasicAttribute(attributeName); updatedAttributes.put(currentUpdatedAttribute); } subDirContext = (DirContext) dirContext.lookup(userSearchBase); subDirContext.modifyAttributes(returnedUserEntry, DirContext.REMOVE_ATTRIBUTE, updatedAttributes); } catch (Exception e) { handleException(e, userName); } finally { JNDIUtil.closeContext(subDirContext); JNDIUtil.closeContext(dirContext); } }
From source file:org.springframework.ldap.core.LdapTemplate.java
private SearchControls getDefaultSearchControls(int searchScope, boolean returningObjFlag, String[] attrs) { SearchControls controls = new SearchControls(); controls.setSearchScope(searchScope); controls.setReturningObjFlag(returningObjFlag); controls.setReturningAttributes(attrs); return controls; }
From source file:org.lsc.jndi.JndiServices.java
/** * Retrieve a specific attribute from an object * /*from ww w.j av a 2 s . com*/ * @param objectDn * @param attribute * @return * @throws LscServiceException */ public List<String> getAttributeValues(String objectDn, String attribute) throws LscServiceException { List<String> values = null; try { // Setup search SearchControls sc = new SearchControls(); sc.setDerefLinkFlag(false); sc.setReturningAttributes(new String[] { attribute }); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningObjFlag(true); // Retrieve attribute values SearchResult res = getEntry(objectDn, "objectClass=*", sc, SearchControls.OBJECT_SCOPE); Attribute attr = res.getAttributes().get(attribute); if (attr != null) { values = new ArrayList<String>(); NamingEnumeration<?> enu = attr.getAll(); while (enu.hasMoreElements()) { Object val = enu.next(); values.add(val.toString()); } } } catch (NamingException e) { throw new LscServiceException(e); } return values; }
From source file:org.lsc.jndi.JndiServices.java
public Map<String, LscDatasets> doGetAttrsList(final String base, final String filter, final int scope, final List<String> attrsNames) throws NamingException { // sanity checks String searchBase = base == null ? "" : rewriteBase(base); String searchFilter = filter == null ? DEFAULT_FILTER : filter; Map<String, LscDatasets> res = new LinkedHashMap<String, LscDatasets>(); if (attrsNames == null || attrsNames.size() == 0) { LOGGER.error("No attribute names to read! Check configuration."); return res; }//from w ww .j a v a 2 s . c o m String[] attributes = new String[attrsNames.size()]; attributes = attrsNames.toArray(attributes); SearchControls constraints = new SearchControls(); constraints.setDerefLinkFlag(false); constraints.setReturningAttributes(attributes); constraints.setSearchScope(scope); constraints.setReturningObjFlag(true); try { boolean requestPagedResults = false; List<Control> extControls = new ArrayList<Control>(); if (pageSize > 0) { requestPagedResults = true; LOGGER.debug("Using pagedResults control for {} entries at a time", pageSize); } if (requestPagedResults) { extControls.add(new PagedResultsControl(pageSize, Control.CRITICAL)); } if (sortedBy != null) { extControls.add(new SortControl(sortedBy, Control.CRITICAL)); } if (extControls.size() > 0) { ctx.setRequestControls(extControls.toArray(new Control[extControls.size()])); } byte[] pagedResultsResponse = null; do { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, constraints); if (results != null) { Map<String, Object> attrsValues = null; while (results.hasMoreElements()) { attrsValues = new HashMap<String, Object>(); SearchResult ldapResult = (SearchResult) results.next(); // get the value for each attribute requested for (String attributeName : attrsNames) { Attribute attr = ldapResult.getAttributes().get(attributeName); if (attr != null && attr.get() != null) { attrsValues.put(attributeName, attr.get()); } } res.put(ldapResult.getNameInNamespace(), new LscDatasets(attrsValues)); } } Control[] respCtls = ctx.getResponseControls(); if (respCtls != null) { for (Control respCtl : respCtls) { if (requestPagedResults && respCtl instanceof PagedResultsResponseControl) { pagedResultsResponse = ((PagedResultsResponseControl) respCtl).getCookie(); } } } if (requestPagedResults && pagedResultsResponse != null) { ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, pagedResultsResponse, Control.CRITICAL) }); } } while (pagedResultsResponse != null); // clear requestControls for future use of the JNDI context if (requestPagedResults) { ctx.setRequestControls(null); } } catch (CommunicationException e) { // Avoid handling the communication exception as a generic one throw e; } catch (ServiceUnavailableException e) { // Avoid handling the service unavailable exception as a generic one throw e; } catch (NamingException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } catch (IOException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } return res; }
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. j a va 2s .c om * @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.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
/** * @param searchFilter// w ww . j a v a2 s .c om * @param returnedAtts * @param dirContext * @return * @throws UserStoreException */ protected NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts, DirContext dirContext) throws UserStoreException { SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBases = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); if (returnedAtts != null && returnedAtts.length > 0) { searchCtls.setReturningAttributes(returnedAtts); } if (log.isDebugEnabled()) { try { log.debug("Searching for user with SearchFilter: " + searchFilter + " in SearchBase: " + dirContext.getNameInNamespace()); } catch (NamingException e) { log.debug("Error while getting DN of search base", e); } if (returnedAtts == null) { log.debug("No attributes requested"); } else { for (String attribute : returnedAtts) { log.debug("Requesting attribute :" + attribute); } } } String[] searchBaseAraay = searchBases.split("#"); NamingEnumeration<SearchResult> answer = null; try { for (String searchBase : searchBaseAraay) { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMore()) { return answer; } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while search user for filter : " + searchFilter; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } return answer; }
From source file:com.aurel.track.util.LdapUtil.java
static TPersonBean getLdapUser(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String searchStr) throws Exception { LdapContext ctx = null;/*from w ww . jav a 2s. c o m*/ try { ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { LOGGER.warn("The context is null"); } // Control the search SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Don't ask for more than we can handle anyways if (ldapMap == null || ldapMap.isEmpty()) { LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!"); return null; } String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME); String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME); String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL); String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE); NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); return getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); } } catch (NamingException e) { LOGGER.warn( "Searching from " + providerUrl + " by filter " + searchStr + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } finally { if (ctx != null) { ctx.close(); } } return null; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * * @param callback//from w ww.j a v a 2s .c o m * the callback * @param searchBase * the base DN for the search * @param query * the query * @param returningAttributes * the attributes to include in search results * @throws org.alfresco.error.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 (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger.debug("Processing query"); LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase); LDAPMultiBaseUserRegistry.logger.debug(" Return result limit: " + searchControls.getCountLimit()); LDAPMultiBaseUserRegistry.logger.debug(" DerefLink: " + searchControls.getDerefLinkFlag()); LDAPMultiBaseUserRegistry.logger .debug(" Return named object: " + searchControls.getReturningObjFlag()); LDAPMultiBaseUserRegistry.logger.debug(" Time limit for search: " + searchControls.getTimeLimit()); LDAPMultiBaseUserRegistry.logger .debug(" Attributes to return: " + returningAttributes.length + " items."); for (String ra : returningAttributes) { LDAPMultiBaseUserRegistry.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); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * Returns the list of role names for the given search base and other * parameters./* w w w . jav a 2 s. c om*/ * @param searchTime Maximum search time * @param filter Filter for searching role names * @param maxItemLimit Maximum number of roles required * @param searchFilter Group name search filter * @param roleNameProperty Attribute name of the group in LDAP user store. * @param searchBase Group search base. * @return The list of roles in the given search base. * @throws UserStoreException If an error occurs while retrieving the required information. */ private List<String> getLDAPRoleNames(int searchTime, String filter, int maxItemLimit, String searchFilter, String roleNameProperty, String searchBase) throws UserStoreException { boolean debug = log.isDebugEnabled(); List<String> roles = new ArrayList<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setCountLimit(maxItemLimit); searchCtls.setTimeLimit(searchTime); String returnedAtts[] = { roleNameProperty }; searchCtls.setReturningAttributes(returnedAtts); StringBuilder finalFilter = new StringBuilder(); finalFilter.append("(&").append(searchFilter).append("(").append(roleNameProperty).append("=") .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))"); if (debug) { log.debug("Listing roles. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString()); } DirContext dirContext = null; NamingEnumeration<SearchResult> answer = null; try { dirContext = connectionSource.getContext(); answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls); while (answer.hasMoreElements()) { SearchResult sr = answer.next(); if (sr.getAttributes() != null) { Attribute attr = sr.getAttributes().get(roleNameProperty); if (attr != null) { String name = (String) attr.get(); roles.add(name); } } } } catch (PartialResultException e) { // can be due to referrals in AD. so just ignore error String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (isIgnorePartialResultException()) { if (log.isDebugEnabled()) { log.debug(errorMessage, e); } } else { throw new UserStoreException(errorMessage, e); } } catch (NamingException e) { String errorMessage = "Error occurred while getting LDAP role names. SearchBase: " + searchBase + " ConstructedFilter: " + finalFilter.toString(); if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { for (String role : roles) { log.debug("result: " + role); } } return roles; }