Day 9: ColdFusion 10 and Enhanced Java Integration – Part 2

It’s DAY 9 and I enjoyed last 8 days with ColdFusion 10 and as days pass my curiosity graph going high. In yesterday post discuss about how easy to use your java class/jar file within your project. But you may also want to use power of ColdFusion in Java class and this one is possible with use of CFCProxy. Well CFCProxy available since ColdFusion 7 ( I guess) but never get chance to look into this. 

I continue using previous post example to explain how to call ColdFusion component function within Java class.

Employee.cfc

[code:cf]<cfcomponent output="false" displayname="Employee">
<cffunction name="sayCFHello" access="public" output="false" returntype="String">
<cfargument name="name" required="true">
<cfreturn "ColdFusion says hello to " & arguments.name>
</cffunction>
</cfcomponent>[/code]
Simple coldfusion component having function "sayCFHello" which take name as an argument and return hello message.

Hello.java

[code:java]
import coldfusion.cfc.CFCProxy;
public class Hello{
public String sayHello(){
return "Hello World!!!!";
}
public String sayHello(String name){
return "Hello " + name + "!!!!!";
}
public String sayHelloThroughCF(String name){
String message = "";
try{
CFCProxy empCFC = new CFCProxy("D:\\projects\\allmytests\\cf10\\day9\\Employee.cfc",true);
Object[] args = {name};
message = (String) empCFC.invoke("sayCFHello",args);
}
catch(Throwable e){
e.printStackTrace();
}
return message;
}
}[/code]

My custom java class having three functions, overloaded sayHello function with and without argument used in previous post and added one more function named "sayHelloThroughCF" which take single argument and invoke Employee.cfc’s sayCFHello() function. We may need to import CFCProxy from coldfusion library. CFCProxy will create proxy from provided file location in it’s argument. You may need to pass physical location of CFC as first argument and second argument directInvoke you can pass true/false (Introduced in ColdFusion 10). If true, request doesn’t go through ColdFusion chain and give better performance.

You can use invoke function of proxy object to call ColdFusion component function and all arguments you can passed as array of objects.

sayHello.cfm

[code:cf]
<cfobject type="java" class="Hello" name="myObj"> 
<cfoutput>
#myObj.sayHello()# <br/>
#myObj.sayHello(‘Pritesh’)# <br/>
#myObj.sayHelloThroughCF("Pritesh")#
</cfoutput>[/code]

And here is output

Hello World!!!!
Hello Pritesh!!!!!
ColdFusion says hello to Pritesh 

To call CFC you ColdFusion class loader must be current class loader. If you want to compile your java code using javac file in command prompt then you must specify necessary file as classpath. 
For ColdFusion 10 your command may look like below..

javac -classpath "c:\\coldfusion10\cfusion\lib\cfusion.jar;c:\\coldfusion10\cfusion\wwwroot\WEB-INF\lib\cfmx_bootstrap.jar" Hello.java