1

I'm trying to inject a DataSource into a ContainerRequestFilter in TomEE [Apache Tomcat (TomEE)/9.0.20 (8.0.0-M3]. However, I'm getting errors no matter what I do.

I see that the JNDI name is being registered in TomEE via:

org.apache.openejb.assembler.classic.Assembler.createRecipe Creating Resource(id=jdbc/auth/ReadDataSource)

But even when I manually lookup the DataSource via InitialContext I get errors doing a lookup. For example here is my sample filter:

@Provider
@PreMatching
public class MyFilter implements ContainerRequestFilter {

    DataSource dataSource;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        try {
            InitialContext initialContext = new InitialContext();
            dataSource = (DataSource)initialContext.lookup("jdbc/auth/ReadDataSource");
        } catch (NullPointerException | NamingException e) {
            Response response = Response
                .status(Status.INTERNAL_SERVER_ERROR)
                .entity(e.getMessage())
                .build();
            requestContext.abortWith(response);
        }
    }
}

Unfortunantely, I get the following error:

Name [jdbc/auth/ReadDataSource] is not bound in this Context. Unable to find [jdbc]

What can I do? I been researching how to fix my issue and lot of what I see is Jersey specific solutions. However, I using TomEE and its JAX-RS implementation is Apache CXF1. So a jersey solution wouldn't work, unless I change the JAX-RS implementation but that seem overkill for something trivia.

Any help would be greatly appreciated.

Thanks.

MWiesner
  • 7,913
  • 11
  • 31
  • 66
Gerb
  • 583
  • 6
  • 22

2 Answers2

0

Add java:comp/env/ prefix to your JNDI name:

... initialContext.lookup("java:comp/env/jdbc/auth/ReadDataSource");
mentallurg
  • 4,271
  • 5
  • 22
  • 32
0

What I ended up doing was lookup a EJB via initial context and have the EJB inject the resource. For example, in my Filter, this worked:

            Properties p = new Properties();
            p.put("java.naming.factory.initial", "org.apache.openejb.client.LocalInitialContextFactory");
            InitialContext ic = new InitialContext(p);
            Hello hellpEJB = (Hello)ic.lookup("HelloImplLocal");

in the EJB i can easily inject a resource via:

    @Resource(name="jdbc/auth/ReadDataSource")
    DataSource dataSource;

    @Override
    public String sayHello() {
        try {
            Connection connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "Hello from EJB";
    }

Everything is working perfectly!

Gerb
  • 583
  • 6
  • 22