List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:com.surevine.ldap2alfresco.ProfileFieldTextConverter.java
/** * Encode some attributes as JSON./*from w ww. jav a 2 s. c o m*/ * @param json The JSON object to insert into * @param attributes Collection of attributes */ public void toJson(final JSONObject json, final Attributes attributes) { Attribute attribute = attributes.get(attributeLabel); if (attribute == null) { LOGGER.debug("Missing attribute: " + attributeLabel); // just put an empty entry into the JSON try { if (allowMultiples) { json.put(jsonLabel, new JSONArray()); } else { json.put(jsonLabel, ""); } } catch (JSONException e) { logException(Level.ERROR, e); } return; } int numValues = attribute.size(); if (numValues == 0) { LOGGER.error("Attribute " + attributeLabel + " contains no values"); return; } try { if (allowMultiples) { JSONArray values = new JSONArray(); NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); if (value != null && value.length() > MAX_STRING_LENGTH) { value = value.substring(0, MAX_STRING_LENGTH - 1); } values.put(value); } json.put(jsonLabel, values); } else { // expecting only one value if (numValues != 1) { LOGGER.error("Expected single value in attribute " + attributeLabel + ", found " + numValues); return; } String value = attribute.get().toString(); if (value != null && value.length() > MAX_STRING_LENGTH) { value = value.substring(0, MAX_STRING_LENGTH - 1); } json.put(jsonLabel, value); } } catch (NamingException e) { logException(Level.ERROR, e); return; } catch (JSONException e) { logException(Level.ERROR, e); return; } }
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 v a 2s. 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:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java
/** * Ensure able to obtain credentials.//w w w . j a va 2s . c om */ public void testObtainCredentials() throws Exception { final Charset ASCII = Charset.forName("ASCII"); // Calculate the expected credential String expectedRaw = "daniel:officefloor:password"; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(expectedRaw.getBytes(ASCII)); byte[] expectedBytes = digest.digest(); String expectedCredentials = Base64.encodeBase64String(expectedBytes).trim(); // Obtain the context DirContext context = this.ldap.getDirContext(); // Obtain the People context DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net"); assertNotNull("Should have People context", people); // Search for person NamingEnumeration<SearchResult> results = people.search("", "(&(objectClass=inetOrgPerson)(uid=daniel))", null); assertTrue("Expecting to find daniel entry", results.hasMore()); SearchResult result = results.next(); assertFalse("Should only have the daniel entry", results.hasMore()); // Obtain the digest MD5 credentials for Daniel String digestMd5Credential = null; Attributes attributes = result.getAttributes(); Attribute passwordAttribute = attributes.get("userPassword"); for (NamingEnumeration<?> enumeration = passwordAttribute.getAll(); enumeration.hasMore();) { byte[] credentials = (byte[]) enumeration.next(); String text = new String(credentials, ASCII); // Determine if MD5 credential if (text.toUpperCase().startsWith("{MD5}")) { // Found MD5 credential digestMd5Credential = text.substring("{MD5}".length()); } } assertNotNull("Must have digest MD5 credential", digestMd5Credential); // Ensure correct credentials assertEquals("Incorrect DIGEST MD5 credentials", expectedCredentials, digestMd5Credential); }
From source file:com.swdouglass.joid.server.DirectoryUserManagerImpl.java
private Attributes findAttributes(String inUsername, InitialDirContext ctx) throws NamingException { SearchControls ctls = new SearchControls(); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // perform the search NamingEnumeration results = ctx.search("", "(uid={0})", new Object[] { inUsername }, ctls); Attributes outAttrs = null;/* w w w . ja v a 2 s. c om*/ if (results.hasMore()) { log.info("Found username \"" + inUsername + "\" in directory"); outAttrs = ((SearchResult) results.next()).getAttributes(); } else { log.info("Could NOT find username \"" + inUsername + "\" in directory"); } return outAttrs; }
From source file:com.adito.activedirectory.PagedResultTemplate.java
private void mapResults(PagedResultMapper mapper, NamingEnumeration<SearchResult> results) throws NamingException { while (results != null && results.hasMore()) { SearchResult searchResult = results.next(); String dn = searchResult.getNameInNamespace(); try {// w ww . j a v a 2 s . co m if (isDnValid(dn)) { if (logger.isDebugEnabled()) { logger.debug("Included result " + dn); } mapper.mapSearchResult(searchResult); } else { if (logger.isDebugEnabled()) { logger.debug("Excluding result " + dn); } } } catch (Exception e) { mapper.processSearchResultException(searchResult, e); } } }
From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java
/** * Ensure able to obtain the roles.// w ww . jav a 2 s . co m */ public void testObtainRoles() throws Exception { // Obtain the context DirContext context = this.ldap.getDirContext(); // Obtain the People context DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net"); assertNotNull("Should have People context", people); // Search for person NamingEnumeration<SearchResult> personResults = people.search("", "(&(objectClass=inetOrgPerson)(uid=daniel))", null); assertTrue("Expecting to find daniel entry", personResults.hasMore()); SearchResult daniel = personResults.next(); assertFalse("Should only have the daniel entry", personResults.hasMore()); // Obtain the Groups context DirContext groups = (DirContext) context.lookup("ou=Groups,dc=officefloor,dc=net"); assertNotNull("Should have Groups context", groups); // Search for groups containing daniel String danielDn = daniel.getNameInNamespace(); NamingEnumeration<SearchResult> groupResults = groups.search("", "(&(objectClass=groupOfNames)(member=" + danielDn + "))", null); // Obtain the listing of roles for daniel List<String> roles = new ArrayList<String>(2); for (; groupResults.hasMore();) { SearchResult group = groupResults.next(); // Obtain the role from the group String role = (String) group.getAttributes().get("ou").get(); // Add role to listing roles.add(role); } // Ensure the correct roles assertEquals("Incorrect number of roles", 2, roles.size()); assertTrue("Missing user role", roles.contains("developer")); assertTrue("Missing developer role", roles.contains("committer")); }
From source file:com.hs.mail.security.login.JndiLoginModule.java
@SuppressWarnings("unchecked") protected boolean authenticate(String username, String password) throws Exception { DirContext context = null;//from w w w .j av a2 s .com try { context = open(); searchFilterFormat.format(new String[] { username }); SearchControls constraints = new SearchControls(); constraints.setSearchScope(subtree ? SearchControls.SUBTREE_SCOPE : SearchControls.ONELEVEL_SCOPE); if (returnAttribute != null) { String[] attribs = StringUtils.split(returnAttribute, ","); constraints.setReturningAttributes(attribs); } NamingEnumeration ne = context.search(base, searchFilter, constraints); if (ne == null || !ne.hasMore()) { return false; } SearchResult sr = (SearchResult) ne.next(); if (ne.hasMore()) { // Ignore for now } // Check the credentials by binding to server if (bindUser(context, sr.getNameInNamespace(), password)) { return true; } else { return true; } } catch (NamingException e) { close(context); return false; } }
From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java
/** * displayName and mail are returned always, the map allows us to support * getting arbitrary properties in the future, hopefully *///from www. j a va 2 s .co m public Map<String, String> bind(String loginName, String password) throws Exception { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, ldapUrl); env.put(Context.SECURITY_AUTHENTICATION, "simple"); LdapContext ctx = null; if (activeDirectoryDomain != null) { // we are using Active Directory Control[] controls = new Control[] { control }; ctx = new InitialLdapContext(env, controls); logger.debug("Active Directory LDAP context initialized"); ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName); ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); // javax.naming.AuthenticationException ctx.reconnect(controls); logger.debug("Active Directory LDAP bind successful"); } else { // standard LDAP env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase); env.put(Context.SECURITY_CREDENTIALS, password); ctx = new InitialLdapContext(env, null); logger.debug("Standard LDAP bind successful"); } SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(returningAttributes); NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc); while (results.hasMoreElements()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = sr.getAttributes(); logger.debug("attributes: " + attrs); Map<String, String> map = new HashMap<String, String>(returningAttributes.length); for (String key : returningAttributes) { Attribute attr = attrs.get(key); if (attr != null) { map.put(key, (String) attr.get()); } } return map; // there should be only one anyway } // if we reached here, there was no search result throw new Exception("no results returned from ldap"); }
From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java
public void collect() { // Setup initial LDAP properties Properties env = new Properties(); Properties props = getProperties(); // Set our default factory name if one is not given String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY); if (factoryName == null) { env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); }/* ww w . j a v a 2s . c o m*/ // Set the LDAP url if (isSSL()) { env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName()); env.put(Context.SECURITY_PROTOCOL, "ssl"); } String providerUrl = "ldap://" + getHostname() + ":" + getPort(); env.setProperty(Context.PROVIDER_URL, providerUrl); // For log track setSource(providerUrl); // Follow referrals automatically env.setProperty(Context.REFERRAL, "follow"); // Base DN String baseDN = props.getProperty(PROP_BASEDN); if (baseDN == null) { setErrorMessage("No Base DN given, refusing login"); setAvailability(false); return; } // Search filter String filter = props.getProperty(PROP_FILTER); // Load any information we may need to bind String bindDN = props.getProperty(PROP_BINDDN); String bindPW = props.getProperty(PROP_BINDPW); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } if (log.isDebugEnabled()) { log.debug("Using LDAP environment: " + env); } try { startTime(); InitialLdapContext ctx = new InitialLdapContext(env, null); endTime(); setAvailability(true); // If a search filter is specified, run the search and return the // number of matches as a metric if (filter != null) { log.debug("Using LDAP filter=" + filter); NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls()); long matches = 0; while (answer.hasMore()) { matches++; answer.next(); } setValue("NumberofMatches", matches); } } catch (Exception e) { setAvailability(false); if (log.isDebugEnabled()) { log.debug("LDAP check failed: " + e, e); } setErrorMessage("LDAP check failed: " + e); } }
From source file:jndi.view.JndiView.java
/** * @param path/*from w w w . ja va 2 s . c om*/ * the path to browse * @return {@link List} of {@link JndiEntry}s * @throws NamingException * on exception */ private List<JndiEntry> browse(final String path) throws NamingException { final JndiCallback<List<JndiEntry>> contextCallback = new JndiCallback<List<JndiEntry>>() { @Override public List<JndiEntry> doInContext(final Context context) throws NamingException { if (JAVA_GLOBAL.equals(path)) { // Do a little trick to handle "java:global" final NamingEnumeration<Binding> root = context.listBindings(""); Context javaGlobalContext = null; while (root.hasMore()) { final Binding binding = root.next(); if (JAVA_GLOBAL.equals(binding.getName())) { final Object obj = binding.getObject(); if (obj instanceof Context) { javaGlobalContext = (Context) obj; } break; } } if (javaGlobalContext != null) { return examineBindings(javaGlobalContext, path, javaGlobalContext.listBindings("")); } logger.warning("Unable to browse \"" + JAVA_GLOBAL + "\" namespace!"); return emptyList(); } return examineBindings(context, path, context.listBindings(path)); } }; return jndiTemplate.execute(contextCallback); }