List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:net.spfbl.core.Reverse.java
public static TreeSet<String> getAddressSet(String hostname) throws NamingException { if ((hostname = Domain.normalizeHostname(hostname, false)) == null) { return null; } else {//from ww w. ja v a 2 s . c om TreeSet<String> ipSet = new TreeSet<String>(); Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" }); if (attributesA != null) { Enumeration enumerationA = attributesA.getAll(); while (enumerationA.hasMoreElements()) { Attribute attributeA = (Attribute) enumerationA.nextElement(); NamingEnumeration enumeration = attributeA.getAll(); while (enumeration.hasMoreElements()) { String address = (String) enumeration.next(); if (SubnetIPv4.isValidIPv4(address)) { address = SubnetIPv4.normalizeIPv4(address); ipSet.add(address); } } } } Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" }); if (attributesAAAA != null) { Enumeration enumerationAAAA = attributesAAAA.getAll(); while (enumerationAAAA.hasMoreElements()) { Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement(); NamingEnumeration enumeration = attributeAAAA.getAll(); while (enumeration.hasMoreElements()) { String address = (String) enumeration.next(); if (SubnetIPv6.isValidIPv6(address)) { address = SubnetIPv6.normalizeIPv6(address); ipSet.add(address); } } } } return ipSet; } }
From source file:org.pentaho.di.trans.steps.mailvalidator.MailValidation.java
private static ArrayList<String> getMX(String hostName) throws NamingException { // Perform a DNS lookup for MX records in the domain Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); DirContext ictx = new InitialDirContext(env); Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" }); Attribute attr = attrs.get("MX"); // if we don't have an MX record, try the machine itself if ((attr == null) || (attr.size() == 0)) { attrs = ictx.getAttributes(hostName, new String[] { "A" }); attr = attrs.get("A"); if (attr == null) { throw new NamingException(BaseMessages.getString(PKG, "MailValidator.NoMatchName", hostName)); }/*from w w w .j a v a 2 s.c o m*/ } // Huzzah! we have machines to try. Return them as an array list // NOTE: We SHOULD take the preference into account to be absolutely // correct. This is left as an exercise for anyone who cares. ArrayList<String> res = new ArrayList<String>(); NamingEnumeration<?> en = attr.getAll(); while (en.hasMore()) { String x = (String) en.next(); String[] f = x.split(" "); if (f[1].endsWith(".")) { f[1] = f[1].substring(0, (f[1].length() - 1)); } res.add(f[1]); } return res; }
From source file:org.codehaus.groovy.grails.plugins.springsecurity.ldap.GrailsLdapRoleMapper.java
/** * {@inheritDoc}// ww w.j av a2 s . c o m * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) */ public Object mapFromAttributes(final Attributes attributes) throws NamingException { Attribute roleAttr = attributes.get(_groupRoleAttributeName); NamingEnumeration<?> ne = roleAttr.getAll(); // assert ne.hasMore(); Object group = ne.next(); String role = group.toString(); return new GrantedAuthorityImpl(_rolePrefix + role.toUpperCase()); }
From source file:de.interseroh.report.test.security.LdapServerTest.java
@Test public void testJndiSun() throws NamingException { Hashtable<String, String> contextParams = new Hashtable<String, String>(); contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389"); contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP); contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP); contextParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); DirContext dirContext = new InitialDirContext(contextParams); Attributes attributes = dirContext.getAttributes("", new String[] { "namingContexts" }); Attribute attribute = attributes.get("namingContexts"); NamingEnumeration<?> all = attribute.getAll(); while (all.hasMore()) { String next = (String) all.next(); logger.info(next);// w w w. j ava 2 s . c o m } }
From source file:cyrille.jndi.LdapTest.java
@Test public void test() throws Exception { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://localhost:389"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system"); env.put(Context.SECURITY_CREDENTIALS, "secret"); DirContext dirContext = new InitialDirContext(env); Attributes attributes = dirContext.getAttributes("uid=aeinstein,ou=Users,dc=example,dc=com"); for (NamingEnumeration<Attribute> attributesEnumeration = (NamingEnumeration<Attribute>) attributes .getAll(); attributesEnumeration.hasMore();) { Attribute attribute = attributesEnumeration.next(); System.out.print(attribute.getID() + "="); for (NamingEnumeration<?> attributeValues = attribute.getAll(); attributeValues.hasMore();) { Object value = attributeValues.next(); if (value instanceof byte[] && "userpassword".equals(attribute.getID())) { byte[] bytes = (byte[]) value; System.out.print(new String(bytes) + ", "); } else { System.out.print(value + ", "); }/* w ww . j a va 2 s . c o m*/ } System.out.println(); } }
From source file:org.apache.james.user.ldap.ReadOnlyLDAPGroupRestriction.java
/** * Extracts the DNs for members of the group with the given LDAP context * attributes. This is achieved by extracting all the values of the LDAP * attribute, with name equivalent to the field value * {@link #memberAttribute}, from the attributes collection. * * @param groupAttributes The attributes taken from the group's LDAP context. * @return A collection of distinguished-names for the users belonging to * the group with the specified attributes. * @throws NamingException Propagated from underlying LDAP communication layer. *//*from ww w. jav a2 s. c o m*/ private Collection<String> extractMembers(Attributes groupAttributes) throws NamingException { Collection<String> result = new ArrayList<String>(); Attribute members = groupAttributes.get(memberAttribute); NamingEnumeration<?> memberDNs = members.getAll(); while (memberDNs.hasMore()) result.add(memberDNs.next().toString()); return result; }
From source file:org.sonar.plugins.ldap.LdapAutodiscovery.java
List<LdapSrvRecord> getLdapServers(DirContext context, String domain) throws NamingException { Attributes lSrvAttrs = context.getAttributes("dns:/_ldap._tcp." + domain, new String[] { "srv" }); Attribute serversAttribute = lSrvAttrs.get("srv"); NamingEnumeration<?> lEnum = serversAttribute.getAll(); SortedSet<LdapSrvRecord> result = new TreeSet<>(); while (lEnum.hasMore()) { String srvRecord = (String) lEnum.next(); // priority weight port target String[] srvData = srvRecord.split(" "); int priority = NumberUtils.toInt(srvData[0]); int weight = NumberUtils.toInt(srvData[1]); String port = srvData[2]; String target = srvData[3]; if (target.endsWith(".")) { target = target.substring(0, target.length() - 1); }/*w ww .j a va 2 s . c o m*/ String server = "ldap://" + target + ":" + port; result.add(new LdapSrvRecord(server, priority, weight)); } return new ArrayList<>(result); }
From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java
/** * Ensure able to obtain credentials.// w w w . j a v a 2s . com */ 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:jenkins.security.plugins.ldap.FromUserRecordLDAPGroupMembershipStrategy.java
@Override public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails ldapUser) { List<GrantedAuthority> result = new ArrayList<GrantedAuthority>(); Attributes attributes = ldapUser.getAttributes(); final String attributeName = getAttributeName(); Attribute attribute = attributes == null ? null : attributes.get(attributeName); if (attribute != null) { try {// www .jav a 2 s. co m for (Object value : Collections.list(attribute.getAll())) { String groupName = String.valueOf(value); try { LdapName dn = new LdapName(groupName); groupName = String.valueOf(dn.getRdn(dn.size() - 1).getValue()); } catch (InvalidNameException e) { LOGGER.log(Level.FINEST, "Expected a Group DN but found: {0}", groupName); } result.add(new GrantedAuthorityImpl(groupName)); } } catch (NamingException e) { LogRecord lr = new LogRecord(Level.FINE, "Failed to retrieve member of attribute ({0}) from LDAP user details"); lr.setThrown(e); lr.setParameters(new Object[] { attributeName }); LOGGER.log(lr); } } return result.toArray(new GrantedAuthority[result.size()]); }
From source file:org.apereo.portal.groups.smartldap.SimpleAttributesMapper.java
public Object mapFromAttributes(Attributes attr) { // Assertions. if (keyAttributeName == null) { String msg = "The property 'keyAttributeName' must be set."; throw new IllegalStateException(msg); }//from w w w. j av a 2 s. com if (groupNameAttributeName == null) { String msg = "The property 'groupNameAttributeName' must be set."; throw new IllegalStateException(msg); } if (membershipAttributeName == null) { String msg = "The property 'membershipAttributeName' must be set."; throw new IllegalStateException(msg); } if (log.isDebugEnabled()) { String msg = "SimpleAttributesMapper.mapFromAttributes() :: settings: keyAttributeName='" + keyAttributeName + "', groupNameAttributeName='" + groupNameAttributeName + "', groupNameAttributeName='" + groupNameAttributeName + "'"; log.debug(msg); } LdapRecord rslt; try { String key = (String) attr.get(keyAttributeName).get(); String groupName = (String) attr.get(groupNameAttributeName).get(); IEntityGroup g = new EntityTestingGroupImpl(key, IPerson.class); g.setCreatorID("System"); g.setName(groupName); g.setDescription(GROUP_DESCRIPTION); List<String> membership = new LinkedList<String>(); Attribute m = attr.get(membershipAttributeName); if (m != null) { for (Enumeration<?> en = m.getAll(); en.hasMoreElements();) { membership.add((String) en.nextElement()); } } rslt = new LdapRecord(g, membership); if (log.isDebugEnabled()) { StringBuilder msg = new StringBuilder(); msg.append("Record Details:").append("\n\tkey=").append(key).append("\n\tgroupName=") .append(groupName).append("\n\tmembers:"); for (String s : membership) { msg.append("\n\t\t").append(s); } log.debug(msg.toString()); } } catch (Throwable t) { log.error("Error in SimpleAttributesMapper", t); String msg = "SimpleAttributesMapper failed to create a LdapRecord " + "from the specified Attributes: " + attr; throw new RuntimeException(msg, t); } return rslt; }