Search in sources :

Example 1 with LinkRef

use of javax.naming.LinkRef in project jetty.project by eclipse.

the class TestMailSessionReference method testMailSessionReference.

@Test
public void testMailSessionReference() throws Exception {
    InitialContext icontext = new InitialContext();
    MailSessionReference sref = new MailSessionReference();
    sref.setUser("janb");
    sref.setPassword("OBF:1xmk1w261z0f1w1c1xmq");
    Properties props = new Properties();
    props.put("mail.smtp.host", "xxx");
    props.put("mail.debug", "true");
    sref.setProperties(props);
    NamingUtil.bind(icontext, "mail/Session", sref);
    Object x = icontext.lookup("mail/Session");
    assertNotNull(x);
    assertTrue(x instanceof javax.mail.Session);
    javax.mail.Session session = (javax.mail.Session) x;
    Properties sessionProps = session.getProperties();
    assertEquals(props, sessionProps);
    assertTrue(session.getDebug());
    Context foo = icontext.createSubcontext("foo");
    NameParser parser = icontext.getNameParser("");
    Name objectNameInNamespace = parser.parse(icontext.getNameInNamespace());
    objectNameInNamespace.addAll(parser.parse("mail/Session"));
    NamingUtil.bind(foo, "mail/Session", new LinkRef(objectNameInNamespace.toString()));
    Object o = foo.lookup("mail/Session");
    assertNotNull(o);
    Session fooSession = (Session) o;
    assertEquals(props, fooSession.getProperties());
    assertTrue(fooSession.getDebug());
    icontext.destroySubcontext("mail");
    icontext.destroySubcontext("foo");
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) Session(javax.mail.Session) Properties(java.util.Properties) InitialContext(javax.naming.InitialContext) NameParser(javax.naming.NameParser) Session(javax.mail.Session) Name(javax.naming.Name) LinkRef(javax.naming.LinkRef) Test(org.junit.Test)

Example 2 with LinkRef

use of javax.naming.LinkRef 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 3 with LinkRef

use of javax.naming.LinkRef in project jetty.project by eclipse.

the class NamingContext method lookup.

/*------------------------------------------------*/
/**
     * Lookup a binding by name
     *
     * @param name name of bound object
     * @exception NamingException if an error occurs
     */
public Object lookup(Name name) throws NamingException {
    if (__log.isDebugEnabled())
        __log.debug("Looking up name=\"" + name + "\"");
    Name cname = toCanonicalName(name);
    if ((cname == null) || (cname.size() == 0)) {
        __log.debug("Null or empty name, returning copy of this context");
        NamingContext ctx = new NamingContext(_env, _name, _parent, _parser);
        ctx._bindings = _bindings;
        return ctx;
    }
    if (cname.size() == 1) {
        Binding binding = getBinding(cname);
        if (binding == null) {
            NameNotFoundException nnfe = new NameNotFoundException();
            nnfe.setRemainingName(cname);
            throw nnfe;
        }
        Object o = binding.getObject();
        //handle links by looking up the link
        if (o instanceof LinkRef) {
            //if link name starts with ./ it is relative to current context
            String linkName = ((LinkRef) o).getLinkName();
            if (linkName.startsWith("./"))
                return this.lookup(linkName.substring(2));
            else {
                //link name is absolute
                InitialContext ictx = new InitialContext();
                return ictx.lookup(linkName);
            }
        } else if (o instanceof Reference) {
            //deference the object
            try {
                return NamingManager.getObjectInstance(o, cname, this, _env);
            } catch (NamingException e) {
                throw e;
            } catch (Exception e) {
                __log.warn("", e);
                throw new NamingException(e.getMessage());
            }
        } else
            return o;
    }
    //it is a multipart name, recurse to the first subcontext
    String firstComponent = cname.get(0);
    Object ctx = null;
    if (firstComponent.equals(""))
        ctx = this;
    else {
        Binding binding = getBinding(firstComponent);
        if (binding == null) {
            NameNotFoundException nnfe = new NameNotFoundException();
            nnfe.setRemainingName(cname);
            throw nnfe;
        }
        //as we have bound a reference to an object factory
        //for the component specific contexts
        //at "comp" we need to resolve the reference
        ctx = binding.getObject();
        if (ctx instanceof Reference) {
            //deference the object
            try {
                ctx = NamingManager.getObjectInstance(ctx, getNameParser("").parse(firstComponent), this, _env);
            } catch (NamingException e) {
                throw e;
            } catch (Exception e) {
                __log.warn("", e);
                throw new NamingException(e.getMessage());
            }
        }
    }
    if (!(ctx instanceof Context))
        throw new NotContextException();
    return ((Context) ctx).lookup(cname.getSuffix(1));
}
Also used : Binding(javax.naming.Binding) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) NotContextException(javax.naming.NotContextException) NameNotFoundException(javax.naming.NameNotFoundException) Reference(javax.naming.Reference) InitialContext(javax.naming.InitialContext) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) NotContextException(javax.naming.NotContextException) OperationNotSupportedException(javax.naming.OperationNotSupportedException) CompoundName(javax.naming.CompoundName) Name(javax.naming.Name) NamingException(javax.naming.NamingException) LinkRef(javax.naming.LinkRef)

