Jetty Bind DataSource in JNDI Context

datasource, eclipse, jetty, jndi

Solution

I encountered the same issue and here is what I did to fix it:

    server = new Server(PORT);
    WebAppContext context = new WebAppContext();
    context.setContextPath(CONTEXT);
    context.setConfigurationClasses(new String[] { "org.eclipse.jetty.plus.webapp.PlusConfiguration",
            "org.eclipse.jetty.webapp.FragmentConfiguration" });
    // A filter needed by Guice, but this is independent
    context.addFilter(GuiceFilter.class, "/*", 0);
    PGSimpleDataSource simpleDataSource = new PGSimpleDataSource();
    simpleDataSource.setDatabaseName("db-name");
    simpleDataSource.setUser("user");
    simpleDataSource.setPassword("pwd");
    String jndiName = "jdbc/myDS";
    Resource resource = new Resource("java:comp/env/" + jndiName, simpleDataSource);
    server.setHandler(context);
    // an event listener (because I use Guice, but this is independent)
    GuiceServletConfig guiceServletConfig = new GuiceServletConfig();
    context.addEventListener(guiceServletConfig);
    server.start();

This requires to have the following additional libraries:

- jetty-jndi

- jetty-plus

I tested this code on Embedded Jetty 7 (7.6.10.v20130312)

Problem

I would like to bind DataSource object to (eclipse) jetty's JNDI context programatically. I need for testing purpose. Here's a piece of code I have now: ``` server = new Server(SERVER_PORT); webAppContext = new WebAppContext(); webAppContext.setResourceBase("."); webAppContext.setContextPath("/" + SERVER_CONTEXT); webAppContext.addEventListener(prepareServletContextListener()); webAppContext.addFilter(GuiceFilter.class, "/*", null); webAppContext.addServlet(DefaultServlet.class, "/"); Resource r = new Resource(webAppContext,"jdbc/testDS",createDataSource()); server.setHandler(webAppContext); server.start(); ``` Of course the line with Resource isn't working.I have no idea how to bind it programatically to obtain sth similar to: ``` <New id="DSTest" class="org.eclipse.jetty.plus.jndi.Resource"> <Arg></Arg> <Arg>jdbc/DSTest</Arg> <Arg> <New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource"> <Set name="Url">jdbc:mysql://localhost:3306/databasename</Set> <Set name="User">user</Set> <Set name="Password">pass</Set> </New> </Arg> </New> ``` Any help would be greatly appreciated.

Original source