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.

@ThingsExpo Stories
It is of utmost importance for the future success of WebRTC to ensure that interoperability is operational between web browsers and any WebRTC-compliant client. To be guaranteed as operational and effective, interoperability must be tested extensively by establishing WebRTC data and media connections between different web browsers running on different devices and operating systems. In his session at WebRTC Summit at @ThingsExpo, Dr. Alex Gouaillard, CEO and Founder of CoSMo Software, presented ...
Most people haven’t heard the word, “gamification,” even though they probably, and perhaps unwittingly, participate in it every day. Gamification is “the process of adding games or game-like elements to something (as a task) so as to encourage participation.” Further, gamification is about bringing game mechanics – rules, constructs, processes, and methods – into the real world in an effort to engage people. In his session at @ThingsExpo, Robert Endo, owner and engagement manager of Intrepid D...
Recently, WebRTC has a lot of eyes from market. The use cases of WebRTC are expanding - video chat, online education, online health care etc. Not only for human-to-human communication, but also IoT use cases such as machine to human use cases can be seen recently. One of the typical use-case is remote camera monitoring. With WebRTC, people can have interoperability and flexibility for deploying monitoring service. However, the benefit of WebRTC for IoT is not only its convenience and interopera...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution. In his session at @ThingsExpo, Akvelon expert and IoT industry leader Sergey Grebnov provided an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
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.
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abilit...
In his session at Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to maximize project result...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. In his session at @BigDataExpo, Jack Norris, Senior Vice President, Data and Applications at MapR Technologies, reviewed best practices to ...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Two weeks ago (November 3-5), I attended the Cloud Expo Silicon Valley as a speaker, where I presented on the security and privacy due diligence requirements for cloud solutions. Cloud security is a topical issue for every CIO, CISO, and technology buyer. Decision-makers are always looking for insights on how to mitigate the security risks of implementing and using cloud solutions. Based on the presentation topics covered at the conference, as well as the general discussions heard between sessio...
To Really Work for Enterprises, MultiCloud Adoption Requires Far Better and Inclusive Cloud Monitoring and Cost Management … But How? Overwhelmingly, even as enterprises have adopted cloud computing and are expanding to multi-cloud computing, IT leaders remain concerned about how to monitor, manage and control costs across hybrid and multi-cloud deployments. It’s clear that traditional IT monitoring and management approaches, designed after all for on-premises data centers, are falling short in ...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
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 ...