Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

A Cold Cup o' Joe

A Cold Cup o' Joe

Without a doubt, one of the most powerful assets available from the ColdFusion and Javamarriage is the simple ability to call up anything from the extensive Java class libraries.

In this article we'll look at the basics of working with Java in ColdFusion. I'll specifically talk about the different ways to create and use a Java object within your templates. As with most things, there are a few twists and turns when you mix technologies.

Configuration
It's important to make certain that the ColdFusion Server's Java settings are properly configured. Misconfiguration can lead to poor server performance and considerable frustration for the developer. Check the settings with the information in the ColdFusion Server's documentation and in Part 1 of this series (CFDJ, Vol. 3, issue 1).

In this article you'll be working with some simple classes that must be placed somewhere in the ColdFusion Server's Java CLASSPATH setting. This can be configured through the CLASSPATH setting on the ColdFusion Admin-istrator's Java Settings panel.

For example, on my Windows machine it is:

C:\CFusion\CFX;C:\CFDJ\javalib
and on my Linux machine:
/opt/coldfusion/cfx:/usr/local/CFDJ/javalib

Hello, Java
Creating a Java class for use in a ColdFusion template doesn't re-quire any special handling or subclassing (see Listing 1, HelloWorld). Actually, using it doesn't require much either, just a simple call to <CFOBJECT> or the CreateObject function in <CFSCRIPT>.

Tag, You're It
Through the <CFOBJECT> tag, ColdFusion can create an instance of nearly any Java class in the ColdFusion Server's Java CLASSPATH setting. This makes <CFOBJECT> one of the most powerful tags in the language's repertoire. Creating a Java object with <CFOBJECT> requires only four attributes: Type, Action, Class, and Name. The Type attribute allows <CFOBJECT> to identify which kind of object handling it will use; in this case it'll always be a value of "Java". The Action attribute specifies the instantiation method of the object, either "Create" or "Connect"; in this case it'll always be a value of "Create". The Class attribute specifies the name of the Java class to be instantiated; since it refers to a Java class name it's case sensitive and, if necessary, should be fully qualified with a package path. The Name attribute is the name of the object variable that's to be created. As you can see in the following snippet:

<CFOBJECT Type="java" Action="create" Class="HelloWorld" Name="hw">
Accessing a method of the Hello-World class is just as easy:
<CFOUTPUT>
#hw.greeting()#
</CFOUTPUT>

Follow the Script
Within a <CFSCRIPT> block, objects are created with the CreateObject function. The syntax for creating Java objects is pretty simple and requires only two arguments: Type and Class. The Type argument identifies which kind of object handling to use; in this case it'll always be a value of "Java". The Class argument is the name of the Java class to be instantiated. As with <CFOBJECT>, the class name is case sensitive and, if necessary, should be fully qualified with a package path. The function returns a handle to an object.

Once the object is created, the usage is comparable to the usage in a <CFOUTPUT> block:

<CFSCRIPT>
hw = CreateObject("Java",
"HelloWorld"); WriteOutput(hw.greeting());
</CFSCRIPT>

Digging Deeper
The examples from the previous snippets work smoothly enough, but seldom are classes that simple. Working with more complex classes requires a little more investigation, so we've graduated the HelloWorld class a bit (see the Hello class in Listing 2). Further, showing the intricacies of working with objects requires a busier example (see Listing 3). For the sake of convenience I used line numbers, which allow me to focus on specific aspects of object creation and usage since I'm going to jump around a bit.

Static Members
Let's begin with the following snippet from Listing 3:

14. hw2 = CreateObject("java", "Hello");
This single statement causes the ColdFusion Server's JVM to load the specific class; however, it doesn't create an instance. This is an interesting state to exist in - the code that makes up a class is placed in memory but it's not executing. Not until reference to the newly created object is made is it really instantiated. It will then have its own internal state and its variable values will likely be different from other executing instances of the same class. Some classes have static members that are independent of their instantiation and can be accessed without causing the object to be created. This nuance of Java has no ColdFusion equivalent, but it can be very useful. The basic Java class library abounds with static members; in fact, the entire java.lang.Math class, used for general purpose math functions, is static. This can be seen in the following lines:
16. WriteOutput("<h2>Displaying a static member</h2>");
17. WriteOutput(hw2.DEFAULT_STYLE);

