Getting access to a Lucee Datasource inside a Java class


#1

We have a usecase which inovolves some intesive DB processing that we’d like to implement a Java class. The Java class will be invoked from within a cfc template using createObject() and init() like so:

<cfset myJavaObj = createObject( "java", "some.package.MyJavaClass" ).init();
<cfset myVal = myJavaObj.someMethod()>;

I have a DataSource defined in my application.cfc. If needed, I can also define a DataSource in the Lucee Web Adminstrator.

How can I get a reference to this DataSource within my Java class? Ideally, I’d like back an object of type javax.sql.DataSource.

Appreciate any help that anyone can provide, Thanks!

Raj


#2

This is an excerpt from code I use… Technically I suppose you only need the lucee line.

        if (Server.Coldfusion.ProductName is "Lucee") {
            con = getPageContext().getDataSourceManager().getConnection(getPageContext(), dsn, Username, Password);
        } else {
            ds=createobject("java","coldfusion.server.ServiceFactory").getDataSourceService().getDataSource(dsn);
            con = ds.getConnection(Username,Password);
        }

I know you asked for a datasource instead of a connection - it doesn’t look like DatasourceManagerImpl has an easy way to get that. (You see the ACF one does return a Datasource, Lucee not so much) . But if you get connection objects you also have the benefit of leveraging Lucee’s connection pools.

Another option would be to create a CFC that implements the getConnection() and getConnection(username, password) methods like javax.sql.DataSource defines, and use CreateDynamicProxy (https://cfdocs.org/createdynamicproxy) to pass an instance of your CFC as a javax.sql.DataSource implementation.


#3

DatasourceManagerImpl here


#5

Yep!

User and pass can be null- it’ll use whats in the administrator if not provided.