Search in sources :

Example 1 with NameClassPair

use of javax.naming.NameClassPair 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);
    }
}
Also used : Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) NamingContext(org.eclipse.jetty.jndi.NamingContext) NameNotFoundException(javax.naming.NameNotFoundException) HashMap(java.util.HashMap) Reference(javax.naming.Reference) NamingEnumeration(javax.naming.NamingEnumeration) InitialContext(javax.naming.InitialContext) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) StringRefAddr(javax.naming.StringRefAddr) NameClassPair(javax.naming.NameClassPair) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) NamingException(javax.naming.NamingException) LinkRef(javax.naming.LinkRef) Test(org.junit.Test)

Example 2 with NameClassPair

use of javax.naming.NameClassPair in project ACS by ACS-Community.

the class TestJDAL method testListContext.

/**
	 * Listing different contexts - simple and XML contexts
	 * We shouldn't see any difference in listing just 'directory' context
	 * or listing inside a XML data
	 */
public void testListContext() throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.cosylab.cdb.jdal.JNDIContextFactory");
    env.put(Context.PROVIDER_URL, strIOR);
    Context context = null;
    context = new InitialContext(env);
    assertNotNull(context);
    // try simple listing
    String list = "";
    NamingEnumeration ne = context.list("MACI");
    while (ne.hasMore()) {
        NameClassPair pair = (NameClassPair) ne.nextElement();
        list = list + pair.getName() + " ";
    }
    // same as we did listing
    assertTrue(list.indexOf("Containers") != -1);
    assertTrue(list.indexOf("Managers") != -1);
    // try with a XML
    ne = ((Context) (((Context) context.lookup("MACI")).lookup("Managers"))).list("Manager");
    list = "";
    while (ne.hasMore()) {
        NameClassPair pair = (NameClassPair) ne.nextElement();
        list = list + pair.getName() + " ";
    //System.out.println(pair.getName() + " " + pair.getClassName());
    }
    // this should be in Manager data
    assertTrue(list.indexOf("ServiceComponents") != -1);
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Hashtable(java.util.Hashtable) NameClassPair(javax.naming.NameClassPair) NamingEnumeration(javax.naming.NamingEnumeration) InitialContext(javax.naming.InitialContext)

Example 3 with NameClassPair

use of javax.naming.NameClassPair in project spring-framework by spring-projects.

the class SimpleNamingContextTests method testNamingContextBuilder.

