|
YOUR FEEDBACK Did you read today's front page stories & breaking news?
SYS-CON.TV SYS-CON.TV WEBCASTS |
TOP COLDFUSION LINKS CF & Java A Cold Cup o' Joe
A Cold Cup o' Joe
By: Guy Rish
Jun. 7, 2001 12:00 AM
In Part 3 of this series (CFDJ, Vol. 3, issue 4) we looked at the basics of creating and using Java objects in ColdFusion templates. In Part 4, I discuss a number of other aspects of using Java objects in CFML as well as introduce some tools that I hope will be useful to you in debugging the Java components.
Bonus
Amend the CLASSPATH setting on the Java Settings panel to include this JAR.
A Confession
public class HelloWorldUnfortunately, this doesn't work in ColdFusion. Remember, as I discussed in Part 3, a <CFOBJECT> or CreateObject call loads only the class and doesn't execute it until use. One of the things the Java command line interpreter will look for is a main method in the class file being executed. To add to the inquirer's frustration, the ColdFusion interpreter doesn't capture the standard output or standard error output of executing Java objects. Getting data or feedback from a Java object should happen though returned values from method calls. Designing a Java object that interacts with ColdFusion should reflect that ideal. So printing anything to System.out or System.err is verboten, strictly speaking. Thus a "Hello, World" in Java, written to be well behaved for ColdFusion, would look something like this: public class HelloWorldand could be used in a ColdFusion template with a few lines: <CFSCRIPT>Log It While I steadfastly agree with the whole concept of well-designed classes with queryable state information, as opposed to unsolicited feedback, I felt this was a drawback. There are plenty of times when the ability to capture both the standard and error output is valuable, even if only for logging purposes. To that end I created a class that allows you to tee tap everything written to System.out and System.err and have it directed to a log. In the JVMLog class I created you can replace the PrintStream instances used by the JVM's system object. The new PrintStream subclass that I created will allow for any data directed to it to be logged (through an Observer design pattern) before being sent to its final destinations, shown in this short <CFSCRIPT> snippet from Listing 1. <CFSCRIPT>Naturally this is something you'll have to manually toggle on and off yourself each time the ColdFusion Server is restarted. Toggling the logging mechanism off can also be done with an equally short <CFSCRIPT> snippet from Listing 2. <CFSCRIPT>This is really no great feat. I merely made the PrintStream subclass static members of JVMLog. The class file caching feature of the JVM did much of the work for me.
JavaCast - Overloading Revisited
The JavaCast function takes two arguments: Type and Variable. The Type argument specifies the Java data type the CFML variable will be converted into (Boolean, int, long, double, or String); the Variable argument is the CFML variable that's to be converted. I created a simple class called SignatureCheck (see Listing 3) that contains a method called print with several different signatures, one for each of the accepted types. Then with a template (see Listing 4) I cast a numeric CFML variable to those types. In all cases the calls to the print method of the SignatureCheck succeeded, and in all cases they called the exact same print method, the one with the primitive int as its argument. I scratched my head for a long time on this one. Reviewing the broken sample in the JavaCast documentation, I noted the order that it listed the signatures. Interestingly enough, when I shuffled the order of the print methods in Signature-Check, I received some different results. As long as the method that took the String appeared in the source file before the others, my example partially worked. A little more shuffling, recompiling, re-starting, and head scratching and I found that getting any two of the numerical signatures to work was beyond me. Whichever one ap-peared after the String signature in the source file was the one that would get called in all cases. In frustration I even created a signature with a char (which is not one of the listed castable types) only to have a truncated number begin to appear in my browser. It would seem that despite the documentation to the contrary, JavaCast doesn't work as advertised. Nested Objects A common enough practice in OO projects is to have hierarchies of nested objects. Without getting into complicated code listings, we can imagine such a hierarchy as a shelf object that contains zero to many book objects, each containing zero to many pages. It's conceivable then to obtain the name of a book with the following code snippet: shelf.getBook(2).getName();Or the contents of a page with the following: shelf.getBook(2).getPage(1).getText();It could then be expected that to get the page content, a statement like this could be used in ColdFusion: <CFSET pagecontent = shelf.getBook(2).getPage(1).getText()>Using this syntax raises an exception. It seems that the current versions of ColdFusion can't navigate nested hierarchies at all. A series of <CFSET> statements is need to drill down, such as: <CFSET book = shelf.getBook(2)>This can get rather tedious in deeply nested sets (though using <CFSCRIPT> blocks will cut the typing a little) and, unfortunately, there doesn't seem to be a way around this.
Catching Errors
Assuming a properly configured JVM, there are essentially two different classifications of errors that can be raised using Java. The first type are errors thrown by the CFML interpreter trying to load Java classes, create objects, or locate methods or properties in a class. The second type consists of exceptions thrown during the execution of a properly loaded and called Java class. Both kinds of errors are demonstrated in the template (see Listing 5) using a slightly modified version of the Hello class, from Part 3 (see Listing 6). In this template I try to create an object with a misspelling in the Class parameter of <CFOBJECT>, make a method call (with a misspelling), and finally I correctly call a method whose only purpose is to raise an exception. In all three cases I display the entire CFCATCH structure (using an exceptionally useful custom tag by Nathan Dintenfass, <CF_OBJECTDUMP>, which can be found at Allaire's TagGallery), shown in Figure 1. As you can see, the first two errors look fairly common for CFML errors, though the value of the Type key being "UNKNOWN" is troublesome. It's the third error that you're more likely to encounter. There's actually quite a bit of information to be gleaned here. The Type key has a listed value, "OBJECT"; the Message key holds the fully qualified Java exception class (in this case java.-lang.Exception); the Detail key also contains the Java exception class, a colon (if there is a message), the message sent with the raise exception, an additional period, and some additional text informing you that a Java exception occurred. I'm not overly fond of the noise in the Detail key, so within my Java code I put the message text of my exception in square brackets. This tactic allows me to dissect the string and display only the error message I really want to be displayed, as seen in this snippet: #ListGetAt(ListGetAt(CFCATCH.Detail, 1, "]"), 2, "[")#If you're using <CFSCRIPT> for your Java work you'll have to wrap that block inside your <CFTRY> block as <CFSCRIPT> doesn't yet support try/catch blocks.
Class Caching
The downside to this wonderful feature comes in the development phase of your Java components. Every time you update and recompile the source, you have to restart the ColdFusion Server to flush the JVM's class cache from its memory. As tedious as this is, it could almost be considered acceptable in small development efforts. However, providing hot fixes in a testing or staging environment is a completely different matter. Restarting the ColdFusion Server just to flush the JVM could be devastating to days' worth of functional or performance testing. Keeping it simple, an exemplification of this would be to execute the following: <CFSCRIPT>This will cause the JVM to cache the Hello class shown in Listing 6. First open the source for Hello class in your favored editor, then do a search and replace on the word "Hello," changing it to "Hi." Save, recompile, and execute the snippet again. You should see the same results. Your change won't be picked up until you restart your ColdFusion Server. I've trolled through the documentation and the forums looking for some hint of a secret Allaire setting that would allow me to restart the JVM or flush its class loader, to no avail. I had some difficulty interpreting the documentation about how to force Java CFX tags to reload (which I'll discuss in a later article in this series), but nothing for regular Java classes. After a little thinking I came up with a simple-to-use solution - I created my own custom class loader wrapped with a class factory design pattern. This class factory (the Debugging-Factory class) stays loaded, as does the custom loader (which I made static within the factory), so a fair measure of performance is still maintained. The benefit is that the factory has a method for flushing the custom loader. What's more, the custom loader filters incoming requests so that the "primordial" class loader still handles all the classes from the default Java packages. You can load the Debugging-Factory with the following: <CFSCRIPT>Using the factory to load and flush classes from its own internal class loader is simple. Review a snippet from Listing 7 below: <CFSCRIPT>We see the creation of the factory, a call to the factory to create the Hello class (from Listing 6), and the use of the instantiated Hello object. Execut-ing Listing 7 should show you a "Hello, World" in the browser. Pretending that this is unacceptable you can now go to Hello's class source and change the greeting method to "Hi." Recompile the Hello and hit the Refresh button on your browser. What you see is pretty much what you'd expect under normal operation - the new greeting is not displayed. But if you execute the template shown in Listing 8, the DebuggingFactory's flush method is invoked. This will clear the factory's internal class cache. Now for the real test: if you return to Listing 7 and hit the Refresh button, the new greeting should be displayed. The class factory is generic. One of its shortcomings is that it actually instantiates the requested class. This means you can't use alternate constructors for the objects you're creating. In a real-world scenario, you'd have to implement your own or subclass this one.
Wrapping It Up
Standing Upon the Shoulders
of Others
A good place to start would be with one of the most recognized book on the subject: Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma et al (Addison-Wesley). It's not a quick read, nor is it a onetime read. It's the jumping-off point for years of research and application. While it's targeted for folks doing object-oriented programming, I've found it's still applicable to any kind of software development effort. YOUR FEEDBACK
CFDJ LATEST STORIES . . .
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
|
SYS-CON FEATURED WHITEPAPERS MOST READ THIS WEEK |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||