List of usage examples for javax.naming.directory SearchControls getCountLimit
public long getCountLimit()
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * * @param callback/* w w w . j ava2 s.c om*/ * 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 */ protected void processQuery(final SearchCallback callback, final String searchBase, final String query, final String[] returningAttributes) { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(returningAttributes); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Processing query {}\nSearch base: {}\n\rReturn result limit: {}\n\tDereflink: {}\n\rReturn named object: {}\n\tTime limit for search: {}\n\tAttributes to return: {} items\n\tAttributes: {}", query, searchBase, searchControls.getCountLimit(), searchControls.getDerefLinkFlag(), searchControls.getReturningObjFlag(), searchControls.getTimeLimit(), String.valueOf(returningAttributes.length), Arrays.toString(returningAttributes)); } 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); this.commonCloseSearchResult(result); result = null; } } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize)); } catch (final NamingException e) { final Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } catch (final ParseException e) { final Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } finally { this.commonAfterQueryCleanup(searchResults, result, ctx); } }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * * @param callback/*ww w . j a va 2 s.co 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: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 www . j av a 2 s . c o 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:com.aurel.track.util.LdapUtil.java
/** * Gets all persons for a group//from w w w . j a v a2 s.com * * @param groups * @param siteBean * @param filter * @return * @throws Exception */ static List<TPersonBean> getAllLdapUsersDescendants(String providerUrl, String bindDN, String bindPassword, String loginAttributeName, String filter) throws Exception { List<TPersonBean> personBeans = new ArrayList<TPersonBean>(); if (filter == null || "".equals(filter) || "*".equals(filter)) { filter = loginAttributeName + "=*"; } int recordCount = 0; SearchControls ctls = null; LdapContext ctx = null; try { ctx = getInitialContext(providerUrl, bindDN, bindPassword); if (ctx == null) { return personBeans; } // Activate paged results int pageSize = 5; // TODO replace for GROOVY ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) }); int total; String searchStr = "(" + filter + ")"; // 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 personBeans; } String firstNameAttributeName = ldapMap.get("firstName"); String lastNameAttributName = ldapMap.get("lastName"); String emailAttributeName = ldapMap.get("email"); String phoneAttributName = ldapMap.get("phone"); byte[] cookie = null; // TODO replace for GROOVY cookie = new byte[] {}; // cookie = [] as byte[]; while (cookie != null) { NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls); while (results != null && results.hasMore()) { SearchResult sr = (SearchResult) results.next(); TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName, lastNameAttributName, emailAttributeName, phoneAttributName); if (personBean != null) { personBeans.add(personBean); ++recordCount; } } // Examine the paged results control response Control[] controls = ctx.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 // TODO replace for GROOVY ctx.setRequestControls( new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) }); } } 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 (ctx != null) { ctx.close(); } } return personBeans; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups// ww w . j ava 2s . co m * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap, Map<String, String> groups) throws Exception { HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { LOGGER.debug( "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER); groupMemberAttributName = DEFAULT_GROUP_MEMBER; } LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword); if (baseContext == null) { LOGGER.warn("Context is null for baseURL " + baseURL); return ldapGroupsMap; } for (Map.Entry<String, String> groupEntry : groups.entrySet()) { String groupName = groupEntry.getKey(); String groupDN = groupEntry.getValue(); int index = groupDN.indexOf(","); if (index != -1) { String searchPart = groupDN.substring(0, index); String searchStr = "(" + searchPart + ")"; String parentDNPart = groupDN.substring(index + 1); LdapContext context = (LdapContext) baseContext.lookup(parentDNPart); if (context == null) { LOGGER.warn("Context is null after lookup for " + parentDNPart); continue; } int recordCount = 0; 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 do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls); /* * for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); continue; } TPersonBean personBean = new TPersonBean(); try { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } LOGGER.debug("Member found: " + memberSearchResult); memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed group " + groupName); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++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 { context.close(); } } } return ldapGroupsMap; }
From source file:com.aurel.track.util.LdapUtil.java
/** * Get all ldap groups/* w ww . j a v a2 s . c o m*/ * * @param siteBean * @param baseDnGroup * @param ldapFilterGroups * @param groupAttributeName * @param groupToMemberReferencesMap * @return * @throws Exception */ public static Map<String, TPersonBean> getLdapGroupsPaged(String baseURL, TSiteBean siteBean, String baseDnGroup, String ldapFilterGroups, String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap) throws Exception { if (ldapFilterGroups == null || "".equals(ldapFilterGroups) || "*".equals(ldapFilterGroups)) { ldapFilterGroups = "(" + groupAttributeName + "=*)"; } String bindDN = siteBean.getLdapBindDN(); String bindPassword = siteBean.getLdapBindPassword(); LdapContext context = getInitialContext(baseURL + baseDnGroup, bindDN, bindPassword); HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>(); if (context == null) { LOGGER.warn("Context is null"); return ldapGroupsMap; } int recordCount = 0; SearchControls ctls = null; String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER); if (groupMemberAttributName == null) { groupMemberAttributName = DEFAULT_GROUP_MEMBER; } 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 do { /* perform the search */ NamingEnumeration<SearchResult> results = context.search("", ldapFilterGroups, ctls); /* for each entry print out name + all attrs and values */ while (results != null && results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); // Attributes atrs = sr.getAttributes(); Attributes attributes = searchResult.getAttributes(); if (attributes == null) { LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName()); return null; } TPersonBean personBean = new TPersonBean(); try { Attribute groupNameAttribute = attributes.get(groupAttributeName); if (groupNameAttribute != null) { String groupName = (String) groupNameAttribute.get(); LOGGER.debug("Groupname: " + groupName); if (groupName == null || "".equals(groupName)) { LOGGER.info("No value for group name attribute " + groupAttributeName); return null; } else { personBean.setLoginName(groupName); ldapGroupsMap.put(personBean.getLoginName(), personBean); } Attribute memberAttribute = attributes.get(groupMemberAttributName); if (memberAttribute != null) { NamingEnumeration<?> members = memberAttribute.getAll(); while (members != null && members.hasMore()) { String memberSearchResult = (String) members.next(); List<String> memberDNList = groupToMemberReferencesMap.get(groupName); if (memberDNList == null) { memberDNList = new ArrayList<String>(); groupToMemberReferencesMap.put(groupName, memberDNList); } memberDNList.add(memberSearchResult); } } else { LOGGER.info("Could not find value(s) for group member attribute " + groupMemberAttributName + " for group " + groupName); } } LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get()); LOGGER.debug("Processed " + personBean.getLoginName() + " (" + personBean.getFirstName() + " " + personBean.getLastName() + ")"); } catch (Exception e) { LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage()); LOGGER.warn( "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Stack trace:", e); } } ++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 { context.close(); } return ldapGroupsMap; }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * /*from www . j a v a 2s . 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.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java
/** * {@inheritDoc}// w w w .j a v a 2 s . co m */ public StudioNamingEnumeration search(final String searchBase, final String filter, final SearchControls searchControls, final AliasDereferencingMethod aliasesDereferencingMethod, final ReferralHandlingMethod referralsHandlingMethod, final Control[] controls, final StudioProgressMonitor monitor, final ReferralsInfo referralsInfo) { final long requestNum = searchRequestNum++; InnerRunnable runnable = new InnerRunnable() { public void run() { try { // Preparing the search request SearchRequest request = new SearchRequestImpl(); request.setBase(new Dn(searchBase)); ExprNode node = FilterParser.parse(filter, true); request.setFilter(node); request.setScope(convertSearchScope(searchControls)); if (searchControls.getReturningAttributes() != null) { request.addAttributes(searchControls.getReturningAttributes()); } request.addAllControls(convertControls(controls)); request.setSizeLimit(searchControls.getCountLimit()); request.setTimeLimit(searchControls.getTimeLimit()); request.setDerefAliases(convertAliasDerefMode(aliasesDereferencingMethod)); // Performing the search operation SearchCursor cursor = ldapConnection.search(request); // Returning the result of the search namingEnumeration = new CursorStudioNamingEnumeration(connection, cursor, searchBase, filter, searchControls, aliasesDereferencingMethod, referralsHandlingMethod, controls, requestNum, monitor, referralsInfo); } catch (Exception e) { exception = e; } NamingException ne = null; if (exception != null) { ne = new NamingException(exception.getMessage()); } for (IJndiLogger logger : getJndiLoggers()) { if (namingEnumeration != null) { logger.logSearchRequest(connection, searchBase, filter, searchControls, aliasesDereferencingMethod, controls, requestNum, ne); } else { logger.logSearchRequest(connection, searchBase, filter, searchControls, aliasesDereferencingMethod, controls, requestNum, ne); logger.logSearchResultDone(connection, 0, requestNum, ne); } } } }; try { checkConnectionAndRunAndMonitor(runnable, monitor); } catch (Exception e) { monitor.reportError(e); return null; } if (runnable.isCanceled()) { monitor.setCanceled(true); } if (runnable.getException() != null) { monitor.reportError(runnable.getException()); return null; } else { return runnable.getResult(); } }
From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java
/** * {@inheritDoc}//from ww w.ja va 2 s . c o m */ public void logSearchRequest(Connection connection, String searchBase, String filter, SearchControls searchControls, AliasDereferencingMethod aliasesDereferencingMethod, Control[] controls, long requestNum, NamingException ex) { if (!isSearchRequestLogEnabled()) { return; } String scopeAsString = searchControls.getSearchScope() == SearchControls.SUBTREE_SCOPE ? "wholeSubtree (2)" //$NON-NLS-1$ : searchControls.getSearchScope() == SearchControls.ONELEVEL_SCOPE ? "singleLevel (1)" //$NON-NLS-1$ : "baseObject (0)"; //$NON-NLS-1$ String attributesAsString = searchControls.getReturningAttributes() == null ? "*" //$NON-NLS-1$ : searchControls.getReturningAttributes().length == 0 ? "1.1" //$NON-NLS-1$ : StringUtils.join(searchControls.getReturningAttributes(), " "); String aliasAsString = aliasesDereferencingMethod == AliasDereferencingMethod.ALWAYS ? "derefAlways (3)" //$NON-NLS-1$ : aliasesDereferencingMethod == AliasDereferencingMethod.FINDING ? "derefFindingBaseObj (2)" //$NON-NLS-1$ : aliasesDereferencingMethod == AliasDereferencingMethod.SEARCH ? "derefInSearching (1)" //$NON-NLS-1$ : "neverDerefAliases (0)"; //$NON-NLS-1$ // build LDAP URL LdapUrl url = Utils.getLdapURL(connection, searchBase, searchControls.getSearchScope(), filter, searchControls.getReturningAttributes()); // build command line String cmdLine = Utils.getLdapSearchCommandLine(connection, searchBase, searchControls.getSearchScope(), aliasesDereferencingMethod, searchControls.getCountLimit(), searchControls.getTimeLimit(), filter, searchControls.getReturningAttributes()); // build Collection<LdifLineBase> lines = new ArrayList<LdifLineBase>(); lines.add(LdifCommentLine.create("# LDAP URL : " + url.toString())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# command line : " + cmdLine.toString())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# baseObject : " + searchBase)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# scope : " + scopeAsString)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# derefAliases : " + aliasAsString)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# sizeLimit : " + searchControls.getCountLimit())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# timeLimit : " + searchControls.getTimeLimit())); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# typesOnly : " + "False")); //$NON-NLS-1$ //$NON-NLS-2$ lines.add(LdifCommentLine.create("# filter : " + filter)); //$NON-NLS-1$ lines.add(LdifCommentLine.create("# attributes : " + attributesAsString)); //$NON-NLS-1$ if (controls != null) { for (Control control : controls) { lines.add(LdifCommentLine.create("# control : " + control.getID())); //$NON-NLS-1$ } } lines.add(LdifSepLine.create()); String formattedString = ""; //$NON-NLS-1$ for (LdifLineBase line : lines) { formattedString += line.toFormattedString(LdifFormatParameters.DEFAULT); } log(formattedString, "SEARCH REQUEST (" + requestNum + ")", ex, connection); //$NON-NLS-1$ //$NON-NLS-2$ }
From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java
/** * We need to make sure the search controls has the return object flag set to true, in order for * the search to return DirContextAdapter instances. * @param originalControls/* www.j a v a 2 s . co m*/ * @return */ private static SearchControls buildControls(SearchControls originalControls) { return new SearchControls(originalControls.getSearchScope(), originalControls.getCountLimit(), originalControls.getTimeLimit(), originalControls.getReturningAttributes(), RETURN_OBJECT, originalControls.getDerefLinkFlag()); }