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

Matching ColdFusion with Server-Side Java

Matching ColdFusion with Server-Side Java

This article focuses on some interesting features of ColdFusion 4.5 and server-side Java. Introduced in ColdFusion 4 (and greatly extended in 4.5), the CF Server supports Java by providing three ways to access server-side Java with ColdFusion. (We're not talking about client-side Java, which is built into ColdFusion using applets, e.g., the CF tree applet.)

  1. Accessing the usual Java classes/beans
  2. Accessing EJBs
  3. Wrapping Java code into a CFX custom tag
The first two types are supported in ColdFusion through the <CFOBJECT> tag as well as the CreateObject() function, while the third type enables developers to wrap custom Java code into a custom tag interface.

Since this article presents examples of server-side Java code and how to use it within ColdFusion, you should have a basic understanding of Java and it's concepts. The Java Development Kit (JDK) includes the Java compiler as well as the runtime environment (the virtual machine) and can be downloaded from JavaSoft at www.javasoft.com. It's necessary to install the JDK to run the examples in this article. Tutorials and reference documentation about the Java language as well as how to install the JDK can also be located on the JavaSoft Web site.

What's the Point?
The main idea is to connect ColdFusion to components written in other languages so it will also be available to other environments. These are mainly distributed objects such as D/COM, CORBA, and EJBs, whereas the Java side focuses on EJBs and simple Java classes (like normal JavaBeans), as well as CFXs developed in Java. ColdFusion developers can easily reuse existing components/objects that are written in other languages or even write their own components in these languages to achieve performance gains that are dependent on the task the component should solve. CFML Isn't suitable for certain components such as image processing, since this involves complex algorithms that will run magnitudes slower in CFML than in Java.

Although the types of distributed objects (as mentioned) include D/COM and CORBA, this article focuses on Java components and doesn't take the others into account. Even though using D/COM and CORBA objects within ColdFusion is to a certain extent similar to using Java objects, their architecture is different, so a full description of D/COM and CORBA accesses is beyond the scope of this article.

Before We Start...
To connect server-side Java to ColdFusion we need to meet some requirements. These include the proper installation of the JDK (see above), as well as properly configuring ColdFusion Server (4.5) to enable it to talk to Java. The first part (installing the JDK) varies for different operating systems and is best described in the installation tutorials available at www.javasoft.com.

The other part is easier since it has to be done in the CF Administrator (see Figure 1). In the Administrator you can enable Java by providing ColdFusion with the path to the Java Virtual Machine, which points to the file jvm.dll (if you're using NT; otherwise the file may differ). This file is located in the directory c:/program files/ javasoft/ jre/ 1.2/bin/ classic/jvm.dll if you've installed only the Java Runtime Environment (JRE), or in c:/jdk1.2.2/jre/bin/classic/jvm.dll if you've installed the full JDK. Also, the ClassPath for this VM has to be set inside the CF Admin to ensure that the ColdFusion Server can find the classes you wish to access. For general use of server-side Java this should be at least c:\programfiles\jdk1.2.2\jre\lib\rt.jar, c:\cfusion\java\classes\cfx.jar and c:\cfusion\java\classes. When accessing classes that aren't located in the specified ClassPaths (which results in a ClassNotFound Exception), you have to add the appropriate path to the Java ClassPath. To be sure these settings take effect, restart the ColdFusion service after changing it.

From the other settings one can also decide to start up the JVM within ColdFusion automatically at each start of the CF Server. This increases performance slightly for the first request of server-side Java (and might prevent errors if accessing Java for the first time, and ColdFusion from taking too long to start the VM on the fly). Be aware that this option could also prevent your ColdFusion Server from starting if the Java settings are wrong. Therefore I suggest you leave this option unchecked when testing server-side Java with ColdFusion for the first time, and then (assuming everything works fine) you're free to decide whether to check this option to get a small performance increase for the first Java access after a restart.

Lets Take a Look Inside
After all the conceptional and configurational stuff I guess you're curious to see some details and code. Let's look at a few examples. First I'd like to introduce the necessary tag to access and use external objects (including Java objects), such as <CFOBJECT> and it's equivalent function, CreateObject(). With this tag/function you can create objects from the usual Java classes as well as EJBs, access their properties, and invoke their methods. Objects are returned inside CFML as simple variables, meaning you can assign them and their methods results using <cfset> (this includes even complex data types being returned, such as arrays).

The creation of a Java object within CFML can be as simple as one line:

<CFOBJECT ACTION="CREATE" TYPE="Java" CLASS="java.util.GregorianCalendar" NAME="myCalendar">

This statement simply creates an object of the type "java.util.GregorianCalendar", which is part of the JRE that's shipped with your Java installation, and saves it into the ColdFusion variable "myCalendar" for future use. Could it be simpler? When using <CFSCRIPT> you can make it as short as this:

myCalendar = createObject("JAVA", "java.util.GregorianCalendar") ;

Now we have a variable called "myCalendar" holding a java.util.GregorianCalendar object. We can do everything to this object that we can do with java.util.GregorianCalendar objects including invoking it's method "isLeapYear(year)", which checks if a given year is a leap year and returns true if it is, and false if it's not:

<cfset theResult = myCalendar.isLeapYear(2000)>.

Here the ColdFusion variable " theResult" will be true since 2000 is indeed a leap year. Note: This could also be checked within CFML using ColdFusions own function, also named "isLeapYear(year)", but doing so through the Java class is for demonstration purposes only.

The class java.util.GregorianCalendar has a default constructor (the method being invoked when the object of a class is created) that assigns the current date to the object. This enables us to display the current date of this Java object to demonstrate it's use. It can be done the following way (note that months are being counted in Java starting at zero). See Listing 1 for the full source of this example.

<CFSET theYear = myCalendar.get(myCalendar.YEAR)>
<CFSET theMonth = myCalendar.get(myCalendar.MONTH) + 1>
<CFSET theDay = myCalendar.get(myCalendar.DATE)>
Today is <b>#theMonth# / #theDay# / #theYear#</b>

That's all for our first marriage of Java with ColdFusion!

The ability to access the entire Java classes API from within ColdFusion provides a nice extension to what we can do with CF by itself. See the Java API reference at www.javasoft.com for a complete class reference. Assuming you're a curious reader, it's time to extend our simple example so that we access a self-made Java class, right? However, to do so youll need at least some basic knowledge of Java and it's concepts. As the scope of this article is limited and not a Java tutorial, I recommend that Java newbies take a brief look at the Sun Java Tutorial.

Accessing Your Own Classes
To access the self-made class example I coded a simple JavaBean (named "MakeSomewhat") that indeed does something (that's worthless and taken only to demonstrate it's basic use). It simply takes a name (as a string) and returns three sentences (as an array of strings) with the name incorporated into them (see Listing 2). That way I can show you how to pass data to that class and get return data from it.

Such simple tasks can often be solved much easier with custom tags in CFML, but as I told you in the intro, Java components are better suited for some special tasks, such as image processing or spell checking. I coded the Java class MakeSomewhat.java as a bean; it has a parameterless constructor and so-called setter- and getter-methods to input data and extract data from it. This is the basic idea behind JavaBeans - to keep all internal properties private (encapsulated in a kind of black box) and communicate with them only via the setter/getter-methods. As you may have already guessed, the methods of this class are similar to these:

getName() : name
getSentences() : sentences[]

It's important to put a custom class into a package (optional when only using in Java, but a must when using with ColdFusion). So note the line "package test;" at the top of MakeSomewhat.java that indicates that it resides in a package named "test" (represented by a directory named "test" where you compile it). This is, of course, only for testing as Sun recommends you use more meaningful package names like "com.myDomain.myProject" where each token (separated by the dot) is a subdirectory. After compiling the class "MakeSomewhat.java" (using javac.exe or any Java IDE), the resulting file "MakeSomewhat.class" must be accessible by the ColdFusion Server. Therefore it has to be placed into one of the directories listed above as the ClassPath under the CF Admin, or the ClassPath setting has to be extended pointing to the directory where you've saved "MakeSomewhat.class".

After placing the file where it's accessible by the CF Server you can - with only a few lines of CFML code - use it's whole functionality (see Listing 3). After instantiating an object from the MakeSomewhat class, feed it with the name "John Doe":

<CFOBJECT ACTION="CREATE" TYPE="Java" CLASS="test.MakeSomewhat" NAME="mySomewhat">
<CFSET void = mySomewhat.setName("John Doe")>

It returns an array of all three sentences with the name "John Doe" incorporated into them:

<CFSET SentenceArray = mySomewhat.getSentences()>

Overloaded Methods
In object-oriented programming it's a common practice to overload methods (including constructors). This results in multiple methods/constructors with different parameter signatures (for example, setting color values in separate RGB values or in one hex string). There's even support for overloaded methods in ColdFusion, as long as the number of arguments are different. According to Allaire, future versions of ColdFusion will have fine enhancements that allow the user to use cast functions that allow method signatures to be built more accurately. To call another constructor instead of the default one of a class (that's being called automatically when accessing a public method of a class for the first time), you have to call it explicitly using the "init()" method with the appropriate arguments:

<CFSET return = myObj.init(arg1, arg2)>

Java Exceptions
Like the exception-handling model we all know from ColdFusion, Java has an analogous type of exception model. The nice thing about this is that all exceptions thrown by Java classes invoked within CFML can be caught by the <CFTRY> <CFCATCH> tags. The message field of the <CFCATCH> variable contains the exception text thrown by Java including the class name.

CFX Custom Tags in Java
In the introduction I mentioned three types of Java accesses within ColdFusion, including developing CFXs in Java. Using CFX is quite convenient and even easier than using Java classes within CFML. As all of you know, you can simply invoke any CFX custom tag (developed in Java or C++) as follows:

<CFX_MakeSomethingUseful times=42 text="The quick brown fox jumps over the lazy dog">

This invokes a CFX with two attributes. Note that Java CFX custom tags have to be registered inside the CF Administrator with their class name and a description (see Figure 2). Be sure to use only the name of the class without the ".class" ending to avoid troubleshooting when CF cant find the CFX. Of course, the class file should be accessible to the CF Servers ClassPath specified in the CF Admin.

Even though it's easy to use CFX custom tags, it's more interesting to develop them. Let's take a look behind the scenes at CFX custom tags written in Java. As with all CFXs they can handle numerous tasks including the parsing and returning of attributes/variables, the parsing and returning of query recordsets (handy to output using CFML), the dynamic generation of HTML code for the client, and even throwing custom exceptions.

How are CFXs coded in Java? They share a method invoked from the CF Server process called "processRequest(Request, Response)" that takes a request- and response-object (much like the concept of classical servlets). The proper existence of this method is guaranteed as all CFX custom tags must implement the interface "custom tag" from Allaire in the package com.allaire.cfx located in c:\cfusion\java\ classes\cfx.jar. The request object handed into the processRequest() method as a parameter holds all attributes of the <CFX_> invocation accessible through it's attributeExists(attributename) and getAttribute- (attributename) methods. As expected, the response object has several methods for returning data into the calling template by setting variables back in the caller page (as the CALLER-scope in CFML <CF_>-CustomTags does). These methods of the response object include addQuery (name, columnarray), which adds a query result set into the caller template, which can be filled with data through the method setData() of Allaires Query object available in the cfx.jar package.

Listing 4 provides a CFML source for invoking a nice CFX custom tag called ZipBrowser that can open and parse the zip files shown (see Figure 3). The Java source code for that CFX (extended from Allaires sample code inside the CF Studio help) is provided in Listing 5.

Basically, a CFX (written in C++, Delphi, or Java) can do whatever the targeted language supports. It can communicate with the CFML template using the predefined interfaces with the CFML page regarding the passing of attributes and the returning of data. Under the hood this CFX can use other classes to solve many different tasks. Go to Allaires Tag Gallery ( www.allaire.com/developer/gallery.cfm) to search for available CFX custom tags to solve certain tasks. Also note that many software vendors have wrapped their own Java and C++ APIs into ColdFusion CFXs to support easy connection of CFML with their products, such as credit card processing software, image and charting software, and much more.

What About EJBs?
As the JavaBeans component model wasn't fitting well for transaction and database intensive tasks, a new component model was built. Named "Enterprise JavaBean," it takes a predefined set of interfaces and database transaction management features into account. The result was a complete server architecture built around it with products from IBM, BEA, and Sun, among others.

Looking inside EJBs from the Java side would extend this article's scope into that of a book, so I'll only look briefly at EJBs from the ColdFusion side. To put it simply, you can treat an EJB as if it were just another Java class. (Please, all Java gurus out there, don't flame me on this; it's just from the usage of EJBs within CFML, not the development of EJBs!) There is, of course - even when only accessing EJBs from within CFML - some overhead compared to "just another Java class," such as fetching an initial context or looking up an EJB from it's name. However, once you've instantiated an EJB object, you can treat that object within CFML like all other Java objects by accessing it's methods and properties.

Look inside the CF Studio help for some examples of using an EJB within CFML. Be aware that to understand fully the use of EJBs, you must understand the concepts behind the EJB architecture (again, out of this article's scope). For the curious among you, look at Listing 6, which contains the sample code, taken from the CF Studio help, for accessing an EJB. If some of you are interested in reading an article about using EJBs with ColdFusion, e-mail me (see address at the end of this article).

I hope this technical overview of what's possible with ColdFusion and Java may whet your appetite for more. What I personally like about ColdFusion is that the guys from Allaire constantly manage to connect CF to all kinds of standards out there, such as supporting all major native database drivers, Web protocols, directory services, data standards, distributed object technologies, and now, in CF 4.5, even Java through EJBs and normal Java classes as well as their CFX API. The best thing is that everything is there at your fingertips to use in the form of simple and efficient <tags>.

More Stories By Christian Schneider

Christian Schneider is an Allaire Certified ColdFusion and Web site developer. He has over four years of intensive experience developing CF-based intranet applications for banks and logistic corporations.

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
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities - ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups.
The standardization of container runtimes and images has sparked the creation of an almost overwhelming number of new open source projects that build on and otherwise work with these specifications. Of course, there's Kubernetes, which orchestrates and manages collections of containers. It was one of the first and best-known examples of projects that make containers truly useful for production use. However, more recently, the container ecosystem has truly exploded. A service mesh like Istio addr...
Predicting the future has never been more challenging - not because of the lack of data but because of the flood of ungoverned and risk laden information. Microsoft states that 2.5 exabytes of data are created every day. Expectations and reliance on data are being pushed to the limits, as demands around hybrid options continue to grow.
Poor data quality and analytics drive down business value. In fact, Gartner estimated that the average financial impact of poor data quality on organizations is $9.7 million per year. But bad data is much more than a cost center. By eroding trust in information, analytics and the business decisions based on these, it is a serious impediment to digital transformation.
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.
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As automation and artificial intelligence (AI) power solution development and delivery, many businesses need to build backend cloud capabilities. Well-poised organizations, marketing smart devices with AI and BlockChain capabilities prepare to refine compliance and regulatory capabilities in 2018. Volumes of health, financial, technical and privacy data, along with tightening compliance requirements by...
As IoT continues to increase momentum, so does the associated risk. Secure Device Lifecycle Management (DLM) is ranked as one of the most important technology areas of IoT. Driving this trend is the realization that secure support for IoT devices provides companies the ability to deliver high-quality, reliable, secure offerings faster, create new revenue streams, and reduce support costs, all while building a competitive advantage in their markets. In this session, we will use customer use cases...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...
DXWorldEXPO LLC announced today that "Miami Blockchain Event by FinTechEXPO" has announced that its Call for Papers is now open. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Financial enterprises in New York City, London, Singapore, and other world financial capitals are embracing a new generation of smart, automated FinTech that eliminates many cumbersome, slow, and expe...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering Cloud Expo and @ThingsExpo 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 Cloud Expo. Product announcements during our show provide your company with the most reach through our targeted audiences.
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held November 11-13, 2018, in New York City. Digital Transformation (DX) is a major focus with the introduction of DXWorldEXPO 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 over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of bus...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
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...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City and will bring together Cloud Computing, FinTech and Blockchain, Digital Transformation, Big Data, Internet of Things, DevOps, AI, Machine Learning and WebRTC to one location.
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by FinTechEXPO. ICOHOLDER give you detailed information and help the community to invest in the trusty projects. Miami Blockchain Event by FinTechEXPO has opened its Call for Papers. The two-day event will present 20 top Blockchain experts. All speaking inquiries which covers the following information can be submitted by email to [email protected] Miami Blockchain Event by FinTechEXPO also offers s...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
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...
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...