List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildUserSearcher(final String query) { LOGGER.debug("Building user searcher for query {}", query); final SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); userSearchCtls.setReturningAttributes(this.userKeys.getFirst()); // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control userSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0); return (ctx) -> { try {/* www .j av a 2 s . c om*/ final NamingEnumeration<SearchResult> results = ctx.search(this.userSearchBase, query, userSearchCtls); return results; } catch (final NamingException e) { throw new AlfrescoRuntimeException("Failed to import people.", e); } }; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }/*w w w. j av a 2 s.co 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 }); InitialDirContext ctx = null; for (String userSearchBase : this.userSearchBases) { String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = 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(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 { LDAPMultiBaseUserRegistry.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; } } 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); } 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); } } // failed to search // Object[] args = {e.getLocalizedMessage()}; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic); }
From source file:org.lsc.jndi.JndiServices.java
private void doDeleteChildrenRecursively(String distinguishName) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> ne = ctx.search(distinguishName, DEFAULT_FILTER, sc); while (ne.hasMore()) { SearchResult sr = (SearchResult) ne.next(); String childrenDn = rewriteBase(sr.getName() + "," + distinguishName); deleteChildrenRecursively(childrenDn); }/*from w w w.j ava 2s . co m*/ ctx.destroySubcontext(new LdapName(distinguishName)); }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected Function<InitialDirContext, NamingEnumeration<SearchResult>> buildGroupSearcher(final String query) { LOGGER.debug("Building group searcher for query {}", query); final SearchControls groupSearchCtls = new SearchControls(); groupSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); groupSearchCtls.setReturningAttributes(this.groupKeys.getFirst()); // MNT-14001 fix, set search limit to ensure that server will not return more search results then provided by paged result control groupSearchCtls.setCountLimit(this.queryBatchSize > 0 ? this.queryBatchSize : 0); return (ctx) -> { try {/*from w w w . jav a 2s .c o m*/ final NamingEnumeration<SearchResult> results = ctx.search(this.groupSearchBase, query, groupSearchCtls); return results; } catch (final NamingException e) { throw new AlfrescoRuntimeException("Failed to import groups.", e); } }; }
From source file:org.lsc.jndi.JndiServices.java
/** * Return the LDAP schema.//from w ww . j a v a 2 s. c om * * @param attrsToReturn * list of attribute names to return (or null for all * 'standard' attributes) * @return the map of name => attribute * @throws NamingException * thrown if something goes wrong (bad */ @SuppressWarnings("unchecked") public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException { Map<String, List<String>> attrsResult = new HashMap<String, List<String>>(); // connect to directory Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment(); String baseUrl = (String) props.get(Context.PROVIDER_URL); baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/')); props.put(Context.PROVIDER_URL, baseUrl); DirContext schemaCtx = new InitialLdapContext(props, null); // find schema entry SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningAttributes(new String[] { "subschemaSubentry" }); NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc); SearchResult sr = null; Attribute subschemaSubentry = null; String subschemaSubentryDN = null; if (schemaDnSR.hasMore()) { sr = schemaDnSR.next(); } if (sr != null) { subschemaSubentry = sr.getAttributes().get("subschemaSubentry"); } if (subschemaSubentry != null && subschemaSubentry.size() > 0) { subschemaSubentryDN = (String) subschemaSubentry.get(); } if (subschemaSubentryDN != null) { // get schema attributes from subschemaSubentryDN Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN, attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" }); if (schemaAttrs != null) { for (String attr : attrsToReturn) { Attribute schemaAttr = schemaAttrs.get(attr); if (schemaAttr != null) { attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll())); } } } } return attrsResult; }
From source file:org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager.java
@Override protected String[] doGetDisplayNamesForInternalRole(String[] userNames) throws UserStoreException { // search the user with UserNameAttribute, retrieve their // DisplayNameAttribute combine and return String displayNameAttribute = this.realmConfig.getUserStoreProperty(LDAPConstants.DISPLAY_NAME_ATTRIBUTE); if (displayNameAttribute != null) { String userNameAttribute = this.realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE); String userSearchBase = this.realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String userNameListFilter = this.realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER); String[] returningAttributes = { displayNameAttribute }; SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(returningAttributes); List<String> combinedNames = new ArrayList<String>(); if (userNames != null && userNames.length > 0) { for (String userName : userNames) { String searchFilter = "(&" + userNameListFilter + "(" + userNameAttribute + "=" + escapeSpecialCharactersForFilter(userName) + "))"; List<String> displayNames = this.getListOfNames(userSearchBase, searchFilter, searchControls, displayNameAttribute, false); // we expect only one display name String name = UserCoreUtil.getCombinedName( this.realmConfig .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME), userName, displayNames.get(0)); combinedNames.add(name); }//from w w w .ja va2 s . c o m return combinedNames.toArray(new String[combinedNames.size()]); } else { return userNames; } } else { return userNames; } }
From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java
/** * {@inheritDoc}/*from w ww . ja v a2s . com*/ */ @Override public boolean doCheckExistingRole(String roleName) throws UserStoreException { boolean debug = log.isDebugEnabled(); boolean isExisting = false; if (debug) { log.debug("Searching for role: " + roleName); } String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER); String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE); searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "=" + escapeSpecialCharactersForFilter(roleName) + "))"; String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE); if (debug) { log.debug("Using search filter: " + searchFilter); } SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(new String[] { roleNameProperty }); NamingEnumeration<SearchResult> answer = null; DirContext dirContext = null; try { dirContext = connectionSource.getContext(); String[] roleSearchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR); for (String searchBase : roleSearchBaseArray) { if (debug) { log.debug("Searching in " + searchBase); } try { answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls); if (answer.hasMoreElements()) { isExisting = true; break; } } catch (NamingException e) { if (log.isDebugEnabled()) { log.debug(e); } } } } finally { JNDIUtil.closeNamingEnumeration(answer); JNDIUtil.closeContext(dirContext); } if (debug) { log.debug("Is role: " + roleName + " exist: " + isExisting); } return isExisting; }
From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java
@Override public void doDeleteUserClaimValue(String userName, String claimURI, 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 {//w w w. j ava 2 s . com 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 String attributeName = null; 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:com.aurel.track.util.LdapUtil.java
/** * Returns a HashMap <login name, TPersonBean> for all LDAP objects found in * the directory und the DN configured in the Genji server configuration. * /*from w w w.ja va 2s . co m*/ * @return Map with <login name, TPersonBean> */ public static HashMap<String, TPersonBean> getAllLdapPersonsPaged(TSiteBean siteBean, String filter) throws Exception { if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = siteBean.getLdapAttributeLoginName() + "=*"; } if (!(filter.startsWith("(") && filter.endsWith(")"))) { filter = "(" + filter + ")"; } LOGGER.debug("User filter expression " + filter); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); HashMap<String, TPersonBean> ldapPersonsMap = new HashMap<String, TPersonBean>(); LdapContext context = getInitialContext(siteBean.getLdapServerURL(), bindDN, bindPassword); if (context == null) { return ldapPersonsMap; } int recordCount = 0; // Create initial context // Control the search SearchControls ctls = null; try { // Activate paged results int pageSize = 5; byte[] cookie = null; context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; // Control the search ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers() + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // 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); String loginAttributeName = siteBean.getLdapAttributeLoginName(); do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", filter, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { ldapPersonsMap.put(personBean.getLoginName(), personBean); } ++recordCount; } // Examine the paged results control response Control[] controls = context.getResponseControls(); if (controls != null) { for (int i = 0; i < controls.length; i++) { if (controls[i] instanceof PagedResultsResponseControl) { PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i]; total = prrc.getResultSize(); if (total != 0) { LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total + ") *****************\n"); } else { LOGGER.debug( "***************** END-OF-PAGE " + "(total: unknown) ***************\n"); } cookie = prrc.getCookie(); } } } else { LOGGER.debug("No controls were sent from the server"); } // Re-activate paged results context.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } while (cookie != null); } catch (SizeLimitExceededException sle) { if (recordCount < ctls.getCountLimit()) { LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server."); LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with " + sle.getMessage()); LOGGER.error( "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter."); } else { LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server (" + recordCount + ")."); LOGGER.error( "You have to get more user licenses for Genji or specify a more suitable search base or filter."); } LOGGER.error("The LDAP synchronization is most likely incomplete."); } catch (NamingException e) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException ie) { LOGGER.error("PagedSearch failed."); LOGGER.debug(ExceptionUtils.getStackTrace(ie)); } finally { if (context != null) { context.close(); } } return ldapPersonsMap; }
From source file:org.apache.syncope.fit.core.GroupITCase.java
@Test public void issueSYNCOPE632() { DerSchemaTO orig = schemaService.read(SchemaType.DERIVED, "displayProperty"); DerSchemaTO modified = SerializationUtils.clone(orig); modified.setExpression("icon + '_' + show"); GroupTO groupTO = GroupITCase.getSampleTO("lastGroup"); try {//from w w w . j a va2s . c om schemaService.update(SchemaType.DERIVED, modified); // 0. create group groupTO.getPlainAttrs().add(attrTO("icon", "anIcon")); groupTO.getPlainAttrs().add(attrTO("show", "true")); groupTO.getResources().clear(); groupTO = createGroup(groupTO).getEntity(); assertNotNull(groupTO); // 1. create new LDAP resource having ConnObjectKey mapped to a derived attribute ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP); newLDAP.setKey("new-ldap"); newLDAP.setPropagationPriority(0); for (ProvisionTO provision : newLDAP.getProvisions()) { provision.getVirSchemas().clear(); } MappingTO mapping = newLDAP.getProvision(AnyTypeKind.GROUP.name()).get().getMapping(); ItemTO connObjectKey = mapping.getConnObjectKeyItem(); connObjectKey.setIntAttrName("displayProperty"); connObjectKey.setPurpose(MappingPurpose.PROPAGATION); mapping.setConnObjectKeyItem(connObjectKey); mapping.setConnObjectLink("'cn=' + displayProperty + ',ou=groups,o=isp'"); ItemTO description = new ItemTO(); description.setIntAttrName("key"); description.setExtAttrName("description"); description.setPurpose(MappingPurpose.PROPAGATION); mapping.add(description); newLDAP = createResource(newLDAP); assertNotNull(newLDAP); // 2. update group and give the resource created above GroupPatch patch = new GroupPatch(); patch.setKey(groupTO.getKey()); patch.getResources().add( new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE).value("new-ldap").build()); groupTO = updateGroup(patch).getEntity(); assertNotNull(groupTO); // 3. update the group GroupPatch groupPatch = new GroupPatch(); groupPatch.setKey(groupTO.getKey()); groupPatch.getPlainAttrs().add(attrAddReplacePatch("icon", "anotherIcon")); groupTO = updateGroup(groupPatch).getEntity(); assertNotNull(groupTO); // 4. check that a single group exists in LDAP for the group created and updated above int entries = 0; DirContext ctx = null; try { ctx = getLdapResourceDirContext(null, null); SearchControls ctls = new SearchControls(); ctls.setReturningAttributes(new String[] { "*", "+" }); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp", "(description=" + groupTO.getKey() + ")", ctls); while (result.hasMore()) { result.next(); entries++; } } catch (Exception e) { // ignore } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { // ignore } } } assertEquals(1, entries); } finally { schemaService.update(SchemaType.DERIVED, orig); if (groupTO.getKey() != null) { groupService.delete(groupTO.getKey()); } resourceService.delete("new-ldap"); } }