}
// Get the environment properties (props) for creating initial
// context and specifying LDAP service provider parameters..
DirContext ctx = new InitialDirContext(props);
// Search the named object and all of its descendants.
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
// Retrieve the specified attributes only..
String[] al = new String[ attributeList.size() ];
attributeList.toArray(al);
constraints.setReturningAttributes(al);
String filter = USER_FILTER +"="+userId;
logger.info("LDAP search '" + filter + "' ");
// Search the context specified in the String object "base".
try {
NamingEnumeration<?> results = ctx.search(BASE, filter, constraints);
if (results.hasMoreElements()) {
logger.info("has returned results..\n");
user = new JSONObject();
// Since UID is unique across the entire directory,
// the search results should contain only one entry.
SearchResult sr = (SearchResult) results.next();
// we need the DN to authenticate the user
NameParser parser = ctx.getNameParser(BASE);
Name userDN = parser.parse(BASE);
if (userDN == (Name) null)
// This should not happen in theory
throw new NameNotFoundException();
else
userDN.addAll(parser.parse(sr.getName()));
user.put("userDN", userDN.toString());
// Get all available attribute types and their associated values.
// we can build a user object to return.
Attributes attributes = sr.getAttributes();
Attribute attr;
NamingEnumeration<?> ne;
// Iterate through the attributes.
//String json = "{";
for (NamingEnumeration<?> a = attributes.getAll(); a.hasMore();) {
attr = (Attribute)a.next();
//json = json + attr.getID() + ": { ";
String json = "";
ne = attr.getAll();
while (ne.hasMore()) {
json = json + ne.next(); // should only be one entry for the attributes we retreive + ", ";
}
//json = json + "\n";
user.put(attr.getID(), json);
}
//json = json + "}";
//user.put("jsonAttrib", json);
}
else {
logger.info("has returned no results..");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
ctx.close();
}
return user;
}