List of usage examples for javax.naming.directory Attribute getAll
NamingEnumeration<?> getAll() throws NamingException;
From source file:no.dusken.momus.ldap.LdapSyncer.java
private List<Person> getAllPersonsFromLdap() { final int[] activeCount = { 0 }; List<Person> persons = ldapTemplate.search("ou=Users", "(objectClass=person)", new AttributesMapper<Person>() { @Override//from w ww . j a v a 2 s .c om public Person mapFromAttributes(Attributes attributes) throws NamingException { Long id = Long.valueOf((String) attributes.get("uidNumber").get()); String firstName = attributes.get("givenName") != null ? (String) attributes.get("givenName").get() : ""; String fullName = attributes.get("cn") != null ? (String) attributes.get("cn").get() : ""; String userName = attributes.get("uid") != null ? (String) attributes.get("uid").get() : ""; String email = attributes.get("mail") != null ? (String) attributes.get("mail").get() : ""; String telephoneNumber = attributes.get("telephoneNumber") != null ? (String) attributes.get("telephoneNumber").get() : ""; boolean isActive = false; Attribute memberOf1 = attributes.get("memberOf"); if (memberOf1 != null) { NamingEnumeration<?> memberOf = memberOf1.getAll(); while (memberOf.hasMore()) { String group = (String) memberOf.next(); if (group.equalsIgnoreCase( "cn=Active,ou=Sections,ou=Org,ou=Groups,dc=studentmediene,dc=no")) { isActive = true; activeCount[0]++; break; } } } return new Person(id, userName, firstName, fullName, email, telephoneNumber, isActive); } }); logger.info("Number of users from LDAP: {}", persons.size()); logger.info("Number of active: {}", activeCount[0]); return persons; }
From source file:com.swdouglass.joid.server.DirectoryUserManagerImpl.java
@Override public User getUser(String username) { User user = null;//from w ww. ja va 2 s . c o m try { Attributes attrs = findAttributes(username, initialCtx); if (attrs != null) { if (log.isDebugEnabled()) { NamingEnumeration ne = attrs.getAll(); while (ne.hasMore()) { log.debug(ne.next()); } } // create the user, password very likely to be in binary form... user = new User(username, DirectoryUtil.getAttributeValue(attrs, PASSWORD_ATTRIBUTE_PROP, PASSWORD_ATTRIBUTE_PROP_DEFAULT)); // set the list of OpenIDs Attribute openIDattr = attrs .get(DirectoryUtil.getProperty(OPENID_OBJECTCLASS_PROP, OPENID_OBJECTCLASS_PROP_DEFAULT)); Enumeration e = openIDattr.getAll(); Set<String> openIDs = new HashSet<String>(); while (e.hasMoreElements()) { openIDs.add((String) e.nextElement()); } user.setOpenIDs(openIDs); } } catch (NamingException ex) { log.warn("Error in finding the userame=" + username, ex); } return user; }
From source file:org.springframework.ldap.core.LdapAttributes.java
/** * Returns a string representation of the object in LDIF format. * //from www . j a va 2s.c o m * @return {@link java.lang.String} formated to RFC2849 LDIF specifications. */ public String toString() { StringBuilder sb = new StringBuilder(); try { DistinguishedName dn = getDN(); if (!dn.toString().matches(SAFE_INIT_CHAR + SAFE_CHAR + "*")) { sb.append("dn:: " + new BASE64Encoder().encode(dn.toString().getBytes()) + "\n"); } else { sb.append("dn: " + getDN() + "\n"); } NamingEnumeration<Attribute> attributes = getAll(); while (attributes.hasMore()) { Attribute attribute = attributes.next(); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMore()) { Object value = values.next(); if (value instanceof String) sb.append(attribute.getID() + ": " + (String) value + "\n"); else if (value instanceof byte[]) sb.append(attribute.getID() + ":: " + new BASE64Encoder().encode((byte[]) value) + "\n"); else if (value instanceof URI) sb.append(attribute.getID() + ":< " + (URI) value + "\n"); else { sb.append(attribute.getID() + ": " + value + "\n"); } } } } catch (NamingException e) { log.error("Error formating attributes for output.", e); sb = new StringBuilder(); } return sb.toString(); }
From source file:com.surevine.chat.auth.GroupAuthorisationFilter.java
/** * Get a list of the members of a group, searching for the group using an * LDAP filter expression and scope./* ww w.j a v a 2 s.c o m*/ * * @param filter * LDAP search filter (see RFC2254) * @param scope * One of SearchControls.OBJECT_SCOPE, * SearchControls.ONELEVEL_SCOPE, or SearchControls.SUBTREE_SCOPE * (see javax.naming.directory.SearchControls) * @return List of usernames * @throws NamingException * @throws LdapException * On any LDAP error */ private Collection<String> getGroupMembers(final String groupName) throws NamingException { _logger.debug("Looking for members of " + groupName); String filter = "cn=" + groupName; Collection<String> memberList = new HashSet<String>(20); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> objects; DirContext ctx = getLdapConnection(); objects = ctx.search("ou=groups", filter, controls); while (objects.hasMore()) { SearchResult sr = (SearchResult) objects.next(); Attributes attributes = sr.getAttributes(); Attribute attribute = attributes.get("member"); if (attribute != null) { NamingEnumeration<?> valueEnum = attribute.getAll(); while (valueEnum.hasMore()) { String value = valueEnum.next().toString(); final String searchFor = "cn="; int start = value.indexOf(searchFor); int end = value.indexOf(',', start); if (start >= 0 && end >= 0) { String name = value.substring(start + searchFor.length(), end); _logger.debug(name + " is a chatter"); memberList.add(name); } } } } _logger.debug("Returning a total of " + memberList.size() + " chatters"); return memberList; }
From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java
/** * <p>Return a single value of an attribute from possibly multiple values, * grossly ignoring anything else. If there are no values, then * return an empty string.</p>/* ww w . j a va 2s .c om*/ * * @param attrs LDAP query results * @param attribute LDAP attribute we are interested in * @return a single value of the attribute */ private String getAttributeValue(Attributes attrs, int attribute) throws NamingException { NamingEnumeration values = null; String aValue = ""; if (!isAttribute(attribute)) return aValue; Attribute attrib = attrs.get(attributes[attribute]); if (attrib != null) { for (values = attrib.getAll(); values.hasMoreElements();) { aValue = (String) values.nextElement(); break; // take only the first attribute value } } return aValue; }
From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java
private List<String> getCustomerNames(Attributes attrs) throws NamingException { if (isDebugEnabled) { S_LOGGER.debug("Entering Method LDAPManagerImpl.getCustomerName(Attributes attrs"); }/*w ww . j a v a2 s.co m*/ List<String> customerNames = new ArrayList<String>(); Attribute attribute = attrs.get(ldapConfig.getCustomerNameAttribute()); if (attribute != null) { NamingEnumeration<?> all = attribute.getAll(); while (all.hasMoreElements()) { customerNames.add((String) all.nextElement()); } } return customerNames; }
From source file:de.tuttas.util.LDAPUtil.java
/** * Benutzer aus der LDAP Abfragen//w w w . j a v a 2 s . co m * * @param username Benutzername * @param password Kennwort * @return der Benutzer * @throws Exception Wenn etwas schief ging */ public LDAPUser authenticateJndi(String username, String password) throws Exception { // Anbindung ans LDAP Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, Config.getInstance().bindUser);//adminuser - User with special priviledge, dn user props.put(Context.SECURITY_CREDENTIALS, Config.getInstance().bindPassword);//dn user password try { context = new InitialDirContext(props); ctrls = new SearchControls(); ctrls.setReturningAttributes(new String[] { "description", "mail", "sn", "initials", "givenName", "memberOf", "userPrincipalName", "distinguishedName" }); ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE); } catch (NamingException ex) { Logger.getLogger(LDAPUtil.class.getName()).log(Level.SEVERE, null, ex); } NamingEnumeration<javax.naming.directory.SearchResult> answers = context .search(Config.getInstance().userContext, "(cn=" + username + ")", ctrls); Log.d("answers=" + answers); Log.d("answers=" + answers.hasMore()); if (!answers.hasMore()) { return null; } javax.naming.directory.SearchResult result = answers.nextElement(); try { for (NamingEnumeration ae = result.getAttributes().getAll(); ae.hasMore();) { Attribute attr = (Attribute) ae.next(); Log.d("attribute: " + attr.getID()); /* print each value */ for (NamingEnumeration e = attr.getAll(); e.hasMore(); System.out.println("value: " + e.next())) ; } } catch (NamingException e) { e.printStackTrace(); } String inititials = ""; if (result.getAttributes().get("initials") != null) { inititials = result.getAttributes().get("initials").getAll().next().toString(); } LDAPUser u; if (result.getAttributes().get("mail") == null) { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), "", inititials); } else { u = new LDAPUser(result.getAttributes().get("sn").getAll().next().toString(), result.getAttributes().get("givenName").getAll().next().toString(), result.getAttributes().get("mail").getAll().next().toString(), inititials); } String dName = result.getAttributes().get("distinguishedName").getAll().next().toString(); Log.d("dName=" + dName); if (dName.contains("OU=Lehrer")) { Log.d("Ich bin ein Lehrer"); u.setRole(Roles.toString(Roles.LEHRER)); } else { Log.d("Ich bin ein Schler"); u.setRole(Roles.toString(Roles.SCHUELER)); if (result.getAttributes().get("memberOf") != null) { String memberOf = result.getAttributes().get("memberOf").getAll().next().toString(); String courseName = memberOf.split(",")[0]; courseName = courseName.substring(courseName.indexOf("=") + 1); Log.d("Name der Klasse ist " + courseName); u.setCourse(courseName); } } String user = result.getNameInNamespace(); try { props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, Config.getInstance().ldaphost); props.put(Context.SECURITY_PRINCIPAL, user); props.put(Context.SECURITY_CREDENTIALS, password); context = new InitialDirContext(props); } catch (Exception e) { return null; } return u; }
From source file:org.apache.cloudstack.ldap.LdapUserManager.java
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException { String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute(); final SearchControls controls = new SearchControls(); controls.setSearchScope(_ldapConfiguration.getScope()); controls.setReturningAttributes(new String[] { attributeName }); NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(), generateGroupSearchFilter(groupName), controls); final List<LdapUser> users = new ArrayList<LdapUser>(); //Expecting only one result which has all the users if (result.hasMoreElements()) { Attribute attribute = result.nextElement().getAttributes().get(attributeName); NamingEnumeration<?> values = attribute.getAll(); while (values.hasMoreElements()) { String userdn = String.valueOf(values.nextElement()); try { users.add(getUserForDn(userdn, context)); } catch (NamingException e) { s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage()); }// w w w . j a va2 s . c o m } } Collections.sort(users); return users; }
From source file:org.apache.geode.internal.net.SocketCreator.java
/** * This method uses JNDI to look up an address in DNS and return its name * //from w w w .j a va 2s . c o m * @param addr * * @return the host name associated with the address or null if lookup isn't possible or there is * no host name for this address */ public static String reverseDNS(InetAddress addr) { byte[] addrBytes = addr.getAddress(); // reverse the address suitable for reverse lookup String lookup = ""; for (int index = addrBytes.length - 1; index >= 0; index--) { lookup = lookup + (addrBytes[index] & 0xff) + '.'; } lookup += "in-addr.arpa"; // System.out.println("Looking up: " + lookup); try { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(lookup, new String[] { "PTR" }); for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) { Attribute attr = (Attribute) ae.next(); for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { Object elem = vals.nextElement(); if ("PTR".equals(attr.getID()) && elem != null) { return elem.toString(); } } } ctx.close(); } catch (Exception e) { // ignored } return null; }
From source file:com.healthcit.cacure.businessdelegates.LdapUserManager.java
public Set<UserCredentials> loadUsersByRole(RoleCode roleCode) { Role role = roleDao.getByRoleCode(roleCode); String groupFilter = createGroupFilter(roleCode); Set<UserCredentials> userCredentials = new HashSet<UserCredentials>(); try {// w ww . j a v a 2s . co m Attributes attrs = contextSource.getReadOnlyContext().getAttributes(groupFilter); Attribute memAttr = attrs.get(Constants.LDAP_GROUP_UNIQUE_MEMBER); NamingEnumeration<?> elements = memAttr.getAll(); while (elements.hasMoreElements()) { DistinguishedName dn = new DistinguishedName((String) elements.nextElement()); String userName = dn.getValue(Constants.LDAP_UID); DirContextOperations dir = searchForUser(userName); String email = dir.getStringAttribute("mail"); UserCredentials user = getUserFromDatabase(userName); user.setEmail(email); userCredentials.add(user); } } catch (NamingException e) { log.error(e.getMessage()); } return userCredentials; }