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:

view plain print about
1import java.sql.Connection;
2import javax.sql.DataSource;
4import coldfusion.server.DataSourceService;
5import coldfusion.server.ServiceFactory;
9DataSourceService dsService = ServiceFactory.getDataSourceService();
10DataSource ds = dsService.getDatasource( "datasourceName" );
11Connection con = ds.getConnection();