Example 4 with LinkRef

use of javax.naming.LinkRef in project jetty.project by eclipse.

the class Transaction method bindToComp.

/**
     * Insist on the java:comp/UserTransaction binding
     * @throws NamingException
     */
private void bindToComp() throws NamingException {
    //ignore the name, it is always bound to java:comp
    InitialContext ic = new InitialContext();
    Context env = (Context) ic.lookup("java:comp");
    __log.debug("Binding java:comp/" + getJndiName() + " to " + _objectNameString);
    NamingUtil.bind(env, getJndiName(), new LinkRef(_objectNameString));
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) InitialContext(javax.naming.InitialContext) LinkRef(javax.naming.LinkRef)

Example 5 with LinkRef

use of javax.naming.LinkRef in project tomcat by apache.

the class NamingContext method bind.

/**
     * Binds a name to an object. All intermediate contexts and the target
     * context (that named by all but terminal atomic component of the name)
     * must already exist.
     *
     * @param name the name to bind; may not be empty
     * @param obj the object to bind; possibly null
     * @param rebind if true, then perform a rebind (ie, overwrite)
     * @exception NameAlreadyBoundException if name is already bound
     * @exception javax.naming.directory.InvalidAttributesException if object
     * did not supply all mandatory attributes
     * @exception NamingException if a naming exception is encountered
     */
protected void bind(Name name, Object obj, boolean rebind) throws NamingException {
    if (!checkWritable()) {
        return;
    }
    while ((!name.isEmpty()) && (name.get(0).length() == 0)) name = name.getSuffix(1);
    if (name.isEmpty())
        throw new NamingException(sm.getString("namingContext.invalidName"));
    NamingEntry entry = bindings.get(name.get(0));
    if (name.size() > 1) {
        if (entry == null) {
            throw new NameNotFoundException(sm.getString("namingContext.nameNotBound", name, name.get(0)));
        }
        if (entry.type == NamingEntry.CONTEXT) {
            if (rebind) {
                ((Context) entry.value).rebind(name.getSuffix(1), obj);
            } else {
                ((Context) entry.value).bind(name.getSuffix(1), obj);
            }
        } else {
            throw new NamingException(sm.getString("namingContext.contextExpected"));
        }
    } else {
        if ((!rebind) && (entry != null)) {
            throw new NameAlreadyBoundException(sm.getString("namingContext.alreadyBound", name.get(0)));
        } else {
            // Getting the type of the object and wrapping it within a new
            // NamingEntry
            Object toBind = NamingManager.getStateToBind(obj, name, this, env);
            if (toBind instanceof Context) {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.CONTEXT);
            } else if (toBind instanceof LinkRef) {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.LINK_REF);
            } else if (toBind instanceof Reference) {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE);
            } else if (toBind instanceof Referenceable) {
                toBind = ((Referenceable) toBind).getReference();
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.REFERENCE);
            } else {
                entry = new NamingEntry(name.get(0), toBind, NamingEntry.ENTRY);
            }
            bindings.put(name.get(0), entry);
        }
    }
}
Also used : InitialContext(javax.naming.InitialContext) Context(javax.naming.Context) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) Referenceable(javax.naming.Referenceable) NameNotFoundException(javax.naming.NameNotFoundException) Reference(javax.naming.Reference) NamingException(javax.naming.NamingException) LinkRef(javax.naming.LinkRef)

Aggregations

LinkRef (javax.naming.LinkRef)32 Context (javax.naming.Context)23 NamingException (javax.naming.NamingException)18 InitialContext (javax.naming.InitialContext)17 NameNotFoundException (javax.naming.NameNotFoundException)17 Reference (javax.naming.Reference)15 NotContextException (javax.naming.NotContextException)11 OperationNotSupportedException (javax.naming.OperationNotSupportedException)11 CompositeName (javax.naming.CompositeName)10 NameAlreadyBoundException (javax.naming.NameAlreadyBoundException)8 Name (javax.naming.Name)7 Referenceable (javax.naming.Referenceable)4 Test (org.junit.Test)4 MalformedURLException (java.net.MalformedURLException)2 HashMap (java.util.HashMap)2 Binding (javax.naming.Binding)2 CannotProceedException (javax.naming.CannotProceedException)2 CompoundName (javax.naming.CompoundName)2 Provider (com.google.inject.Provider)1 IOException (java.io.IOException)1