@Test
public void testNamingContextBuilder() throws NamingException {
    SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
    InitialContextFactory factory = builder.createInitialContextFactory(null);
    DataSource ds = new StubDataSource();
    builder.bind("java:comp/env/jdbc/myds", ds);
    Object obj = new Object();
    builder.bind("myobject", obj);
    Context context1 = factory.getInitialContext(null);
    assertTrue("Correct DataSource registered", context1.lookup("java:comp/env/jdbc/myds") == ds);
    assertTrue("Correct Object registered", context1.lookup("myobject") == obj);
    Hashtable<String, String> env2 = new Hashtable<>();
    env2.put("key1", "value1");
    Context context2 = factory.getInitialContext(env2);
    assertTrue("Correct DataSource registered", context2.lookup("java:comp/env/jdbc/myds") == ds);
    assertTrue("Correct Object registered", context2.lookup("myobject") == obj);
    assertTrue("Correct environment", context2.getEnvironment() != env2);
    assertTrue("Correct key1", "value1".equals(context2.getEnvironment().get("key1")));
    Integer i = new Integer(0);
    context1.rebind("myinteger", i);
    String s = "";
    context2.bind("mystring", s);
    Context context3 = (Context) context2.lookup("");
    context3.rename("java:comp/env/jdbc/myds", "jdbc/myds");
    context3.unbind("myobject");
    assertTrue("Correct environment", context3.getEnvironment() != context2.getEnvironment());
    context3.addToEnvironment("key2", "value2");
    assertTrue("key2 added", "value2".equals(context3.getEnvironment().get("key2")));
    context3.removeFromEnvironment("key1");
    assertTrue("key1 removed", context3.getEnvironment().get("key1") == null);
    assertTrue("Correct DataSource registered", context1.lookup("jdbc/myds") == ds);
    try {
        context1.lookup("myobject");
        fail("Should have thrown NameNotFoundException");
    } catch (NameNotFoundException ex) {
    // expected
    }
    assertTrue("Correct Integer registered", context1.lookup("myinteger") == i);
    assertTrue("Correct String registered", context1.lookup("mystring") == s);
    assertTrue("Correct DataSource registered", context2.lookup("jdbc/myds") == ds);
    try {
        context2.lookup("myobject");
        fail("Should have thrown NameNotFoundException");
    } catch (NameNotFoundException ex) {
    // expected
    }
    assertTrue("Correct Integer registered", context2.lookup("myinteger") == i);
    assertTrue("Correct String registered", context2.lookup("mystring") == s);
    assertTrue("Correct DataSource registered", context3.lookup("jdbc/myds") == ds);
    try {
        context3.lookup("myobject");
        fail("Should have thrown NameNotFoundException");
    } catch (NameNotFoundException ex) {
    // expected
    }
    assertTrue("Correct Integer registered", context3.lookup("myinteger") == i);
    assertTrue("Correct String registered", context3.lookup("mystring") == s);
    Map<String, Binding> bindingMap = new HashMap<>();
    NamingEnumeration<?> bindingEnum = context3.listBindings("");
    while (bindingEnum.hasMoreElements()) {
        Binding binding = (Binding) bindingEnum.nextElement();
        bindingMap.put(binding.getName(), binding);
    }
    assertTrue("Correct jdbc subcontext", bindingMap.get("jdbc").getObject() instanceof Context);
    assertTrue("Correct jdbc subcontext", SimpleNamingContext.class.getName().equals(bindingMap.get("jdbc").getClassName()));
    Context jdbcContext = (Context) context3.lookup("jdbc");
    jdbcContext.bind("mydsX", ds);
    Map<String, Binding> subBindingMap = new HashMap<>();
    NamingEnumeration<?> subBindingEnum = jdbcContext.listBindings("");
    while (subBindingEnum.hasMoreElements()) {
        Binding binding = (Binding) subBindingEnum.nextElement();
        subBindingMap.put(binding.getName(), binding);
    }
    assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("myds").getObject()));
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("myds").getClassName()));
    assertTrue("Correct DataSource registered", ds.equals(subBindingMap.get("mydsX").getObject()));
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subBindingMap.get("mydsX").getClassName()));
    assertTrue("Correct Integer registered", i.equals(bindingMap.get("myinteger").getObject()));
    assertTrue("Correct Integer registered", Integer.class.getName().equals(bindingMap.get("myinteger").getClassName()));
    assertTrue("Correct String registered", s.equals(bindingMap.get("mystring").getObject()));
    assertTrue("Correct String registered", String.class.getName().equals(bindingMap.get("mystring").getClassName()));
    context1.createSubcontext("jdbc").bind("sub/subds", ds);
    Map<String, String> pairMap = new HashMap<>();
    NamingEnumeration<?> pairEnum = context2.list("jdbc");
    while (pairEnum.hasMore()) {
        NameClassPair pair = (NameClassPair) pairEnum.next();
        pairMap.put(pair.getName(), pair.getClassName());
    }
    assertTrue("Correct sub subcontext", SimpleNamingContext.class.getName().equals(pairMap.get("sub")));
    Context subContext = (Context) context2.lookup("jdbc/sub");
    Map<String, String> subPairMap = new HashMap<>();
    NamingEnumeration<?> subPairEnum = subContext.list("");
    while (subPairEnum.hasMoreElements()) {
        NameClassPair pair = (NameClassPair) subPairEnum.next();
        subPairMap.put(pair.getName(), pair.getClassName());
    }
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(subPairMap.get("subds")));
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds")));
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX")));
    pairMap.clear();
    pairEnum = context1.list("jdbc/");
    while (pairEnum.hasMore()) {
        NameClassPair pair = (NameClassPair) pairEnum.next();
        pairMap.put(pair.getName(), pair.getClassName());
    }
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("myds")));
    assertTrue("Correct DataSource registered", StubDataSource.class.getName().equals(pairMap.get("mydsX")));
}
Also used : SimpleNamingContextBuilder(org.springframework.tests.mock.jndi.SimpleNamingContextBuilder) InitialContext(javax.naming.InitialContext) SimpleNamingContext(org.springframework.tests.mock.jndi.SimpleNamingContext) Context(javax.naming.Context) Binding(javax.naming.Binding) NameNotFoundException(javax.naming.NameNotFoundException) HashMap(java.util.HashMap) Hashtable(java.util.Hashtable) InitialContextFactory(javax.naming.spi.InitialContextFactory) DataSource(javax.sql.DataSource) NameClassPair(javax.naming.NameClassPair) Test(org.junit.Test)

