Java Code Examples for javax.naming.Context#list()

The following examples show how to use javax.naming.Context#list() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmbeddedLdapRuleTest.java    From submarine with Apache License 2.0 6 votes vote down vote up
@Test
public void testList() throws Exception {
  final Context context = embeddedLdapRule.context();
  NamingEnumeration list = context.list("ou=semi-people,dc=zapodot,dc=org");

  while (list.hasMore()){
    NameClassPair nc = (NameClassPair) list.next();
    String user, group = null;
    ArrayList user_sp = new ArrayList();
    StringTokenizer user_info = new StringTokenizer(nc.getNameInNamespace(), ",");

    while (user_info.hasMoreTokens()){
      user_sp.add(user_info.nextToken());
    }
    user = user_sp.get(0).toString().substring(3, user_sp.get(0).toString().length());
    group = user_sp.get(1).toString().substring(3, user_sp.get(1).toString().length());

    LOG.info(user);

    assertEquals((user + "," + group) , "Fake-Eros,semi-people");
  }

  context.close();
}
 
Example 2
Source File: JNDIContext.java    From tomee with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public NamingEnumeration<Binding> listBindings(final String name) throws NamingException {
    final Object o = lookup(name);
    if (o instanceof Context) {
        final Context context = (Context) o;
        final NamingEnumeration<NameClassPair> enumeration = context.list("");
        final List<NameClassPair> bindings = new ArrayList<NameClassPair>();

        while (enumeration.hasMoreElements()) {
            final NameClassPair pair = enumeration.nextElement();
            bindings.add(new LazyBinding(pair.getName(), pair.getClassName(), context));
        }

        return new NameClassPairEnumeration(bindings);

    } else {
        return null;
    }

}
 
Example 3
Source File: IvmContextTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void testListContextListsAllFederatedContextBindings() throws SystemException, NamingException {
//mimic logic from EnterpriseBeanBuilder.build, create compJndiContext and bind in it module, app, global 
Context compContext = new IvmContext();
    compContext.bind("java:comp/env/dummy", "dummy");

    Context moduleContext = new IvmContext();
    moduleContext.bind("module/env/test", String.class);
    moduleContext.bind("module/env/sub/test2", String.class);
    Context originalModuleSubContext = (IvmContext)moduleContext.lookup("module");
    compContext.bind("module", originalModuleSubContext);

    Context referencedModuleEnvSubContext = (IvmContext)compContext.lookup("module/env");
    NamingEnumeration<NameClassPair> referencedEnvLookupResult = referencedModuleEnvSubContext.list("");

    boolean testFound= false;
    boolean subFound = false;
    while(referencedEnvLookupResult.hasMore()) {
        String currentName = referencedEnvLookupResult.next().getName();
        if("test".equals(currentName)) {
            testFound = true;
        } else if("sub".equals(currentName)) {
            subFound = true;
        } else {
            fail();
        }
    }
    assertTrue(testFound);
    assertTrue(subFound);
 }
 