At this point it's still not an executing object.

Object Construction
Returning to line 14, we see the creation of the Hello class. Again, there's no instantiated object, only the class is loaded. While access to static class members won't instantiate the object; as soon as a nonstatic method or property is accessed the object will be instantiated with the default class constructor. Until then CFML lets you call an alternate class constructor, as seen here:

19. hw2.init("Yo");
By calling the init method of the loaded class, the interpreter will create the object with one of the alternate constructors defined in the class. In this case, the snippet from line 19 calls the constructor that defines the greeting style for the object. Inspecting the Hello class, however, won't turn up any method called init. This phantom method is a special mechanism in CFML that aliases the class constructors. This does pose a slight problem for classes that actually define real methods called init. Calls to a "real" init method, even after object construction, will cause an exception to be raised.

Overloaded Methods
After line 19 an instance of the class is created:

21. WriteOutput("<h2>Alternate Greetings</h2>");
22. WriteOutput(hw2.greeting());
23. WriteOutput("<br>");
24. WriteOutput(hw2.greeting("Dude"));
What's of major interest in this snippet are the two different calls to the greeting method. What might be inferred is that the greeting method has an optional argument, like many CFML functions. However, upon reviewing the Java code in Listing 2, it's found that greeting is an overloaded method. This means there are two different methods with the same name but distinctly different possible arguments. In this example there's nothing particularly special about the functionality posed by either method, but in a more complex class this is often not the case. An example of this is the getConnection method of the java.sql.DriverManager class.

According to the online documentation (CFML Language Reference, Chapter 1: ColdFusion Tags, CFOBJECT Type="JAVA" and Chapter 2: ColdFusion Functions, CreateObject), the current version of ColdFusion supports only overloaded methods as long as they each have a different number of arguments. As might be expected, this overloading rule applies to constructors as well. Sadly, simply changing the data type of one of the arguments in your Java source is insufficient and creates unpredictable results, almost certainly causing an exception to be raised. After some investigation I found that absolute failure is not assured, and there does seem to be some rationale to the selection of which class method the call is routed to. Since there's no absolute guarantee of an exception, this is something that should be taken into consideration during those late-night debugging sessions.

I'll leave that to your experimentation.

Wrapping It Up
In this article we've investigated two different ways to construct objects in CFML, the flexibility of static members, how to use alternate constructors, and the twists with overloading.

Among the things I'll talk about in Part 4 of this series are the JavaCast function, structured exception handling, and a solution to the problem of loading and unloading Java classes from the ColdFusion Server's JVM instance.

Minor adjustments
Not long ago I had an e-mail exchange with Steven Erat, a support engineer at Allaire, and he gave me a few pointers on configuring ColdFusion 4.5.x with Sun's JDK 1.3. As it turns out, a few adjustments to the settings need to be made before the newer JVM works politely with the ColdFusion Server on the Linux platform. I didn't have any problems under Windows 2000.

You can get the Java 2 Platform, Standard Edition v1.3 from Sun's Javasoft Web site, www.javasoft.com/j2se/1.3/. If you want access to the Enterprise APIs, you'll need to download it separately as the J2EE for 1.3 actually lies on top of the Standard Edition. The folks at Sun have done you a favor if you're running on Red Hat as the 1.3 JDK can be gotten in RPM format. Never fear, though: if you're not using a package management system or RPM you can also get it as a tarball. What's more, I've been told informally that the HotSpot compiler works better with ColdFusion than it did with previous versions.

Once installed, you'll need to make three changes: the Java Virtual Machine Path in the Administrator, the LD_LIBRARY_PATH in the ColdFusion Server's start script, and the Implementation Options, also in the Administrator.