Example 4 with NameClassPair

use of javax.naming.NameClassPair in project iaf by ibissource.

the class LdapSender method getSubContextList.

/**
 * Return a list of all of the subcontexts of the current context, which is relative to parentContext.
 * @return an array of Strings containing a list of the subcontexts for a current context.
 */
public String[] getSubContextList(DirContext parentContext, String relativeContext, ParameterResolutionContext prc) {
    String[] retValue = null;
    try {
        // Create a vector object and add the names of all of the subcontexts
        // to it
        Vector n = new Vector();
        NamingEnumeration list = parentContext.list(relativeContext);
        if (log.isDebugEnabled())
            log.debug("getSubCOntextList(context) : context = " + relativeContext);
        for (int x = 0; list.hasMore(); x++) {
            NameClassPair nc = (NameClassPair) list.next();
            n.addElement(nc);
        }
        // Create a string array of the same size as the vector object
        String[] contextList = new String[n.size()];
        for (int x = 0; x < n.size(); x++) {
            // Add each name to the array
            contextList[x] = ((NameClassPair) (n.elementAt(x))).getName();
        }
        retValue = contextList;
    } catch (NamingException e) {
        storeLdapException(e, prc);
        log.error("Exception in operation [" + getOperation() + "] ", e);
    }
    return retValue;
}
Also used : NameClassPair(javax.naming.NameClassPair) NamingEnumeration(javax.naming.NamingEnumeration) NamingException(javax.naming.NamingException) Vector(java.util.Vector)

Example 5 with NameClassPair

use of javax.naming.NameClassPair in project core by weld.

the class BeanManagerResourceBindingListener method contextInitialized.

public void contextInitialized(ServletContextEvent sce) {
    try {
        InitialContext ctx = new InitialContext();
        boolean present = false;
        try {
            NamingEnumeration<NameClassPair> entries = ctx.list(RESOURCES_CONTEXT);
            while (entries.hasMoreElements()) {
                try {
                    NameClassPair e = entries.next();
                    if (e.getName().equals(BEAN_MANAGER_JNDI_NAME) && e.getClassName().equals(BeanManager.class)) {
                        present = true;
                        break;
                    }
                } catch (Exception e) {
                    WeldServletLogger.LOG.problemWhenInterating(RESOURCES_CONTEXT, e);
                }
            }
        } catch (NamingException e) {
            WeldServletLogger.LOG.couldNotReadContext(RESOURCES_CONTEXT);
            try {
                Context compCtx = (Context) ctx.lookup("java:comp");
                compCtx.createSubcontext("env");
            } catch (Exception ex) {
                WeldServletLogger.LOG.couldntCreateContext(RESOURCES_CONTEXT);
            }
        }
        if (!present) {
            try {
                // we rebind just in case it really is there and we just couldn't read it
                ctx.rebind(QUALIFIED_BEAN_MANAGER_JNDI_NAME, new Reference(BeanManager.class.getName(), BEAN_MANAGER_OBJECT_FACTORY, null));
                bound = true;
                WeldServletLogger.LOG.beanManagerReferenceBoundTo(QUALIFIED_BEAN_MANAGER_JNDI_NAME);
            } catch (NamingException e) {
                throw WeldServletLogger.LOG.couldNotBindBeanManagerReferenceToJNDI(e.getExplanation());
            }
        }
    } catch (NamingException e) {
        throw WeldServletLogger.LOG.couldNotCreateInitialContext(e.getExplanation());
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) NameClassPair(javax.naming.NameClassPair) Reference(javax.naming.Reference) NamingException(javax.naming.NamingException) BeanManager(javax.enterprise.inject.spi.BeanManager) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException)

Aggregations

NameClassPair (javax.naming.NameClassPair)59 NamingException (javax.naming.NamingException)27 DirContext (javax.naming.directory.DirContext)19 Test (org.junit.Test)17 HashSet (java.util.HashSet)13 Context (javax.naming.Context)11 InitialContext (javax.naming.InitialContext)10 Hashtable (java.util.Hashtable)9 NamingEnumeration (javax.naming.NamingEnumeration)8 InitialDirContext (javax.naming.directory.InitialDirContext)8 IOException (java.io.IOException)7 FileNotFoundException (java.io.FileNotFoundException)5 HashMap (java.util.HashMap)5 Resource (org.apache.naming.resources.Resource)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)4 Vector (java.util.Vector)4 CompositeName (javax.naming.CompositeName)4 File (java.io.File)3