views:

76

answers:

4

A POM dependency contains native libraries (DLLs inside a JAR file). How do I programmatically look up the path of the downloaded JAR file so I can pass it into "java.library.path"?

A: 

You can use the maven dependency plugin to copy the artifacts to a predefined path:

http://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-artifacts.html

shipmaster
A: 

If the DLL is inside the JAR, then you will need to copy it out to a directory before it can be loaded. (JARs that include native libraries usually do this themselves.) If your JAR isn't doing this, then you can use Class.getResourceAsStream() and write this to a directory that you've added to the java.library.path.

For an example of this, see loadNativeLibrary in JNA. It uses this technique to load it's own library (a JNI library) from a JAR.

mdma
Great, but how do I do this from within Maven (as opposed to having to bootstrap inside my application code)?
Gili
I would advise against doing this in maven. If the JAR doesn't do it alaready, then create a simple companion JAR that does the unpacking - if your code loads the native library first, it will be found when the library JAR attempts to load the same library. The closest thing in maven is the dependency plugin, which can unpack a dependency to a directory. The native library will be there in the unpacked directory.
mdma
A: 

Since System.load() can't load libraries from within a jar, you will have to use a custom loader which extracts the library to a temporary file at runtime. Projects With JNI discusses this approach and provide code for the custom loader.

Library loader

We now have our JNI library on the class path, so we need a way of loading it. I created a separate project which would extract JNI libraries from the class path, then load them. Find it at http://opensource.mxtelecom.com/maven/repo/com/wapmx/native/mx-native-loader/1.2/. This is added as a dependency to the pom, obviously.

To use it, call com.wapmx.nativeutils.jniloader.NativeLoader.loadLibrary(libname). More information is in the javadoc for NativeLoader.

I generally prefer to wrap such things in a try/catch block, as follows:

public class Sqrt {
    static {
        try {
            NativeLoader.loadLibrary("sqrt");
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    /* ... class body ... */
}

An alternative would be to unpack the dependency, for example using dependency:unpack.

Pascal Thivent
A: 

Answering my own question: http://www.buildanddeploy.com/node/17

Gili