Compiling Java code with ColdFusion
As part of my recent session at CFObjective(ANZ) + Flex, i demonstrated using the MaxMind GeoIP API to get the geographic location of the user's IP address.
MaxMind provide their GeoIP API in several different languages, and of course i grabbed the Java version. A prebuilt JAR isn't supplied, so you're left to compile the java source on your own.
I decided to try the dynamic compilation available in JavaLoader. It is meant to compile .java source files on the fly and then load the compiled JAR and make them available to ColdFusion.
It turns out it works exactly as advertised. I was actually quite surprised at how simple the whole process was.
Here are the steps I took if you want to try it out yourself
1. Download JavaLoader and extract it into a folder
2. Download latest GeoIPJava API (v 1.2.5 right now) and extract into the same folder
3. Download the GeoLite Country and GeoLite City data files and place them in the same folder
4. You should end up with a folder structure similar to the following

5. Create an index.cfm to bring it all together
<cfscript>
javaloader = createObject("component", "javaloader.JavaLoader").init(
sourceDirectories=[expandPath("GeoIPJava-1.2.5/source/")],
trustedSource=true
);
dbFile = expandPath("GeoIP.dat");
geoip = javaloader.create("com.maxmind.geoip.LookupService").init(dbFile);
country = geoip.getCountry(CGI.REMOTE_ADDR);
writeOutput("Country Code: " & country.code & " Country Code: " & country.name);
</cfscript>
And that's it! Running the example should compile the GeoIPJava API, create the Lookup Service using the GeoIP Country datafile and then return the country information for CGI.REMOTE_ADDR. Of course if you're accessing this on your local machine, a lookup against localhost won't provide anything meaningful, so just substitute a public IP address in there.
To get City level information, point the GeoIP API at the GeoCityLite.dat datafile and make the call geoip.getLocation(CGI.REMOTE_ADDR) - just be aware that this will return undefined if you try and look up localhost.
JavaLoader is dead! (not entirely)
It turns out JavaLoader makes compiling and executing Java code directly within your ColdFusion applications ridiculously easy. While Adobe are proclaiming the death of JavaLoader (see slide 51) in the next release of ColdFusion, it turns out their implementation will not support dynamic compilation.
While this isn't likely to ever be a concern for the vast majority of developers, the ease at which JavaLoader does allow it doesn't really make it much of a downside for the rest of us.