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
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
In his session at 21st Cloud Expo, Raju Shreewastava, founder of Big Data Trunk, provided a fun and simple way to introduce Machine Leaning to anyone and everyone. He solved a machine learning problem and demonstrated an easy way to be able to do machine learning without even coding. Raju Shreewastava is the founder of Big Data Trunk (www.BigDataTrunk.com), a Big Data Training and consulting firm with offices in the United States. He previously led the data warehouse/business intelligence and B...
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, examined the regulations and provided insight on how it affects technology, challenges the established rules and will usher in new levels of diligence arou...
Nordstrom is transforming the way that they do business and the cloud is the key to enabling speed and hyper personalized customer experiences. In his session at 21st Cloud Expo, Ken Schow, VP of Engineering at Nordstrom, discussed some of the key learnings and common pitfalls of large enterprises moving to the cloud. This includes strategies around choosing a cloud provider(s), architecture, and lessons learned. In addition, he covered some of the best practices for structured team migration an...
The 22nd International Cloud Expo | 1st DXWorld Expo has announced that its Call for Papers is open. Cloud Expo | DXWorld Expo, to be held June 5-7, 2018, at the Javits Center in New York, NY, brings together Cloud Computing, Digital Transformation, Big Data, Internet of Things, DevOps, Machine Learning and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding busin...
No hype cycles or predictions of a gazillion things here. IoT is here. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, an Associate Partner of Analytics, IoT & Cybersecurity at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He also discussed the evaluation of communication standards and IoT messaging protocols, data...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Recently, REAN Cloud built a digital concierge for a North Carolina hospital that had observed that most patient call button questions were repetitive. In addition, the paper-based process used to measure patient health metrics was laborious, not in real-time and sometimes error-prone. In their session at 21st Cloud Expo, Sean Finnerty, Executive Director, Practice Lead, Health Care & Life Science at REAN Cloud, and Dr. S.P.T. Krishnan, Principal Architect at REAN Cloud, discussed how they built...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
22nd International Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, and co-located with the 1st DXWorld Expo will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud ...
DevOps at Cloud Expo – being held June 5-7, 2018, at the Javits Center in New York, NY – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Among the proven benefits,...
@DevOpsSummit at Cloud Expo, taking place June 5-7, 2018, at the Javits Center in New York City, NY, is co-located with 22nd Cloud Expo | 1st DXWorld Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait...
Cloud Expo | DXWorld Expo have announced the conference tracks for Cloud Expo 2018. Cloud Expo will be held June 5-7, 2018, at the Javits Center in New York City, and November 6-8, 2018, at the Santa Clara Convention Center, Santa Clara, CA. Digital Transformation (DX) is a major focus with the introduction of DX Expo within the program. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive ov...
SYS-CON Events announced today that T-Mobile exhibited at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. As America's Un-carrier, T-Mobile US, Inc., is redefining the way consumers and businesses buy wireless services through leading product and service innovation. The Company's advanced nationwide 4G LTE network delivers outstanding wireless experiences to 67.4 million customers who are unwilling to compromise on qua...
SYS-CON Events announced today that Cedexis 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. Cedexis is the leader in data-driven enterprise global traffic management. Whether optimizing traffic through datacenters, clouds, CDNs, or any combination, Cedexis solutions drive quality and cost-effectiveness. For more information, please visit https://www.cedexis.com.
SYS-CON Events announced today that Google Cloud has been named “Keynote 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. Companies come to Google Cloud to transform their businesses. Google Cloud’s comprehensive portfolio – from infrastructure to apps to devices – helps enterprises innovate faster, scale smarter, stay secure, and do more with data than ever before.
SYS-CON Events announced today that Vivint to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. As a leading smart home technology provider, Vivint offers home security, energy management, home automation, local cloud storage, and high-speed Internet solutions to more than one million customers throughout the United States and Canada. The end result is a smart home solution that sav...
SYS-CON Events announced today that Opsani 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. Opsani is the leading provider of deployment automation systems for running and scaling traditional enterprise applications on container infrastructure.
SYS-CON Events announced today that Nirmata 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. Nirmata provides a comprehensive platform, for deploying, operating, and optimizing containerized applications across clouds, powered by Kubernetes. Nirmata empowers enterprise DevOps teams by fully automating the complex operations and management of application containers and its underlying ...
SYS-CON Events announced today that Opsani to exhibit at SYS-CON's 21st Cloud Expo, which will take place on October 31 through November 2nd 2017 at the Santa Clara Convention Center in Santa Clara, California. Opsani is creating the next generation of automated continuous deployment tools designed specifically for containers. How is continuous deployment different from continuous integration and continuous delivery? CI/CD tools provide build and test. Continuous Deployment is the means by which...