Using MaxMind java class with ColdFusion

2019-06-25 17:27发布

问题:

I'm trying to use MaxMind java library with ColdFusion.

I start converting this sample code on official MaxMind site:

// A File object pointing to your GeoIP2 or GeoLite2 database
File database = new File("/path/to/GeoIP2-City.mmdb");

// This creates the DatabaseReader object, which should be reused across
// lookups.
DatabaseReader reader = new DatabaseReader.Builder(database).build();

InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

// Replace "city" with the appropriate method for your database, e.g.,
// "country".
CityResponse response = reader.city(ipAddress);

Country country = response.getCountry();

What I've tried is:

var file = "pathto\maxmind\GeoLite2-City.mmdb";
var db = createObject("java","java.io.File").init(file);

var mm = createObject("java", "com.maxmind.geoip2.DatabaseReader")
.Builder(db)
.build();

dump(c);abort;

I got this error:

Type: java.lang.NoSuchMethodException 
Messages: No matching Method for Builder(java.io.File) found 
for com.maxmind.geoip2.DatabaseReader

What I'm doing wrong?

回答1:

(Update: @oschwald already provided the answer. However, I am leaving this as an extended comment as it contains some helpful details about accessing inner classes and constructors from CF)

DatabaseReader reader = new DatabaseReader.Builder(database).build();

Notice the . in the new class name statement? That indicates Builder is a special type of class. It is a nested or inner class of DatabaseReader, so you need to use a special syntax to create an instance of it, ie createObject("java", "path.OuterClass$InnerClass").

Also, new DatabaseReader.Builder(database) calls a constructor of the Builder class to create a new instance. CF does not support the "new" keyword with java objects. Instead, use the psuedo method init() to call the constructor:

var mm = createObject("java", "com.maxmind.geoip2.DatabaseReader$Builder").init(db).build();

NB: Calling init() explicitly is only required when invoking a class constructor with one or more arguments, as is the case here. If the java code was instead using the default, no-argument constructor ie new DatabaseReader.Builder().build(), you could technically omit the call to init(). CF automatically invokes the no-argument constructor if needed, when the first non-static method - ie build() - is invoked.



回答2:

Builder is a class, not a method. Perhaps try something like:

var mm = CreateObject("java", "com.maxmind.geoip2.DatabaseReader$Builder").Init(db).build();