List of usage examples for javax.naming NamingEnumeration close
public void close() throws NamingException;
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
private String performRoleSearch(String location, String roleName) { String val = null; try {/*from w ww.j av a 2 s . c o m*/ 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:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java
/** * @see org.apache.archiva.redback.users.ldap.ctl.LdapController#userExists(String, javax.naming.directory.DirContext) *///from ww w. ja v a2s . c om public boolean userExists(String key, DirContext context) throws LdapControllerException { NamingEnumeration<SearchResult> results = null; try { results = searchUsers(key, context); return results.hasMoreElements(); } catch (NamingException e) { throw new LdapControllerException("Error searching for the existence of user: " + key, e); } finally { if (results != null) { try { results.close(); } catch (NamingException e) { log.warn("Error closing search results", e); } } } }
From source file:com.googlecode.fascinator.authentication.custom.ldap.CustomLdapAuthenticationHandler.java
/** * Tries to find the value(s) of the given attribute. Note that this method * uses all search results.//from w ww.jav a 2s.c o m * * @param username * a username * @param attrName * the name of the attribute to find * @return a list of values for the attribute, or an empty list */ public List<String> getAllAttrs(String username, String attrName) { List<String> resultList = new ArrayList<String>(); try { DirContext dc = new InitialDirContext(env); NamingEnumeration<SearchResult> ne = performLdapSearch(username, dc); while (ne.hasMore()) { resultList.add(getAttrValue(attrName, ne.next())); } ne.close(); dc.close(); } catch (NamingException ne) { log.warn("Failed LDAP lookup getAllAttrs" + username, ne); } log.trace("getAllAttrs search result: " + resultList); if (log.isTraceEnabled()) { log.trace("getAllAttrs search result: " + resultList); } return resultList; }
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchGroupResolver.java
/** * Resolves groups by querying the LDAP directory. * /*from w ww . ja v a2s . co m*/ * Never return null in any case. Returns empty list instead. * * @param ctx * @param dn * @param username * @return List of authorities (not null) * @see jp.ikedam.jenkins.plugins.ldap_sasl.GroupResolver#resolveGroup(javax.naming.ldap.LdapContext, java.lang.String, java.lang.String) */ @Override public List<GrantedAuthority> resolveGroup(LdapContext ctx, String dn, String username) { List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); Logger logger = getLogger(); if (dn == null) { logger.warning("Group cannot be resolved: DN of the user is not resolved!"); return authorities; } try { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); logger.fine(String.format("Searching groups base=%s, dn=%s", getSearchBase(), dn)); NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "", getGroupSearchQuery(dn), searchControls); while (entries.hasMore()) { SearchResult entry = entries.next(); String groupName = entry.getAttributes().get("cn").get().toString(); if (getPrefix() != null) { groupName = getPrefix() + groupName; } authorities.add(new GrantedAuthorityImpl(groupName)); logger.fine(String.format("group: %s", groupName)); } entries.close(); } catch (NamingException e) { logger.log(Level.WARNING, "Failed to search groups", e); } return authorities; }
From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java
private void logAttributes(String location, Attributes attrs) throws NamingException { NamingEnumeration<? extends Attribute> values = attrs.getAll(); try {//from w w w . ja v a 2 s . c o m while ((values != null) && values.hasMore()) { Attribute aValue = values.next(); String id = aValue.getID(); Collection<?> valsList = Collections.list(aValue.getAll()); logger.trace(location + "[" + id + "]: " + valsList); } } finally { values.close(); } }
From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchUserDnResolver.java
/** * Resolve the user DN by querying the LDAP directory. * /*from www. j a va2s. c o m*/ * @param ctx LDAP context, already authenticated. * @param username the username the user authenticated with. * * @return the DN of the user. * @see jp.ikedam.jenkins.plugins.ldap_sasl.UserDnResolver#getUserDn(javax.naming.ldap.LdapContext, java.lang.String) */ @Override public String getUserDn(LdapContext ctx, String username) { Logger logger = getLogger(); if (StringUtils.isBlank(getSearchQueryTemplate())) { // not configured. logger.severe("Not configured."); return null; } try { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); logger.fine(String.format("Searching users base=%s, username=%s", getSearchBase(), username)); String query = expandUsername(getSearchQueryTemplate(), username); NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "", query, searchControls); if (!entries.hasMore()) { // no entry. logger.severe(String.format("User not found: %s", username)); return null; } String userDn = entries.next().getNameInNamespace(); if (entries.hasMore()) { // more than one entry. logger.severe(String.format("User found more than one: %s", username)); return null; } entries.close(); return userDn; } catch (NamingException e) { logger.log(Level.SEVERE, "Failed to search a user", e); return null; } }
From source file:it.infn.ct.security.utilities.LDAPUtils.java
public static LDAPUser findUserByMail(String mail) { NamingEnumeration results = null; DirContext ctx = null;/*w ww . j a va 2 s . co m*/ LDAPUser user = null; try { ctx = getContext(); SearchControls controls = new SearchControls(); String retAttrs[] = { "cn" }; controls.setReturningAttributes(retAttrs); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); ResourceBundle rb = ResourceBundle.getBundle("ldap"); results = ctx.search(rb.getString("peopleRoot"), "(mail=" + mail + ")", controls); if (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); user = new LDAPUser(); if (attributes.get("cn") != null) user = getUser((String) attributes.get("cn").get()); } } catch (NameNotFoundException ex) { _log.error(ex); } catch (NamingException e) { _log.error(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 user; }
From source file:com.globalsight.everest.usermgr.UserLdapHelper.java
/** * Get the company names from a NamingEnumeration *///from ww w .j av a2s . co m static String[] getCompanyNamesFromSearchResults(NamingEnumeration p_searchResults) throws NamingException { // use a set so duplicates are not saved Set companyNames = new TreeSet(); while (p_searchResults.hasMoreElements()) { String cName = null; Object searchResultObj = p_searchResults.nextElement(); if (searchResultObj instanceof SearchResult) { SearchResult tempSearchResult = (SearchResult) searchResultObj; Attributes entry = tempSearchResult.getAttributes(); cName = getSingleAttributeValue(entry.get(LDAP_ATTR_COMPANY)); } if (cName != null && cName.trim().length() > 0) { // adds it to the set // if it already exists just returns (NOP) companyNames.add(cName); } } p_searchResults.close(); String[] cns = new String[companyNames.size()]; return (String[]) companyNames.toArray(cns); }
From source file:es.udl.asic.user.OpenLdapDirectoryProvider.java
private boolean getUserInf(UserEdit edit, String filter) { String id = null;/*from w ww .ja v a2 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:com.aurel.track.util.LdapUtil.java
/** * Returns the CN (common name) for a given login name * //from ww w . j a v a 2s . co m * @param loginName * the loginName of the user * @return CN as a String(if found), or null (else) */ private static String getCn(TSiteBean siteBean, String loginName) throws NamingException { String keyDn = null; DirContext ctx = getInitialContext(siteBean.getLdapServerURL(), siteBean.getLdapBindDN(), siteBean.getLdapBindPassword()); if (ctx != null) { SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search for the user-id String searchStr = "(" + siteBean.getLdapAttributeLoginName() + "=" + loginName + ")"; NamingEnumeration<SearchResult> answer = ctx.search("", searchStr, ctls); if (answer.hasMore()) { // retrieve the CN SearchResult sr = answer.next(); keyDn = sr.getName();// + "," + ctx.getNameInNamespace(); LOGGER.debug("Name = " + keyDn); String nameInNamespace = ctx.getNameInNamespace(); LOGGER.debug("Name in namespace " + nameInNamespace); if (nameInNamespace != null && nameInNamespace.trim().length() > 0) { keyDn += "," + ctx.getNameInNamespace(); } LOGGER.debug("entry found for LDAP-search >" + searchStr + "<: dn= >" + keyDn + "<!"); answer.close(); // wo don't need more answers } else { LOGGER.debug("no entry found for LDAP-search >" + searchStr + "<!"); } ctx.close(); } return keyDn; }