Initially, after installing v1.3 on my machine, I just changed the path settings to point at the new JVM library in my JVM path in the Java settings panel of the Administrator. For example:

/usr/local/java/jre/lib/i386/hotspot/ libjvm.so
Then, when I did a test, a confusing message displayed in my browser:
The JVM library could not be found. Please check if the file specified in the ColdFusion Administrator actually exists.
This was pretty vexing after doing a directory listing a few times on an existing file and not being able to put two and two together. It wasn't until I looked in the ColdFusion logs (server.log) that I found my problem:
Error occurred during initialization of VM
Unable to load native library: /usr/local/java/jre/lib/i386/hotspot/ libjvm.so: undefined symbol: jdk_sem_post

I'll attribute it to lack of caffeine but it took me more than a moment to realize that my LD_LIBRARY_PATH setting must not be right. After careful inspection I made a few adjustments:

JAVAPATH=/usr/local/java

LD_LIBRARY_PATH=$CFHOME/lib:$JAVAPATH/lib/ i386:$JAVAPATH/jre/lib/i386:$JAVAPATH/jre/ lib/i386/hotspot:$JAVAPATH/jre/lib/i386/ native_threads

At this point I was still getting an error in the browser, but the message in the log was different:
#
# HotSpot Virtual Machine Error, Internal Error
# Please report this error at
# http://java.sun.com/cgi-bin/bugreport.cgi
#
# Error ID: 4F533F4C494E55580E4350500570
#
# Problematic Thread: "Fatal","TID=9224","02/25/01","14:02:21", "Caught a fatal signal (11) - Aborting"
#

Reviewing a link that Mr. Erat sent me (http://developer.java.sun.com/developer/bugParade/bugs/4397350.html), I found I needed to add a switch in the Implementation Options setting in the Java settings panel of the Administrator:

-XX:+AllowUserSignalHandlers
Once I made this addition, everything ran as expected.

From my e-mail exchanges I've heard that these adjustments are supposed to be solid for the current betas of ColdFusion 5.0 as well. I haven't had time to verify this, though.

More Stories By Guy Rish

Guy Rish is a ColdFusion and .NET developer at Vente as well as President at Gestaltech. He is an active developer and writer for various languages and technologies, and has contributed work in books on ColdFusion MX, Flash MX, and Dreamweaver MX. He blogs at ccoj.coldfusionjournal.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.
SYS-CON Events announced today that Fusic will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Fusic Co. provides mocks as virtual IoT devices. You can customize mocks, and get any amount of data at any time in your test. For more information, visit https://fusic.co.jp/english/.
In his session at @ThingsExpo, Greg Gorman is the Director, IoT Developer Ecosystem, Watson IoT, will provide a short tutorial on Node-RED, a Node.js-based programming tool for wiring together hardware devices, APIs and online services in new and interesting ways. It provides a browser-based editor that makes it easy to wire together flows using a wide range of nodes in the palette that can be deployed to its runtime in a single-click. There is a large library of contributed nodes that help so...
SYS-CON Events announced today that Enroute Lab will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Enroute Lab is an industrial design, research and development company of unmanned robotic vehicle system. For more information, please visit http://elab.co.jp/.
Agile has finally jumped the technology shark, expanding outside the software world. Enterprises are now increasingly adopting Agile practices across their organizations in order to successfully navigate the disruptive waters that threaten to drown them. In our quest for establishing change as a core competency in our organizations, this business-centric notion of Agile is an essential component of Agile Digital Transformation. In the years since the publication of the Agile Manifesto, the conn...
Real IoT production deployments running at scale are collecting sensor data from hundreds / thousands / millions of devices. The goal is to take business-critical actions on the real-time data and find insights from stored datasets. In his session at @ThingsExpo, John Walicki, Watson IoT Developer Advocate at IBM Cloud, will provide a fast-paced developer journey that follows the IoT sensor data from generation, to edge gateway, to edge analytics, to encryption, to the IBM Bluemix cloud, to Wa...