g2532hsq
g2532hsq

Reputation: 1

TomEE Embedded: Resource defined in resources.xml not available within webapp

I'm currently trying to run a simple webapp on TomEE Embedded (TomEE Version 7.0.5).

According to the docs, I can start the TomEE and deploy the classpath as a webapp like this. I've set the document base to src/main/webapp.

try (final Container container = new Container(new Configuration())
                                      .deployClasspathAsWebApp("", new File("src/main/webapp"))) {
    container.await();
}

I have defined a datasource in WEB-INF/resources.xml which looks like this:

<Resource id="myDataSource" type="javax.sql.DataSource">
    JdbcDriver org.hsqldb.jdbcDriver
    JdbcUrl jdbc:hsqldb:file:hsqldb
    UserName sa
    Password
</Resource>

And I've setup a reference in the web.xml:

<resource-ref>
  <res-ref-name>myDataSource</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
</resource-ref>

Then I try to lookup this datasource in my Servlet via JNDI.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  try {
    Context initCtx = new InitialContext();
    DataSource ds = (DataSource) initCtx.lookup("java:comp/env/myDataSource");
    Connection connection = ds.getConnection();    
    ...
}

When the TomEE starts, it seems like my DataSource is created (at least there is some output about that in the logs). However when I try to lookup the DataSource in my servlet, I get an unconfigured dbcp2 connection pool as a DataSource which throws the following exception when ds.getConnection() is called:

java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL 'null'
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createConnectionFactory(BasicDataSource.java:2186)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2066)
    at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1525)
    at TestServlet.doGet(TestServlet.java:32)
    ...

The same configuration works fine on a standalone TomEE (I tried TomEE Webprofile) or when using the TomEE Maven Plugin. Is there anything I'm missing to get it running also for Embedded TomEE?

Thanks in advance

Upvotes: 0

Views: 725

Answers (1)

Romain Manni-Bucau
Romain Manni-Bucau

Reputation: 3422

Tomee embedded does not bind a custom webapp classloader by default so does not have comp/ always bound. You can pass properties to the context to force it to be openejb one or use openejb:Resource/myDataSource or java:openejb/Resource/myDataSource naming.

Upvotes: 0

Related Questions