7

I want to test some new functionality which is part of an internal web app. This new code uses a database connection normally provided by an app server (tomcat).

I do not want to recreate the entire web app on my local machine to test the new code, since I only need to run one function.

Does anyone know how I can 'spoof' a Context, or Datasource, to retrieve the database config, without actually creating a web app instance on a server?

3 Answers 3

4

With the help of Spring SimpleNamingContextBuilder and Apache BasicDataSource, you can do something like this (I usually have this in a static block in test classes that need JNDI):

BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(db_driver_name);
dataSource.setUrl(db_connection_url);
dataSource.setUsername(db_username);
dataSource.setPassword(db_password);
SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.bind(jndi_name, dataSource);
builder.activate();

The value of jndi_name might look like this: java:comp/env/jdbc/my-db

Once this is set up, code that normally looks up the database connection via JNDI should work. The code above would for example work with this Spring config:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
  <property name="jndiName" value="java:comp/env/jdbc/my-db"/>
</bean>
3
  • Lauri, how does the JndiObjectFactoryBean know to lookup my-db in the Spring directory? Don't you have to provide the context environment? In particular, in this environment, to what value would you set property java.naming.factory.initial? Commented Apr 15, 2011 at 21:22
  • Lauri, please see my question at stackoverflow.com/questions/5682732/…. Commented Apr 15, 2011 at 21:57
  • SimpleNamingContextBuilder is "Deprecated as of Spring Framework 5.2 in favor of complete solutions from third parties such as Simple-JNDI"
    – xtian
    Commented Jul 22, 2020 at 15:34
1

The solutions listed here look a bit simpler than what I came up with about a year ago when I had to do the same thing. I basically made my own very simple DataSource implementation and adding it to a new Initial Context.

http://penguindreams.org/blog/running-beans-that-use-application-server-datasources-locally/

0

With TomcatJNDI you can access every JNDI resource you configured within Tomcat as used to do in your web application. The code to achieve it is simple and looks like

TomcatJNDI tomcatJNDI = new TomcatJNDI();
tomcatJNDI.processContextXml(contextXmlFile);
tomcatJNDI.start();

DataSource ds = (DataSource) InitialContext.doLookup("java:comp/env/path/to/datasource")

Go here to read more about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.