use of javax.naming.NamingEnumeration in project hadoop by apache.
the class LdapGroupsMapping method doGetGroups.
/**
* Perform LDAP queries to get group names of a user.
*
* Perform the first LDAP query to get the user object using the user's name.
* If one-query is enabled, retrieve the group names from the user object.
* If one-query is disabled, or if it failed, perform the second query to
* get the groups.
*
* @param user user name
* @return a list of group names for the user. If the user can not be found,
* return an empty string array.
* @throws NamingException if unable to get group names
*/
List<String> doGetGroups(String user, int goUpHierarchy) throws NamingException {
DirContext c = getDirContext();
// Search for the user. We'll only ever need to look at the first result
NamingEnumeration<SearchResult> results = c.search(baseDN, userSearchFilter, new Object[] { user }, SEARCH_CONTROLS);
// return empty list if the user can not be found.
if (!results.hasMoreElements()) {
if (LOG.isDebugEnabled()) {
LOG.debug("doGetGroups(" + user + ") returned no groups because the " + "user is not found.");
}
return new ArrayList<String>();
}
SearchResult result = results.nextElement();
List<String> groups = null;
if (useOneQuery) {
try {
/**
* For Active Directory servers, the user object has an attribute
* 'memberOf' that represents the DNs of group objects to which the
* user belongs. So the second query may be skipped.
*/
Attribute groupDNAttr = result.getAttributes().get(memberOfAttr);
if (groupDNAttr == null) {
throw new NamingException("The user object does not have '" + memberOfAttr + "' attribute." + "Returned user object: " + result.toString());
}
groups = new ArrayList<String>();
NamingEnumeration groupEnumeration = groupDNAttr.getAll();
while (groupEnumeration.hasMore()) {
String groupDN = groupEnumeration.next().toString();
groups.add(getRelativeDistinguishedName(groupDN));
}
} catch (NamingException e) {
// If the first lookup failed, fall back to the typical scenario.
LOG.info("Failed to get groups from the first lookup. Initiating " + "the second LDAP query using the user's DN.", e);
}
}
if (groups == null || groups.isEmpty() || goUpHierarchy > 0) {
groups = lookupGroup(result, c, goUpHierarchy);
}
if (LOG.isDebugEnabled()) {
LOG.debug("doGetGroups(" + user + ") returned " + groups);
}
return groups;
}
use of javax.naming.NamingEnumeration in project zeppelin by apache.
the class GetUserList method getUserList.
/**
* function to extract users from LDAP
*/
public List<String> getUserList(JndiLdapRealm r, String searchText) {
List<String> userList = new ArrayList<>();
String userDnTemplate = r.getUserDnTemplate();
String[] userDn = userDnTemplate.split(",", 2);
String userDnPrefix = userDn[0].split("=")[0];
String userDnSuffix = userDn[1];
JndiLdapContextFactory CF = (JndiLdapContextFactory) r.getContextFactory();
try {
LdapContext ctx = CF.getSystemLdapContext();
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
String[] attrIDs = { userDnPrefix };
constraints.setReturningAttributes(attrIDs);
NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)", constraints);
while (result.hasMore()) {
Attributes attrs = ((SearchResult) result.next()).getAttributes();
if (attrs.get(userDnPrefix) != null) {
String currentUser = attrs.get(userDnPrefix).toString();
userList.add(currentUser.split(":")[1].trim());
}
}
} catch (Exception e) {
LOG.error("Error retrieving User list from Ldap Realm", e);
}
LOG.info("UserList: " + userList);
return userList;
}
use of javax.naming.NamingEnumeration in project jetty.project by eclipse.
the class TestJNDI method testIt.
@Test
public void testIt() throws Exception {
//set up some classloaders
Thread currentThread = Thread.currentThread();
ClassLoader currentLoader = currentThread.getContextClassLoader();
ClassLoader childLoader1 = new URLClassLoader(new URL[0], currentLoader);
ClassLoader childLoader2 = new URLClassLoader(new URL[0], currentLoader);
try {
//Uncomment to aid with debug
/*
javaRootURLContext.getRoot().addListener(new NamingContext.Listener()
{
public void unbind(NamingContext ctx, Binding binding)
{
System.err.println("java unbind "+binding+" from "+ctx.getName());
}
public Binding bind(NamingContext ctx, Binding binding)
{
System.err.println("java bind "+binding+" to "+ctx.getName());
return binding;
}
});
localContextRoot.getRoot().addListener(new NamingContext.Listener()
{
public void unbind(NamingContext ctx, Binding binding)
{
System.err.println("local unbind "+binding+" from "+ctx.getName());
}
public Binding bind(NamingContext ctx, Binding binding)
{
System.err.println("local bind "+binding+" to "+ctx.getName());
return binding;
}
});
*/
//Set up the tccl before doing any jndi operations
currentThread.setContextClassLoader(childLoader1);
InitialContext initCtx = new InitialContext();
//Test we can lookup the root java: naming tree
Context sub0 = (Context) initCtx.lookup("java:");
assertNotNull(sub0);
//already be bound
try {
Context sub1 = sub0.createSubcontext("comp");
fail("Comp should already be bound");
} catch (NameAlreadyBoundException e) {
//expected exception
}
//check bindings at comp
Context sub1 = (Context) initCtx.lookup("java:comp");
assertNotNull(sub1);
Context sub2 = sub1.createSubcontext("env");
assertNotNull(sub2);
initCtx.bind("java:comp/env/rubbish", "abc");
assertEquals("abc", initCtx.lookup("java:comp/env/rubbish"));
//check binding LinkRefs
LinkRef link = new LinkRef("java:comp/env/rubbish");
initCtx.bind("java:comp/env/poubelle", link);
assertEquals("abc", initCtx.lookup("java:comp/env/poubelle"));
//check binding References
StringRefAddr addr = new StringRefAddr("blah", "myReferenceable");
Reference ref = new Reference(java.lang.String.class.getName(), addr, MyObjectFactory.class.getName(), null);
initCtx.bind("java:comp/env/quatsch", ref);
assertEquals(MyObjectFactory.myString, initCtx.lookup("java:comp/env/quatsch"));
//test binding something at java:
Context sub3 = initCtx.createSubcontext("java:zero");
initCtx.bind("java:zero/one", "ONE");
assertEquals("ONE", initCtx.lookup("java:zero/one"));
//change the current thread's classloader to check distinct naming
currentThread.setContextClassLoader(childLoader2);
Context otherSub1 = (Context) initCtx.lookup("java:comp");
assertTrue(!(sub1 == otherSub1));
try {
initCtx.lookup("java:comp/env/rubbish");
fail("env should not exist for this classloader");
} catch (NameNotFoundException e) {
//expected
}
//put the thread's classloader back
currentThread.setContextClassLoader(childLoader1);
//test rebind with existing binding
initCtx.rebind("java:comp/env/rubbish", "xyz");
assertEquals("xyz", initCtx.lookup("java:comp/env/rubbish"));
//test rebind with no existing binding
initCtx.rebind("java:comp/env/mullheim", "hij");
assertEquals("hij", initCtx.lookup("java:comp/env/mullheim"));
//test that the other bindings are already there
assertEquals("xyz", initCtx.lookup("java:comp/env/poubelle"));
//test java:/comp/env/stuff
assertEquals("xyz", initCtx.lookup("java:/comp/env/poubelle/"));
//test list Names
NamingEnumeration nenum = initCtx.list("java:comp/env");
HashMap results = new HashMap();
while (nenum.hasMore()) {
NameClassPair ncp = (NameClassPair) nenum.next();
results.put(ncp.getName(), ncp.getClassName());
}
assertEquals(4, results.size());
assertEquals("java.lang.String", results.get("rubbish"));
assertEquals("javax.naming.LinkRef", results.get("poubelle"));
assertEquals("java.lang.String", results.get("mullheim"));
assertEquals("javax.naming.Reference", results.get("quatsch"));
//test list Bindings
NamingEnumeration benum = initCtx.list("java:comp/env");
assertEquals(4, results.size());
//test NameInNamespace
assertEquals("comp/env", sub2.getNameInNamespace());
//test close does nothing
Context closeCtx = (Context) initCtx.lookup("java:comp/env");
closeCtx.close();
//test what happens when you close an initial context
InitialContext closeInit = new InitialContext();
closeInit.close();
//check locking the context
Context ectx = (Context) initCtx.lookup("java:comp");
ectx.bind("crud", "xxx");
ectx.addToEnvironment("org.eclipse.jndi.immutable", "TRUE");
assertEquals("xxx", initCtx.lookup("java:comp/crud"));
try {
ectx.bind("crud2", "xxx2");
} catch (NamingException ne) {
//expected failure to modify immutable context
}
initCtx.close();
} finally {
//make some effort to clean up
InitialContext ic = new InitialContext();
Context java = (Context) ic.lookup("java:");
java.destroySubcontext("zero");
java.destroySubcontext("fee");
currentThread.setContextClassLoader(childLoader1);
Context comp = (Context) ic.lookup("java:comp");
comp.destroySubcontext("env");
comp.unbind("crud");
comp.unbind("crud2");
currentThread.setContextClassLoader(currentLoader);
}
}
use of javax.naming.NamingEnumeration in project jetty.project by eclipse.
the class NamingUtil method flattenBindings.
/**
* Do a deep listing of the bindings for a context.
* @param ctx the context containing the name for which to list the bindings
* @param name the name in the context to list
* @return map: key is fully qualified name, value is the bound object
* @throws NamingException if unable to flatten bindings
*/
public static Map flattenBindings(Context ctx, String name) throws NamingException {
HashMap map = new HashMap();
//the context representation of name arg
Context c = (Context) ctx.lookup(name);
NameParser parser = c.getNameParser("");
NamingEnumeration enm = ctx.listBindings(name);
while (enm.hasMore()) {
Binding b = (Binding) enm.next();
if (b.getObject() instanceof Context) {
map.putAll(flattenBindings(c, b.getName()));
} else {
Name compoundName = parser.parse(c.getNameInNamespace());
compoundName.add(b.getName());
map.put(compoundName.toString(), b.getObject());
}
}
return map;
}
use of javax.naming.NamingEnumeration in project Openfire by igniterealtime.
the class LdapUserTester method getSample.
/**
* Returns a list of usernames with a sample of the users found in LDAP.
*
* @param maxSample the max size of the sample to return.
* @return a list of usernames with a sample of the users found in LDAP.
* @throws NamingException if something goes wrong....
*/
public List<String> getSample(int maxSample) throws NamingException {
List<String> usernames = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on username field.
Control[] searchControl;
try {
searchControl = new Control[] { new SortControl(new String[] { manager.getUsernameField() }, Control.NONCRITICAL) };
} catch (IOException e) {
Log.error(e.getMessage(), e);
return Collections.emptyList();
}
ctx.setRequestControls(searchControl);
// Search for the dn based on the username.
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
searchControls.setReturningAttributes(new String[] { manager.getUsernameField() });
// Limit results to those we'll need to process
searchControls.setCountLimit(maxSample);
String filter = MessageFormat.format(manager.getSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next userID.
String username = (String) ((SearchResult) answer.next()).getAttributes().get(manager.getUsernameField()).get();
// Escape username and add to results.
usernames.add(JID.escapeNode(username));
}
// Close the enumeration.
answer.close();
} finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return usernames;
}
Aggregations