I'm using a Resource
tag in tomcat's context.xml
file to store database connection info. I access it in my jersey servlet like this:
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup(DB_SOURCE_CONTEXT);
return ds.getConnection();
For unit testing, I'm using jersey-test and grizzly2, rather than deploying to tomcat. I'm trying to set the connection properties to use a test DB (currently MySQL, but I will change it to DBUnit next) in the unit test class:
@BeforeClass
public static void initializeTest() throws NamingException
{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUsername("root");
dataSource.setPassword("");
dataSource.setUrl(TEST_DB_URL);
dataSource.setMaxTotal(10);
dataSource.setMaxIdle(5);
dataSource.setInitialSize(5);
dataSource.setValidationQuery("SELECT 1");
envContext.bind(DB_SOURCE_CONTEXT, dataSource);
}
But I get the following exception, so it's clearly not the correct way to do it:
javax.naming.NoInitialContextException: Need to specify class name in environment or
system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial
How can I set these values so the Context reading code in the servlet reads the test values?