Raymond Camden's Blog Rss

What is your favorite Java class to use with ColdFusion?

35

Posted in ColdFusion | Posted on 04-27-2009 | 5,189 views

OK, this is probably an over-the-top geeky question to ask, but Christopher Ryan suggested it to me earlier today and I thought it would be a great topic. While ColdFusion can do almost anything, there are times when we need to resort to Java in order to do something ColdFusion can't. This can be using another JAR for a feature not implement by ColdFusion, or perhaps just relying on createObject to make an instance of a built-in Java object. So let me ask - which Java class have you found to be the most useful? For me it is StringBuffer. I've only had to use it a few times, but it was incredibly helpful in cases where I was creating a large string on the fly. (Like my toXML CFC.)


Comments

[Add Comment] [Subscribe to Comments]

I'm not a Java person, but was impressed with the way java.util.TimeZone works. ColdFusion's built-in getTimeZoneInfo is essentially a wrapper around this, providing the same information. But you can use java.util.TimeZone paired with java.util.Locale and icu4j for a consistent way to format, sort and translate date/time/time-zone values into different languages and character sets.

I keep my CF servers on UTC time and consistently store date/time data in UTC time. Then users pick their time-zone locale (like 'America/Denver' or 'Navajo'), and CF code using those functions adjusts dates/times shown on web pages to their locale -- automatically detecting if Daylight Savings Time is in effect and applying it, no matter where they are in the world.

I really like the ability to pick-and-choose Java classes that are useful, and have CF code pull everything together. I'm curious what other Java gems CF developers have found.
java.io.BufferedReader for reading large text files instead of CFFILE. Thankfully this has been abstracted by CFLOOP using the FILE attribute.
I'm with you on StringBuffer. Quite handy. Also use StringWriter and PrintWriter a lot, where I want more control than I get with StringBuffer (i.e. .print() vs .println() rather than only getting .append()).

java.util.regex.Pattern and Matcher are also nice to have. CF's inbuilt regular expression support is pretty good, so I don't use them very often, but very nice to have in a bind.

My all-time highest use, however, are undoubtedly the collection classes (java.util.Xxx). CF makes dealing with collections a lot harder than it needs to be, so I do quite a bit of direct [Array]List and [Hash]Map stuff, along with the odd [Hash]Set when it's appropriate.
Before <cfzip>, I had used a Java class to dynamically package up files and zip them up. I can't remember if it was a native Java class or if I used a 3rd party class. Either way, it was pretty cool. B-)
I use the following when writing and reading delimited text data.

http://javacsv.sourceforge.net/
http://www.csvreader.com/java_csv.php

The delimiter can be set. It's not just for comma-delimited.

- Gabriel
com.lowagie.text or iText

i know it's package and not a class, but i have a love/hate relationship with it. love it for the fact that you can do ALMOST anything to a pdf that cfdocument can't. hate it for the fact that the package is so big it's nightmare reading through the documentation to figure out how to do something.
org.h2.tools.Csv - it's a csv file reader. H2 also has a "console" servlet that allows access to any jdbc database.

Also, as of JDK 5 StringBuilder is preferred to StringBuffer in most cases (non-multi-threaded situations).
What I learnt from Java class was to use ColdFusion.

Oh, wait, I see what you asked for...
createObject("java", "java.lang.System").getProperty("line.separator")

My personal favorite bit of Java in CF. Really good for code generation.

I've been using it alot for some reason lately ;)
has to be "java.io.File" . much faster than using cfdirectory to create and handle folders and files. i also found them easier to use than DOM objects....
I am going to have to second java.util.regex.Pattern and Matcher. The ability to extracts groups and other useful tidbits that you can't do through the standard CF functions has been great for someone who ends up parsing more text than any person should ever have to.
Start using StringBuilder! It is better than StringBuffer... but make sure you Var'ed your variables. :)
Favorite is said to much, but i like trilead-ssh2. I've CF8 running on a RedHat Box and use it to perfrom some terminal work.
it would have to be the timezone & simpleTimezone classes. because of tz hell it's kind of a love/hate thing though. if there was a 2nd choice it would have to be iText.

@tony get bruno's "itext in action", the PDF version is only $30. if you use iText for anything complicated, best investment you can make: http://www.manning.com/lowagie/
java.lang.ThreadLocal
http://java.sun.com/javase/6/docs/api/java/lang/Th...

For storing variables you only want to be accessed by that given thread.


I use this allll the time.
for getting current CF/JRun instance:

<cfset Variables.JRunObject = CreateObject("Java", "jrunx.kernel.JRun")>
<cfset Variables.InstanceName = Variables.JRunObject.getServerName()>

and for getting current host name:

<cfset Server.hostName = CreateObject("java", "java.net.InetAddress").localhost.getHostName() />
Ack! Everyone is hung up on this StringBuilder/Buffer thing.

In CF it's actually faster to use arrayNew(1) and arrayAppend() and a final arrayToList() at the end. Even Fusebox has a CFC to "fake" a StringBuilder because someone thought it was faster, but seriously, stop it, just use an array.

