List of usage examples for javax.naming.directory SearchControls SearchControls
public SearchControls()
From source file:alpine.auth.LdapConnectionWrapper.java
/** * Performs a search for the specified username. Internally, this method queries on * the attribute defined by {@link Config.AlpineKey#LDAP_ATTRIBUTE_NAME}. * @param ctx the DirContext to use/*from w ww. j ava 2s . c o m*/ * @param username the username to query on * @return a list of SearchResult objects. If the username is found, the list should typically only contain one result. * @throws NamingException if an exception is thrown * @since 1.4.0 */ public List<SearchResult> searchForUsername(DirContext ctx, String username) throws NamingException { final String[] attributeFilter = {}; final SearchControls sc = new SearchControls(); sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); final String searchFor = LdapConnectionWrapper.ATTRIBUTE_NAME + "=" + LdapStringSanitizer.sanitize(formatPrincipal(username)); return Collections.list(ctx.search(LdapConnectionWrapper.BASE_DN, searchFor, sc)); }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isExistingServicePrinciple(String servicePrinciple) throws DirectoryServerManagerException { DirContext dirContext;/*from ww w.j a v a2 s . co m*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { log.error("Unable to retrieve directory context.", e); throw new DirectoryServerManagerException("Unable to retrieve directory context.", e); } //first search the existing user entry. String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String filter = getServicePrincipleFilter(servicePrinciple); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter, searchControls); return namingEnumeration.hasMore(); } catch (NamingException e) { String message = "Unable to search entry with search base " + searchBase + ", filter -" + filter; log.error(message, e); throw new DirectoryServerManagerException("Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java
/** * Search controls that only fetch attributes defined by the schema * * @return common search controls to use for all LDAP search queries * @throws DirectoryException//from w w w .j a v a 2s .c o m */ protected SearchControls computeSearchControls() throws DirectoryException { LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor(); SearchControls scts = new SearchControls(); // respect the scope of the configuration scts.setSearchScope(ldapDirectoryDesc.getSearchScope()); // only fetch attributes that are defined in the schema or needed to // compute LDAPReferences Set<String> attrs = new HashSet<>(); for (String fieldName : schemaFieldMap.keySet()) { if (!references.containsKey(fieldName)) { attrs.add(fieldMapper.getBackendField(fieldName)); } } attrs.add("objectClass"); for (Reference reference : getReferences()) { if (reference instanceof LDAPReference) { LDAPReference ldapReference = (LDAPReference) reference; attrs.add(ldapReference.getStaticAttributeId(fieldMapper)); attrs.add(ldapReference.getDynamicAttributeId()); // Add Dynamic Reference attributes filtering for (LDAPDynamicReferenceDescriptor dynAtt : ldapReference.getDynamicAttributes()) { attrs.add(dynAtt.baseDN); attrs.add(dynAtt.filter); } } } if (getPasswordField() != null) { // never try to fetch the password attrs.remove(getPasswordField()); } scts.setReturningAttributes(attrs.toArray(new String[attrs.size()])); scts.setCountLimit(ldapDirectoryDesc.getQuerySizeLimit()); scts.setTimeLimit(ldapDirectoryDesc.getQueryTimeLimit()); return scts; }
From source file:org.apache.zeppelin.realm.ActiveDirectoryGroupRealm.java
public List<String> searchForUserName(String containString, LdapContext ldapContext) throws NamingException { List<String> userNameList = new ArrayList<>(); SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = "(&(objectClass=*)(userPrincipalName=*" + containString + "*))"; Object[] searchArguments = new Object[] { containString }; NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls); while (answer.hasMoreElements()) { SearchResult sr = (SearchResult) answer.next(); if (log.isDebugEnabled()) { log.debug("Retrieving userprincipalname names for user [" + sr.getName() + "]"); }/*from ww w . j a va2 s . c o m*/ Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration ae = attrs.getAll(); while (ae.hasMore()) { Attribute attr = (Attribute) ae.next(); if (attr.getID().toLowerCase().equals("cn")) { userNameList.addAll(LdapUtils.getAllAttributeValues(attr)); } } } } return userNameList; }
From source file:org.apache.directory.server.operations.bind.MiscBindIT.java
/** * Test to make sure that if anonymous binds are allowed a user may search * within a a partition.//from w w w . java2 s. c om * * @throws Exception if anything goes wrong */ @Test public void testAnonymousBindsEnabledBaseSearch() throws Exception { getLdapServer().getDirectoryService().setAllowAnonymousAccess(true); // Use the SUN JNDI provider to hit server port and bind as anonymous Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort())); env.put(Context.SECURITY_AUTHENTICATION, "none"); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); InitialDirContext ctx = new InitialDirContext(env); SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); NamingEnumeration<SearchResult> list = ctx.search("dc=apache,dc=org", "(objectClass=*)", cons); SearchResult result = null; if (list.hasMore()) { result = list.next(); } assertFalse(list.hasMore()); list.close(); assertNotNull(result); assertNotNull(result.getAttributes().get("dc")); }
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 ww .ja v a 2 s. c om*/ 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.wfp.utils.LDAPUtils.java
/** * Overloaded method for searching the LDAP based on the searchfilter & searchbase with contraint as "cn" * @param searchFilter//from ww w . j av a 2s. 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:org.jasig.schedassist.impl.oraclecalendar.OracleLdapCalendarResourceAccountDaoImpl.java
/** * //w ww. j a va2 s . com * @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.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 w ww .j a v a 2 s . c om 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 *///www . ja v a2 s . c o m @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); } }