List of usage examples for javax.naming NamingEnumeration close
public void close() throws NamingException;
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 w w w .j a v a 2s. 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:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
/** * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUsers(javax.naming.directory.DirContext) *//*from www .j a v a 2s . c o m*/ public Collection<User> getUsers(DirContext context) throws LdapControllerException, MappingException { NamingEnumeration<SearchResult> results = null; try { results = searchUsers(context, null, null); Set<User> users = new LinkedHashSet<User>(); while (results.hasMoreElements()) { SearchResult result = results.nextElement(); users.add(mapper.getUser(result.getAttributes())); } return users; } catch (NamingException e) { String message = "Failed to retrieve ldap information for users."; throw new LdapControllerException(message, e); } finally { if (results != null) { try { results.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
/** * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUsersByQuery(org.apache.archiva.redback.users.ldap.LdapUserQuery, javax.naming.directory.DirContext) *//*from w w w. j a va 2s .com*/ public List<User> getUsersByQuery(LdapUserQuery query, DirContext context) throws LdapControllerException, MappingException { NamingEnumeration<SearchResult> results = null; try { results = searchUsers(context, null, query); List<User> users = new LinkedList<User>(); while (results.hasMoreElements()) { SearchResult result = results.nextElement(); users.add(mapper.getUser(result.getAttributes())); } return users; } catch (NamingException e) { String message = "Failed to retrieve ldap information for users."; throw new LdapControllerException(message, e); } finally { if (results != null) { try { results.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
/** * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#getUser(String, javax.naming.directory.DirContext) *///w ww . ja v a 2s.co m public LdapUser getUser(String username, DirContext context) throws LdapControllerException, MappingException { log.debug("Searching for user: {}", username); LdapUserQuery query = new LdapUserQuery(); query.setUsername(username); NamingEnumeration<SearchResult> result = null; try { result = searchUsers(context, null, query); if (result.hasMoreElements()) { SearchResult next = result.nextElement(); log.info("Found user: {}", username); return mapper.getUser(next.getAttributes()); } else { return null; } } catch (NamingException e) { String message = "Failed to retrieve information for user: " + username; throw new LdapControllerException(message, e); } finally { if (result != null) { try { result.close(); } catch (NamingException e) { log.warn("failed to close search results", e); } } } }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Resolves all the groups that the user is in. * * We now use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx">tokenGroups</a> * attribute, which is a computed attribute that lists all the SIDs of the groups that the user is directly/indirectly in. * We then use that to retrieve all the groups in one query and resolve their canonical names. * * @param userDN/*from w w w. jav a 2 s . c om*/ * User's distinguished name. * @param context Used for making queries. */ private Set<GrantedAuthority> resolveGroups(String domainDN, String userDN, DirContext context) throws NamingException { if (userDN.contains("/")) { userDN = userDN.replace("/", "\\/"); } Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>(); LOGGER.log(Level.FINER, "Looking up group of {0}", userDN); Attributes id = context.getAttributes(userDN, new String[] { "tokenGroups", "memberOf", "CN" }); Attribute tga = id.get("tokenGroups"); if (tga == null) { // tga will be null if you are not using a global catalogue // or if the user is not actually a member of any security groups. LOGGER.log(Level.FINE, "Failed to retrieve tokenGroups for {0}", userDN); // keep on trucking as we can still use memberOf for Distribution Groups. } else { // build up the query to retrieve all the groups StringBuilder query = new StringBuilder("(|"); List<byte[]> sids = new ArrayList<byte[]>(); NamingEnumeration<?> tokenGroups = tga.getAll(); while (tokenGroups.hasMore()) { byte[] gsid = (byte[]) tokenGroups.next(); query.append("(objectSid={" + sids.size() + "})"); sids.add(gsid); } tokenGroups.close(); query.append(")"); NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope() .returns("cn").search(query.toString(), sids.toArray()); parseMembers(userDN, groups, renum); renum.close(); } {/* stage 2: use memberOf to find groups that aren't picked up by tokenGroups. This includes distribution groups */ LOGGER.fine("Stage 2: looking up via memberOf"); while (true) { switch (groupLookupStrategy) { case TOKENGROUPS: // no extra lookup - ever. return groups; case AUTO: // try the accurate one first, and if it's too slow fall back to recursive in the hope that it's faster long start = System.nanoTime(); boolean found = false; long duration = 0; try { found = chainGroupLookup(domainDN, userDN, context, groups); duration = TimeUnit2.NANOSECONDS.toSeconds(System.nanoTime() - start); } catch (TimeLimitExceededException e) { LOGGER.log(Level.WARNING, "The LDAP request did not terminate within the specified time limit. AD will fall back to recursive lookup", e); } catch (NamingException e) { if (e.getMessage().contains("LDAP response read timed out")) { LOGGER.log(Level.WARNING, "LDAP response read time out. AD will fall back to recursive lookup", e); } else { throw e; } } if (!found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension timed out after {0} seconds. Falling back to recursive group lookup strategy for this and future queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else if (found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension matched user's groups but took {0} seconds to run. Switching to recursive lookup for future group lookup queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; return groups; } else if (!found) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension failed. Falling back to recursive group lookup strategy for this and future queries"); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else { // it run fast enough, so let's stick to it groupLookupStrategy = GroupLookupStrategy.CHAIN; return groups; } case RECURSIVE: recursiveGroupLookup(context, id, groups); return groups; case CHAIN: chainGroupLookup(domainDN, userDN, context, groups); return groups; } } } }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
protected Privilege convertLdapGroupToOrganizationPrivilegeWithUsers( NamingEnumeration<SearchResult> pPrivilegesSearchResults) throws NamingException, IllegalAccessException { Privilege vOrgPrivilege = null;/*from w ww.j a va 2s. c o m*/ try { if ((pPrivilegesSearchResults != null) && (pPrivilegesSearchResults.hasMore())) { vOrgPrivilege = this.convertLdapGroupToOrgPriv(pPrivilegesSearchResults.next()); } } finally { // -- releases this context's resources immediately, instead of // waiting for the garbage collector if (pPrivilegesSearchResults != null) { try { pPrivilegesSearchResults.close(); pPrivilegesSearchResults = null; } catch (NamingException ex) { } } } return vOrgPrivilege; }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
protected Set<Privilege> convertLdapGroupsToOrganizationPrivilegesWithUsers( NamingEnumeration<SearchResult> pPrivilegesSearchResults) throws NamingException, IllegalAccessException { Set<Privilege> vResult = new HashSet<Privilege>(); try {/*from w w w.j av a 2 s . c o m*/ Privilege vOrgPrivilege; // construct privileges while (pPrivilegesSearchResults.hasMore()) { if ((vOrgPrivilege = this.convertLdapGroupToOrgPriv(pPrivilegesSearchResults.next())) != null) { vResult.add(vOrgPrivilege); } } } finally { // -- releases this context's resources immediately, instead of // waiting for the garbage collector if (pPrivilegesSearchResults != null) { try { pPrivilegesSearchResults.close(); } catch (NamingException ex) { } } } return vResult; }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will enumerate the names bounds to the specified context, along with * the class names of objects bound to them. The resulting <code> * Iterator</code> is a deep copy of the original search results. See {@link * javax.naming.Context#list(String)}./*from w ww . ja v a 2 s . c om*/ * * @param dn <code>String</code> LDAP context to list * * @return <code>Iterator</code> - LDAP search result * * @throws NamingException if the LDAP returns an error */ protected Iterator<NameClassPair> list(final String dn) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("list with the following parameters:"); this.logger.debug(" dn = " + dn); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<NameClassPair> results = null; LdapContext ctx = null; NamingEnumeration<NameClassPair> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.list(dn); results = NCP_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Performs AD-extension to LDAP query that performs recursive group lookup. * This Microsoft extension is explained in http://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx * * @return/*from ww w . j a v a 2s .c o m*/ * false if it appears that this search failed. * @see */ private boolean chainGroupLookup(String domainDN, String userDN, DirContext context, Set<GrantedAuthority> groups) throws NamingException { NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope() .returns("cn").search("(member:1.2.840.113556.1.4.1941:={0})", userDN); try { if (renum.hasMore()) { // http://ldapwiki.willeke.com/wiki/Active%20Directory%20Group%20Related%20Searches cites that // this filter search extension requires at least Win2K3 SP2. So if this didn't find anything, // fall back to the recursive search // TODO: this search alone might be producing the super set of the tokenGroups/objectSid based search in the stage 1. parseMembers(userDN, groups, renum); return true; } else { return false; } } finally { renum.close(); } }
From source file:edu.vt.middleware.ldap.AbstractLdap.java
/** * This will enumerate the names bounds to the specified context, along with * the objects bound to them. The resulting <code>Iterator</code> is a deep * copy of the original search results. See {@link * javax.naming.Context#listBindings(String)}. * * @param dn <code>String</code> LDAP context to list * * @return <code>Iterator</code> - LDAP search result * * @throws NamingException if the LDAP returns an error *//* w w w.ja v a2 s .c o m*/ protected Iterator<Binding> listBindings(final String dn) throws NamingException { if (this.logger.isDebugEnabled()) { this.logger.debug("listBindings with the following parameters:"); this.logger.debug(" dn = " + dn); if (this.logger.isTraceEnabled()) { this.logger.trace(" config = " + this.config.getEnvironment()); } } List<Binding> results = null; LdapContext ctx = null; NamingEnumeration<Binding> en = null; try { for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) { try { ctx = this.getContext(); en = ctx.listBindings(dn); results = BINDING_COPY_RESULT_HANDLER.process(null, en, this.config.getHandlerIgnoreExceptions()); break; } catch (NamingException e) { this.operationRetry(ctx, e, i); } } } finally { if (en != null) { en.close(); } if (ctx != null) { ctx.close(); } } return results.iterator(); }