Your code is also portable between every runtime (even that .NET one people don't talk about anymore).

As for some Java classes, the java.lang.reflect.* package is quite useful, but for actual development I'd say java.math.BigInteger. There's no way to do arbitrary precision integer math in CF. precisionEvaluate() always uses BigDecimal, which will throw nasty NaN or Infinity exceptions when doing big exp/mod calculations.
Word up to the regex Pattern and Matcher! They rock the party that rocks the body.
@Elliott: Maybe they are "hung up" on it because they noticed a dramatic speed increase. :) It's not like folks are using it because it is _slower_. Thanks for sharing the array idea though. If it is indeed faster it would be simpler to use that.

@Mark: Can you add a bit? I thought vars created within cfthread were already blackboxed?

@shakti: Have you tested file ops in CF8? They were significantly improved.
Thanks for this topic -- I don't take advantage of this as much as I could. (subscribing to comments)
Haven't had to touch it in a few years (because it just *works*), but implementing javamail to get full, powerful IMAP mail support in CF is solid.
I use many mentioned above, especially StringBuffer... that one was a life saver. But creating my own custom validation exception has been the biggest benefit. Instead of a method throwing an error on the first validation error it finds, i add each validation issue to an exception bean.

.addValidationError("fieldname allows blank","validation error number","Validation message")

then at the end of the method I throw the error

<cfif eValidate.hasValidationError()>
<cfthrow object="#eValidate#">
</cfif>

the calling app can capture the validation exceptions now

try {
oFpsGTW.validateForPassword(oFpsDTO);
} catch (uao.exceptions.Validation e) {
//return to form with messages
}
I want to make sure I'm reading you right - you created your own Java exceptions to use with your form handling?
Yes and No. I created ONE java exception (not plural) to handle holding all the validation exceptions during handling of the form.
@Ray - ThreadLocal has nothing specifically tying it to <cfthread>, I'm not sure where you drew that conclusion from.

To c/p paste from the Javadoc:
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.

Think of it like a request scope variable, but encapsulated.
@Ray, as far as i know i cant get cffile to delete/save/create files accross linked server, i was using DOM objects before but found using "java.io.file" much simpler and easier to debug on errors (even with my extremely limited java knowledge). the DOM objects on the other hand were a nightmare, mostly coz i was too scared to play around with system files on the server :) and my network guy warned me against it. "java.io.file" rocks....(i'm sure there are alot of other java classes more useful and capable of cooler stuff, but i havnt used many java classes)
@Mark: Thanks for the explanation.
At my previous employer I used the a couple Nameservice classes for various business automation tasks.

I used the Jakarta Net Commons WHOIS class to monitor our company's domain names. Somewhere around v7 we noticed that Macromedia rolled the commons-net Jar into the CFMX, so we no longer had to worry about deploying it when we built a new server.

I also used some sort of DNS lookup class to check that an MX record existed for email addresses submitted by users during registration. That added another layer of validation that could occur before we tried to send a user an email.
Lately I've been using the Apache Math Package (http://commons.apache.org/math/) to develop a CF based statistical analysis app. With that package, the list and array classes, file.io, and string buffer (much more stable and thread safe than string buffer), I'm good to go.
Probably java.lang.Runtime for it's ability to provide information about the currently running instance including memory usage details. This has been very useful when needing instance probes in a clustering scenario when using Hardware clustering and load balancing.
Just found another Java gem: java.awt.Polygon, because it easily determines if a point is inside a polygon.

This is great for mapping applications, where you can use the Google maps API to let end users draw regions on a map (see http://code.google.com/articles/support/ezdigitize...). This generates the latitude/longitude coordinates of the boundaries of the area, which can be stored.

Then you can pass any other latitude/longitude coordinates to java.awt.Polygon and determine if the location is within the region. Works well...
Quick script that uses Java's SimpleDateFormat and io.File classes to set/change the lastModifiedDate on a given file:

<cfset objJavaSimpleDateFormat = CreateObject("java", "java.text.SimpleDateFormat").init("dd/MM/yyyy HH:mm:ss")>
<cfset objJavaIoFile = createObject("java", "java.io.File")>
<cfset parsedDateTime = objJavaSimpleDateFormat.parse("28/07/2010 16:45:03")/>
<cfset myFile = objJavaIoFile.init("c:\test\myFile.txt")>
<cfset wasLastModifiedDateChanged = myFile.setLastModified(parsedDateTime.getTime())/>
Hi Ray,

Suppose if you have two java objects bc and sc respectively of class com.abc.def.baseclass and its subclass com.abc.def.subclass, in java you can assign subclass object to superclass reference (i.e. derived is assigned to base or bc=sc;) Any idea how this can be achieved in ColdFusion code with the same two java objects?
@maramandan just assign it. There's no "type" in CF, so assign whatever you want to all variable.

[Add Comment] [Subscribe to Comments]