Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetty Bind DataSource in JNDI Context

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.

like image 605
Opal Avatar asked Sep 15 '25 13:09

Opal


2 Answers

you need to add the defined resource object as attribute to the server object. The following should work:

Resource r = new Resource("jdbc/testDS",createDataSource());
server.setAttribute("myDs", r);
like image 176
langm Avatar answered Sep 17 '25 04:09

langm


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)

like image 24
Guillaume Polet Avatar answered Sep 17 '25 05:09

Guillaume Polet