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.

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:

and on my Linux machine:

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:

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:

hw = CreateObject("Java",
"HelloWorld"); WriteOutput(hw.greeting());

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:


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:

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.

IoT & Smart Cities Stories
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and G...
Discussions of cloud computing have evolved in recent years from a focus on specific types of cloud, to a world of hybrid cloud, and to a world dominated by the APIs that make today's multi-cloud environments and hybrid clouds possible. In this Power Panel at 17th Cloud Expo, moderated by Conference Chair Roger Strukhoff, panelists addressed the importance of customers being able to use the specific technologies they need, through environments and ecosystems that expose their APIs to make true ...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
We are seeing a major migration of enterprises applications to the cloud. As cloud and business use of real time applications accelerate, legacy networks are no longer able to architecturally support cloud adoption and deliver the performance and security required by highly distributed enterprises. These outdated solutions have become more costly and complicated to implement, install, manage, and maintain.SD-WAN offers unlimited capabilities for accessing the benefits of the cloud and Internet. ...
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
DXWorldEXPO LLC announced today that "IoT Now" was named media sponsor of CloudEXPO | DXWorldEXPO 2018 New York, which will take place on November 11-13, 2018 in New York City, NY. IoT Now explores the evolving opportunities and challenges facing CSPs, and it passes on some lessons learned from those who have taken the first steps in next-gen IoT services.
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.