You can configure a standalone app (or unit tests!) to use your server's INITIAL_CONTEXT_FACTORY
without running the server.
This is how to do that for a Apache Tomcat initialization, but you should have enough information to adapt it for another server.
Starting configuration from the server
This example presumes you want to mimic something like this from your context.xml
file:
<Resource name="jdbc/testdb" auth="Container"
type="javax.sql.DataSource"
driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
username="someuser" password="somepassword"
url="jdbc:sqlserver://localhost\SQLEXPRESS;databaseName=somedb;applicationName=someapp"/>
Create the resource to go into the Context
This example is database specific, but you can put things other than a DataSource
in the Context. Here is one way you might be able to create a DataSource
for this SQL Server example. (It requires the JDBC driver and tomcat-dbcp.jar
in your classpath. This code is for an older version of the driver, new versions probably have SQLServerXADataSource
and would not need tomcat-dbcp.jar
.)
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(SQLServerDriver.class.getName());
dataSource.setUrl(url);
dataSource.setUsername(getUserName());
dataSource.setPassword(getPassword());
Initialize using Tomcat INITIAL_CONTEXT_FACTORY
See this old blog post.
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
"org.apache.naming.java.javaURLContextFactory");
System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
InitialContext ctxt = new InitialContext();`
The reference to org.apache.naming.java.javaURLContextFactory
means you should have catalina.jar
in your classpath. You should be able to find variants for the INITIAL_CONTEXT_FACTORY
and URL_PGK_PREFIXES
values for other application servers.
Register the resource for future lookups
Then register your DataSource dataSource
for future lookups, at java:/comp/env/jdbc/testdb
. Unfortunately, you have to make sure all the intermediate subcontext levels are created before you can add the resource. (Exercise for the reader: You can create a method to figure out the subcontext names from the resourceName
instead of hard-coding the list as this example does.)
// Create all the intermediate levels
for (String resource : new String[]{ "java:", "java:comp", "java:comp/env", "java:/comp/env/jdbc" })
{
try
{
ctxt.lookup(subContext);
}
catch (NameNotFoundException nnfe)
{
ctxt.createSubcontext(subContext);
}
}
// Finally, register the resource
ctxt.bind(resourceName, dataSource);
This completes the setup portion, mimicking what is normally done in the Tomcat application server context.xml
.
Do the lookup
Then the rest of your application can create InitialContext
s and do lookup
s as normal (in a single lookup
call):
Context ic = new InitialContext();
DataSource ds = (DataSource)ic.lookup("java:/comp/env/jdbc/testdb");