Using a ColdFusion Datasource in Java

From time to time I have to switch out of ColdFusion into Java to get a task accomplished. The latest was writing a password callback class for a web service integration project using ColdFusion, aka the Axis web service engine, and WSS4J.

I needed to look up a value in a database, as opposed to hard coding the value in the source, and decided to try to reuse the datasource connection already defined in ColdFusion.

Obligatory Warning: The following code uses the undocumented ColdFusion ServiceFactory class. Features may change in future versions of ColdFusion.

The ColdFusion ServiceFactory class lives in the coldfusion.server package. The getDataSourceService method gives you access to the datasources known by ColdFusion, and defined in ColdFusion Administrator.

Getting the connection is very straightforward, just retrieve an instance of the DataSourceService from the ServiceFactory, use the getDataSource method to retrieve the javax.sql.DataSource class for the named datasource, and then retrieve its connection:

import java.sql.Connection;
import javax.sql.DataSource;

import coldfusion.server.DataSourceService;
import coldfusion.server.ServiceFactory;

...

DataSourceService dsService = ServiceFactory.getDataSourceService();
DataSource ds = dsService.getDatasource( "datasourceName" );
Connection con = ds.getConnection();

Comments

sf's Gravatar Aww, this was a really quality post. In theory I’d like to write like this too – taking time and real effort to make a good article… but what can I say… I procrastinate alot and never seem to get something done.
# Posted By sf | 5/16/10 11:35 PM