Example 4
Source File: AbstractCachedLDAPAuthorizationMapLegacyTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public static void cleanAndLoad(String deleteFromDn,
                                String ldifResourcePath,
                                String ldapHost,
                                int ldapPort,
                                String ldapUser,
                                String ldapPass,
                                DirContext context) throws Exception {
   // Cleanup everything used for testing.
   List<String> dns = new LinkedList<>();
   dns.add(deleteFromDn);

   while (!dns.isEmpty()) {
      String name = dns.get(dns.size() - 1);
      Context currentContext = (Context) context.lookup(name);
      NamingEnumeration<NameClassPair> namingEnum = currentContext.list("");

      if (namingEnum.hasMore()) {
         while (namingEnum.hasMore()) {
            dns.add(namingEnum.next().getNameInNamespace());
         }
      } else {
         context.unbind(name);
         dns.remove(dns.size() - 1);
      }
   }

   // A bit of a hacked approach to loading an LDIF into OpenLDAP since there isn't an easy way to do it
   // otherwise.  This approach invokes the command line tool programmatically but has
   // to short-circuit the call to System.exit that the command line tool makes when it finishes.
   // We are assuming that there isn't already a security manager in place.
   final SecurityManager securityManager = new SecurityManager() {

      @Override
      public void checkPermission(java.security.Permission permission) {
         if (permission.getName().contains("exitVM")) {
            throw new SecurityException("System.exit calls disabled for the moment.");
         }
      }
   };

   System.setSecurityManager(securityManager);

   File file = new File(AbstractCachedLDAPAuthorizationMapLegacyTest.class.getClassLoader().getResource(ldifResourcePath).toURI());

   Class<?> clazz = Class.forName("LDAPModify");
   Method mainMethod = clazz.getMethod("main", String[].class);

   try {
      mainMethod.invoke(null, new Object[]{new String[]{"-v", "-h", ldapHost, "-p", String.valueOf(ldapPort), "-D", ldapUser, "-w", ldapPass, "-a", "-f", file.toString()}});
   } catch (InvocationTargetException e) {
      if (!(e.getTargetException() instanceof SecurityException)) {
         throw e;
      }
   }

   System.setSecurityManager(null);
}
 
Example 5
Source File: JNDIConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * This method recursive traverse the JNDI tree, looking for Context objects.
 * When it finds them, it traverses them as well.  Otherwise it just adds the
 * values to the list of keys found.
 *
 * @param keys All the keys that have been found.
 * @param context The parent context
 * @param prefix What prefix we are building on.
 * @param processedCtx a set with the so far processed objects
 * @throws NamingException If JNDI has an issue.
 */
private void recursiveGetKeys(final Set<String> keys, final Context context, final String prefix,
        final Set<Context> processedCtx) throws NamingException
{
    processedCtx.add(context);
    NamingEnumeration<NameClassPair> elements = null;

    try
    {
        elements = context.list("");

        // iterates through the context's elements
        while (elements.hasMore())
        {
            final NameClassPair nameClassPair = elements.next();
            final String name = nameClassPair.getName();
            final Object object = context.lookup(name);

            // build the key
            final StringBuilder key = new StringBuilder();
            key.append(prefix);
            if (key.length() > 0)
            {
                key.append(".");
            }
            key.append(name);

            if (object instanceof Context)
            {
                // add the keys of the sub context
                final Context subcontext = (Context) object;
                if (!processedCtx.contains(subcontext))
                {
                    recursiveGetKeys(keys, subcontext, key.toString(),
                            processedCtx);
                }
            }
            else
            {
                // add the key
                keys.add(key.toString());
            }
        }
    }
    finally
    {
        // close the enumeration
        if (elements != null)
        {
            elements.close();
        }
    }
}
 
Example 6
Source File: JNDIConfiguration.java    From commons-configuration with Apache License 2.0 4 votes vote down vote up
/**
 * Because JNDI is based on a tree configuration, we need to filter down the
 * tree, till we find the Context specified by the key to start from.
 * Otherwise return null.
 *
 * @param path     the path of keys to traverse in order to find the context
 * @param context  the context to start from
 * @return The context at that key's location in the JNDI tree, or null if not found
 * @throws NamingException if JNDI has an issue
 */
private Context getContext(final List<String> path, final Context context) throws NamingException
{
    // return the current context if the path is empty
    if (path == null || path.isEmpty())
    {
        return context;
    }

    final String key = path.get(0);

    // search a context matching the key in the context's elements
    NamingEnumeration<NameClassPair> elements = null;

    try
    {
        elements = context.list("");
        while (elements.hasMore())
        {
            final NameClassPair nameClassPair = elements.next();
            final String name = nameClassPair.getName();
            final Object object = context.lookup(name);

            if (object instanceof Context && name.equals(key))
            {
                final Context subcontext = (Context) object;

                // recursive search in the sub context
                return getContext(path.subList(1, path.size()), subcontext);
            }
        }
    }
    finally
    {
        if (elements != null)
        {
            elements.close();
        }
    }

    return null;
}