List of usage examples for javax.naming.directory SearchControls SUBTREE_SCOPE
int SUBTREE_SCOPE
To view the source code for javax.naming.directory SearchControls SUBTREE_SCOPE.
Click Source Link
From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java
public List<String> getGroupsMember(String group, DirContext context) throws MappingException { NamingEnumeration<SearchResult> namingEnumeration = null; try {//w w w . ja v a2s. c o m SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = context.search("cn=" + group + "," + getGroupsDn(), filter, searchControls); List<String> allMembers = new ArrayList<String>(); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attribute uniqueMemberAttr = searchResult.getAttributes().get(getLdapGroupMember()); if (uniqueMemberAttr != null) { NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr .getAll(); while (allMembersEnum.hasMore()) { String userName = allMembersEnum.next(); // uid=blabla we only want bla bla userName = StringUtils.substringAfter(userName, "="); userName = StringUtils.substringBefore(userName, ","); log.debug("found userName for group {}: '{}", group, userName); allMembers.add(userName); } close(allMembersEnum); } } return allMembers; } catch (LdapException e) { throw new MappingException(e.getMessage(), e); } catch (NamingException e) { throw new MappingException(e.getMessage(), e); } finally { close(namingEnumeration); } }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
@Override public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName) throws Exception { LdapContext ldapContext = null; NamingEnumeration<SearchResult> enu = null; try {/* w w w . j a v a2 s .c o m*/ LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider .getConfiguration(companyId, ldapServerId); String baseDN = ldapServerConfiguration.baseDN(); ldapContext = _portalLDAP.getContext(ldapServerId, companyId); if (ldapContext == null) { _log.error("Unable to bind to the LDAP server"); return null; } String filter = ldapServerConfiguration.authSearchFilter(); if (_log.isDebugEnabled()) { _log.debug("Search filter before transformation " + filter); } filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" }, new String[] { String.valueOf(companyId), emailAddress, screenName }); LDAPUtil.validateFilter(filter); if (_log.isDebugEnabled()) { _log.debug("Search filter after transformation " + filter); } Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId); String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName")); userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName); SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, new String[] { userMappingsScreenName }, false, false); enu = ldapContext.search(baseDN, filter, searchControls); if (enu.hasMoreElements()) { if (_log.isDebugEnabled()) { _log.debug("Search filter returned at least one result"); } Binding binding = enu.nextElement(); Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext, binding.getNameInNamespace()); return importUser(ldapServerId, companyId, ldapContext, attributes, null); } else { return null; } } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn("Problem accessing LDAP server " + e.getMessage()); } if (_log.isDebugEnabled()) { _log.debug(e, e); } throw new SystemException("Problem accessing LDAP server " + e.getMessage()); } finally { if (enu != null) { enu.close(); } if (ldapContext != null) { ldapContext.close(); } } }
From source file:com.wfp.utils.LDAPUtils.java
/** * Overloaded method for searching the LDAP based on the searchfilter & searchbase with contraint as "cn" * @param searchFilter//from www . j a v a 2 s .c om * @param searchBase * @return * @throws NamingException */ @SuppressWarnings("unchecked") public static NamingEnumeration getSearchResults(String searchFilter, String searchBase) { // Specify the attributes to return String returnedAtts[] = { PROPERTY_CN }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try { return getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase); } catch (NamingException e) { Logger.error( " Error occured while searching results 206: getSearchResults(String searchFilter, String searchBase):[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } return null; }
From source file:com.openkm.principal.LdapPrincipalAdapter.java
@SuppressWarnings("unchecked") private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) { log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute }); List<String> al = new ArrayList<String>(); DirContext ctx = null;//from www .j a v a 2 s.com Hashtable<String, String> env = getEnvironment(); try { ctx = new InitialDirContext(env); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); for (String searchBase : searchBases) { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); if (attribute.equals("")) { StringBuilder sb = new StringBuilder(); for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) { Attribute attr = (Attribute) ne.nextElement(); sb.append(attr.toString()); sb.append("\n"); } al.add(sb.toString()); } else { Attribute attrib = attributes.get(attribute); if (attrib != null) { // Handle multi-value attributes for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) { String value = (String) ne.nextElement(); // If FQDN get only main part if (value.startsWith("CN=") || value.startsWith("cn=")) { String cn = value.substring(3, value.indexOf(',')); log.debug("FQDN: {}, CN: {}", value, cn); al.add(cn); } else { al.add(value); } } } } } } } catch (ReferralException e) { log.error("ReferralException: {}", e.getMessage()); log.error("ReferralInfo: {}", e.getReferralInfo()); log.error("ResolvedObj: {}", e.getResolvedObj()); try { log.error("ReferralContext: {}", e.getReferralContext()); } catch (NamingException e1) { log.error("NamingException logging context: {}", e1.getMessage()); } } catch (NamingException e) { log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})", new Object[] { e.getMessage(), searchBases, searchFilter, attribute }); } finally { try { if (ctx != null) { ctx.close(); } } catch (NamingException e) { log.error("NamingException closing context: {}", e.getMessage()); } } log.debug("ldapSearch: {}", al); return al; }
From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java
/** * Retrieves the roles for the from the identity provider. * * @param username the user to get the roles for * @return the list of roles for the user * @throws PortalServiceException for any errors encountered *///from www. jav a 2 s.c om @SuppressWarnings("rawtypes") public List<String> findRoles(String username) throws PortalServiceException { DirContext ctx = null; try { ctx = new InitialDirContext(env); // Search for groups the user belongs to in order to get their names // Create the search controls SearchControls groupsSearchCtls = new SearchControls(); // Specify the search scope groupsSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Specify the attributes to return String groupsReturnedAtts[] = { "cn" }; groupsSearchCtls.setReturningAttributes(groupsReturnedAtts); String userDn = MessageFormat.format(userDNPattern, username); // Search for objects using the filter NamingEnumeration groupsAnswer = ctx.search(groupsSearchBase, MessageFormat.format(groupsFilterPattern, userDn), groupsSearchCtls); List<String> groups = new ArrayList<String>(); // Loop through the search results while (groupsAnswer.hasMoreElements()) { SearchResult sr = (SearchResult) groupsAnswer.next(); Attributes attrs = sr.getAttributes(); if (attrs != null) { groups.add((String) attrs.get("cn").get()); } if (sr.getObject() instanceof Context) { closeContext((Context) sr.getObject()); } } return groups; } catch (NamingException e) { throw new PortalServiceConfigurationException("Unable to get groups.", e); } finally { closeContext(ctx); } }
From source file:org.jasig.schedassist.impl.oraclecalendar.OracleLdapCalendarResourceAccountDaoImpl.java
/** * /*w ww .j ava 2s . c o m*/ * @param searchFilter * @param owner * @return */ @SuppressWarnings("unchecked") protected List<IDelegateCalendarAccount> executeSearchReturnList(final Filter searchFilter, final ICalendarAccount owner) { SearchControls searchControls = new SearchControls(); searchControls.setCountLimit(searchResultsLimit); searchControls.setTimeLimit(searchTimeLimit); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); List<IDelegateCalendarAccount> results = Collections.emptyList(); try { results = ldapTemplate.search(baseDn, searchFilter.toString(), searchControls, new OracleCalendarResourceAccountAttributesMapper(this.oracleGUIDSource, owner)); if (LOG.isDebugEnabled()) { LOG.debug("search " + searchFilter + " returned " + results.size() + " results"); } Collections.sort(results, new DelegateDisplayNameComparator()); } catch (SizeLimitExceededException e) { LOG.debug("search filter exceeded size limit (" + searchResultsLimit + "): " + searchFilter); } catch (TimeLimitExceededException e) { LOG.debug("search filter exceeded time limit(" + searchTimeLimit + " milliseconds): " + searchFilter); } return results; }
From source file:com.orangeleap.common.security.OrangeLeapLdapAuthoritiesPopulator.java
/** * If set to true, a subtree scope search will be performed. If false a single-level search is used. * * @param searchSubtree set to true to enable searching of the entire tree below the <tt>groupSearchBase</tt>. *///from w w w .ja v a 2s . c o m public void setSearchSubtree(boolean searchSubtree) { int searchScope = searchSubtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE; searchControls.setSearchScope(searchScope); }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static String getOrgDN(String organisation, String countryCode) { NamingEnumeration results = null; DirContext ctx = null;//from w w w . java 2 s . co m String dn = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); String retAttrs[] = { "dn" }; controls.setReturningAttributes(retAttrs); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search("c=" + countryCode + "," + rb.getString("organisationsRoot"), "(&(objectclass=organization)(o=" + organisation + "))", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); dn = searchResult.getNameInNamespace(); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { // Never mind this. } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { // Never mind this. } } } return dn; }
From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java
public void updateSchemas() { DirContext dirContext = null; try {/*from w ww .ja v a2 s .c o m*/ dirContext = getContext(); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); controls.setCountLimit(1); updateSuffix(dirContext); updateGroups(dirContext, controls); updatePeople(dirContext, controls); updateRootDN(dirContext, controls); updateUsers(dirContext, controls); } finally { if (dirContext != null) { try { dirContext.close(); } catch (NamingException ex) { throw new RuntimeException("Could not close the LDAP context", ex); } } } }
From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java
private boolean ldapAuthorizationVerification(String user) { M_log.debug("ldapAuthorizationVerification(): called"); boolean isAuthorized = false; DirContext dirContext = null; NamingEnumeration listOfPeopleInAuthGroup = null; NamingEnumeration allSearchResultAttributes = null; NamingEnumeration simpleListOfPeople = null; Hashtable<String, String> env = new Hashtable<String, String>(); if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) { env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY); env.put(Context.PROVIDER_URL, providerURL); } else {//from w w w . ja v a2 s . c om M_log.error( " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file"); return isAuthorized; } try { dirContext = new InitialDirContext(env); String[] attrIDs = { "member" }; SearchControls searchControls = new SearchControls(); searchControls.setReturningAttributes(attrIDs); searchControls.setReturningObjFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchBase = OU_GROUPS; String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))"; listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls); String positiveMatch = "uid=" + user + ","; outerloop: while (listOfPeopleInAuthGroup.hasMore()) { SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next(); allSearchResultAttributes = (searchResults.getAttributes()).getAll(); while (allSearchResultAttributes.hasMoreElements()) { Attribute attr = (Attribute) allSearchResultAttributes.nextElement(); simpleListOfPeople = attr.getAll(); while (simpleListOfPeople.hasMoreElements()) { String val = (String) simpleListOfPeople.nextElement(); if (val.indexOf(positiveMatch) != -1) { isAuthorized = true; break outerloop; } } } } return isAuthorized; } catch (NamingException e) { M_log.error("Problem getting attribute:" + e); return isAuthorized; } finally { try { if (simpleListOfPeople != null) { simpleListOfPeople.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ", e); } try { if (allSearchResultAttributes != null) { allSearchResultAttributes.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ", e); } try { if (listOfPeopleInAuthGroup != null) { listOfPeopleInAuthGroup.close(); } } catch (NamingException e) { M_log.error( "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ", e); } try { if (dirContext != null) { dirContext.close(); } } catch (NamingException e) { M_log.error("Problem occurred while closing the \"dirContext\" object", e); } } }