List of usage examples for javax.naming.directory DirContext search
public NamingEnumeration<SearchResult> search(String name, String filter, SearchControls cons) throws NamingException;
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; Hashtable<String, String> env = getEnvironment(); try {/*from w w w .j a va 2 s .c o m*/ 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:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java
private String searchUser(String login, HashMap<String, String> userAttrs, DirContext ctx) throws NamingException { String uid;//from ww w . j a v a 2 s.c o m SearchControls ctls = new SearchControls(); ctls.setReturningObjFlag(true); ctls.setSearchScope(searchScope); String search = searchPattern.replaceAll(Pattern.quote("%LOGIN%"), escapeLDAPSearchFilter(login)); log.debug("Searching LDAP for " + search); NamingEnumeration<SearchResult> answer = ctx.search(base, search, ctls); try { if (!answer.hasMore()) throw new NoSuchElementException(); log.debug("LDAP returned >=1 record."); SearchResult result = answer.next(); uid = result.getName(); for (Map.Entry<String, String> e : attributeMap.entrySet()) { log.debug("found LDAP attribute: " + e.getKey()); Attribute a = result.getAttributes().get(e.getKey()); if (a != null) userAttrs.put(e.getValue(), a.get().toString()); } } finally { answer.close(); } return uid; }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private String performRoleSearch(String location, String roleName) { String val = null; try {//from ww w . j av a 2 s. c om DirContext dc = new InitialDirContext(env); SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.ONELEVEL_SCOPE); //String filter = "(" + filterPrefix + roleName + ")"; NamingEnumeration<SearchResult> ne = dc.search(location, roleName, sc); if (ne.hasMore()) { val = getAttrValue("memberOf", ne.next()); } ne.close(); dc.close(); } catch (NamingException ne) { log.warn("Failed LDAP lookup getAttr", ne); log.warn("roleName:", roleName); log.warn("location:", location); } return val; }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Performs a search of LDAP/*from www . ja v a 2 s .c o m*/ * * @param username * The username to be used in the search * @param dc * The directory context to use for the search * @return An enumeration containing the search results * @throws NamingException */ private NamingEnumeration<SearchResult> performLdapSearch(String username, DirContext dc) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "(" + filterPrefix + idAttr + "=" + username + filterSuffix + ")"; NamingEnumeration<SearchResult> ne = dc.search(baseDn, filter, sc); log.trace(String.format("performing LDAP search using baseDn: %s, filter: %s", baseDn, filter)); return ne; }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
private boolean getUserInf(UserEdit edit, String filter) { String id = null;/* w w w . j a v a 2 s .c om*/ String firstName = null; String lastName = null; String employeenumber = null; String email = null; try { DirContext ctx = new InitialDirContext(env); // Setup subtree scope to tell LDAP to recursively descend directory structure // during searches. SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); // We want the user's id, first name and last name ... searchControls.setReturningAttributes(new String[] { "uid", "givenName", "sn" }); // Execute the search, starting at the directory level of Users NamingEnumeration results = ctx.search(getBasePath(), filter, searchControls); while (results.hasMore()) { SearchResult result = (SearchResult) results.next(); String dn = result.getName().toString() + "," + getBasePath(); Attributes attrs = ctx.getAttributes(dn); id = attrs.get("uid").get().toString(); String cn = attrs.get("cn").get().toString(); firstName = cn.substring(0, cn.indexOf(" ")); lastName = cn.substring(cn.indexOf(" ")); email = attrs.get("mail").get().toString(); } results.close(); ctx.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } edit.setId(id); edit.setFirstName(firstName); edit.setLastName(lastName); edit.setEmail(email); return true; }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext) throws LdapControllerException { Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>(); NamingEnumeration<SearchResult> namingEnumeration = null; try {// w ww .j a v a2s . c o m SearchControls searchControls = new SearchControls(); searchControls.setDerefLinkFlag(true); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); String filter = "objectClass=" + getLdapGroupClass(); namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls); while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); String groupName = searchResult.getName(); // cn=blabla we only want bla bla groupName = StringUtils.substringAfter(groupName, "="); Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember"); 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, ","); Collection<String> roles = usersWithRoles.get(userName); if (roles == null) { roles = new HashSet<String>(); } roles.add(groupName); usersWithRoles.put(userName, roles); } } log.debug("found groupName: '{}' with users: {}", groupName); } return usersWithRoles; } catch (NamingException e) { throw new LdapControllerException(e.getMessage(), e); } finally { if (namingEnumeration != null) { try { namingEnumeration.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
protected boolean userExists(String id) { env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_CREDENTIALS, "secret"); try {// w ww . j a v a2s .co m DirContext ctx = new InitialDirContext(env); /* * Setup subtree scope to tell LDAP to recursively descend directory structure during searches. */ SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); /* * Setup the directory entry attributes we want to search for. In this case it is the user's ID. */ String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))"; /* Execute the search, starting at the directory level of Users */ NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls); /* All we need to know is if there were any hits at all. */ if (hits.hasMore()) { hits.close(); ctx.close(); return true; } else { hits.close(); ctx.close(); return false; } } catch (Exception e) { e.printStackTrace(); return false; } }
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 {/*www. j a 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.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Returns <code>true</code> if the supplied id is found in the JNDI storage. * @see IStorage#exists(java.lang.String) *//* w ww .j a v a2 s.c o m*/ public boolean exists(String id) throws UserException { DirContext oDirContext = null; NamingEnumeration oNamingEnumeration = null; boolean bReturn = false; try { try { oDirContext = new InitialDirContext(_htJNDIEnvironment); } catch (NamingException e) { _logger.error("Could not create the connection: " + _htJNDIEnvironment); throw new UserException(SystemErrors.ERROR_RESOURCE_CONNECT, e); } SearchControls oScope = new SearchControls(); oScope.setSearchScope(SearchControls.SUBTREE_SCOPE); String searchFilter = resolveSearchQuery(id); try { oNamingEnumeration = oDirContext.search(_sDNBase, searchFilter, oScope); bReturn = oNamingEnumeration.hasMore(); } catch (InvalidSearchFilterException e) { _logger.error("Wrong filter: " + searchFilter); throw new UserException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } catch (NamingException e) { _logger.debug("User unknown, naming exception. query: " + searchFilter, e); return false; //user unknown } } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not verify if user exists: " + id, e); throw new UserException(SystemErrors.ERROR_INTERNAL, e); } finally { if (oNamingEnumeration != null) { try { oNamingEnumeration.close(); } catch (Exception e) { _logger.error("Could not close Naming Enumeration after searching for user with id: " + id, e); } } if (oDirContext != null) { try { oDirContext.close(); } catch (NamingException e) { _logger.error("Could not close Dir Context after searching for user with id: " + id, e); } } } return bReturn; }