Guy Rish

Subscribe to Guy Rish: eMailAlertsEmail Alerts
Get Guy Rish via: homepageHomepage mobileMobile rssRSS facebookFacebook twitterTwitter linkedinLinkedIn

Related Topics: ColdFusion on Ulitzer, Java Developer Magazine

CFDJ: Article

A Cold Cup O'Joe: Part 6 of 8

A Cold Cup O'Joe: Part 6 of 8

With Java's ever-broadening list of class APIs, your CFX has few limitations.

However, shortcomings in the CFX model could make developing solutions a little tricky. Since the ColdFusion server bootstraps CFXs, debugging them poses certain challenges.

In Part 5 of this series (CFDJ, Vol. 3, issue 8) I introduced the basics of writing CFX tags in Java; this merely scratched the surface though. A simple "Hello, World" tag, even one driven by a query such as the second example I provided in Part 5 (see sidebar), is hardly sufficient to show the details of what can be done with a Java CFX tag.

As promised, in Part 6 I delve further into the CFX model by demonstrating some of the Macromedia-recommended debugging techniques, and talk about how you can do things in a Java CFX that would be a little more difficult in C++.

Check Your Tools
Of the 14 classes that comprise the Java CFAPI class library, I discussed only four of them in Part 5. These four classes form the basis of the majority of the interactions needed for working with ColdFusion's CFX interface (see Figure 1).

The CustomTag class is the foundation of every Java CFX tag. The Request class contains all the incoming parameters of the tag, and an instance of it is passed to the CFX tag entry point. The Response class enables data to be sent back to the classing logic, and an instance of it is passed to the CFX tag entry point. The Query class allows you to manipulate any ColdFusion query passed into the CFX tag. These four classes are fairly robust and you can accomplish a broad number of things with them.

Check the Printout
Print-to-screen is a tried-and-true debugging tool. Never elegant or clever, a language's print-to-screen commands are still the cornerstone of debugging. It's a minor challenge using this staple of software development in a CFX; content sent to System.out, the typical print-to-screen destination, doesn't enter the same output stream that the ColdFusion Server sends back to the Web server. However, you can manage this two ways through the Response object that the ColdFusion Server passes to your CFX when it gets called.

The write method of the Response class is used to return formatted output to the ColdFusion Server's output stream. Typically for the construction of an HTML user interface, write can also be used to display debugging information.

This technique, like all uses of the print-to-screen method, has a serious drawback. Not only does it disturb your screen output, but once you're finished, you must remove all calls to write that are used for debugging.

Using an update of the tried-and-true "Hello, World" example from Part 5, HelloWorld1.java (see Listing 1) shows an example of this. The results can be observed by simply executing the tag in a ColdFusion template (see Listing 2).

I registered the CFX as "cfx_helloworld" in the ColdFusion Administrator as discussed in Part 5. We'll be making a few different iterations to the "Hello, World" example throughout this article, and each time I'll update the "class file" setting of the same tag registration.

The writeDebug method of the Response class is a slight improvement. It still relies on the print-to-screen concept, but only under a specific circumstance. When the CFX is invoked with the DEBUG attribute set to "on," it will trip an internal flag. The writeDebug method will print only if this flag is tripped.

Replacing all the write methods with writeDebug methods will give us a CFX as seen in HelloWorld2.java (see Listing 3). Don't forget to update the CFX's "class file" setting in the ColdFusion Administrator. In a ColdFusion template (see Listing 4) I've made two calls to the newer version of our CFX, one with the DEBUG attribute set to "on" and the other with the attribute set to "off." Notice the differing results.

This is a little better, but again it's still messy.

Faking It
What if there was a way to run a custom tag from the command line? What if, instead of the ColdFusion Server instantiating the CFX, you could do it? Macromedia provides for just such a thing with the help of three classes: DebugRequest, DebugResponse, and DebugQuery. These debugging versions allow you to mimic the way the ColdFusion Server might interact with the CFX so you can test it right from the command line. This functionality is unique to Java CFXs, and while similar things can be rigged with their C++ cousins, Macromedia didn't provide a pre-packaged solution for them.

The Main Thing
The code in processRequest doesn't change, but I've added a new method to the class, main. This new iteration of the CFX, HelloWorld3.java (see Listing 5), creates its own debugging versions of Request and Response and passes them to an instance of itself (see lines 1-18).

Using a Java Hashtable, I created the arguments I want passed to the tag instance (lines 8 and 9). I use this Hashtable in the constructor of the DebugRequest instance (line 11). Neither the DebugResponse instance (line 12) nor the tag (line 14) requires construction. The tag's real functionality is invoked (line 16) when processRequest is called. Then it's a simple matter to display the results via the DebugResponse class's printResults (line 18), which displays directly to System.out.

