Using MaxMind java class with ColdFusion

感情迁移 提交于 2019-12-10 15:15:01

问题


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();


来源:https://stackoverflow.com/questions/35822549/using-maxmind-java-class-with-coldfusion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!