Greet Them, One and All
To demonstrate the use of the DebugQuery class I'll use the HelloQuery CFX from Part 5. This tag receives a Query to loop over as the source of its input, nothing overly complex (see sidebar). I made some adjustments to HelloQuery.java (see Listing 6) and it can now be compiled and called from the command line.

I built a hash table of attributes to pass to processRequest, just as before (lines 10 and 11). Notice that I actually add the QUERY attribute and give it a value of "names". The value is unimportant, but it's vital that the QUERY attribute exists.

If you recall from Part 5, to pass a CFML Query to a CFX it had to be passed via the QUERY attribute. The HelloQuery CFX actually tests for this attribute before retrieving the Query object with the Request's getQuery. Because it's possible through the debug versions to pass the Query without using the QUERY attribute, it's vital to create a QUERY attribute so as not to disrupt the current functionality of the tag. At first this might seem silly. If the tag is designed to receive a Query object, why check for the QUERY attribute at all? The answer to that would be: What if the QUERY attribute were being used to pass optional data? This leaves the door open for increased flexibility, especially when this flexibility can be used to overcome the data-passing limitations imposed by the CFX model. In this way nothing is assumed; the code always tries to check itself.

To create a DebugQuery instance two String arrays are needed. One array contains the names of the columns (line 14), the other is a multidimensional array, an array of column values within an array that comprises the rows (lines 15-18). An instance can then be created (line 20) and passed to the DebugRequest constructor (line 22).

The rest is the same as in the previous example.

Debug Class Dividends
All in all, using the debugging classes is not a very complicated activity. The real dividend is that you can run it from the command line, but because of that you can use traditional debuggers to step through the code as it executes. Just when you thought it was going to get tough...

Under Observation
It would hardly seem decent to write an article that contains little more than what can be found in the documentation already. Sure, I've covered a few extra little twists, but nothing you couldn't have gleaned with careful reading and a little experimentation. So I've brought something more to the table: leveraging some of the technology I used in the JVMLog class I introduced in Part 4 (CFDJ, Vol. 3, issue 6), you can take your debugging one step further.

The JVMLog class (reversibly) hijacks the JVM's standard I/O PrintStream instance. It does so with another simple class that I created called ObservablePrintStream. The ObservablePrintStream is a subclass of the normal PrintStream used by the JVM, so my class could polymorphically stand in for the original. The interesting thing about ObservablePrintStream is that it implements the Observer design pattern.

I was unable to use Java's standard Observable class since my PrintStream subclass would have had to inherit from something other than PrintStream - thus completely ruling out my ability to hijack the JVM's PrintStream in the first place.

The point of the Observer design pattern is to set up a relationship of objects that can communicate with each other in a publish/subscribe fashion. An object interested in getting notified whenever something happens "subscribes" to the object in which it is interested. Specifically, anything that's intended for the screen via System.out will also get sent to the subscribing objects.

What I have done is create a set of templates and Java classes that will allow you to install the ObservablePrintStream to the JVM and then "subscribe" objects so you can monitor things printed to the JVM's System.out instances.

Using the ColdFusion template ManageObserver.cfm (see Listing 7) will allow you to toggle the hijacking of the JVM's PrintStream. (Listings 7-10 can be found on the CFDJ Web site, www.sys-con.com/coldfusion/ sourcec.cfm.) Using another template, ManageNetObserver.cfm (see Listing 8), you can toggle the installation of a socketed observer. Then, using either the client I created, Monitor.java (see Listing 9), or a telnet application, you can connect to port 2525 (configurable from ManageNet-Observer.cfm) and watch for anything written to the JVM's System.out to be displayed. To this end I've created a new version of the "Hello, World" CFX, HelloWorld4.java (see Listing 10), where I've done a search and replace on all the writeDebug calls to change them into println calls off System.out.

Wrapping It Up
There are a number of challenges when it comes time to debug your Java extensions, but they don't need to be insurmountable. Using the built-in tools provided by Macromedia you stand a good chance of solving most any debugging problem.

Reusable Tools
When I created the Observable-PrintStream I knew it would be a useful tool. I've gotten considerable mileage out of it in more than just my work with ColdFusion. I've no doubt that this simple tool could be leveraged in ways that I have yet to foresee.

It seems I have an apology to make. There was an error in the source HelloQuery.java in Part 5. The for-loop on line 35 is incorrect and will cause the tag to fail at runtime with a Java IndexOutOf-BoundsException. That line should actually read:

for(nRowIndex = 1; nRowIndex <= nRowCount; nRowIndex++)

Notice that the loop index starts at 1. It seems that a Query is base 1, so it was necessary to adjust the starting position and the terminating condition for the code to function correctly. I've no excuse for this error in judgment. I can only throw myself at your mercy.

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.