Sunday, August 12, 2012

UnsatisfiedLinkError in a JavaWebStart application

Yes ! Me too ! I have spent a tremendous amount of time dealing with trouble using JNI in a Java Web Start or an Applet environment. And by searching on my friend Google, I have found out that I'm not the only Java developer on the Java world to have dealt with this kind of trouble ...
Sometimes, it works pretty fine, especially if you use Java Web Start to wrap your application (Swing/ Eclipse RCP or Applet), you just have to follow a quite simple procedure that can be automated with a simple Ant script (for more details about Java Web Start, check the Lopica web site that is pretty well done) :

1) Jar the native lib :
 <jar destfile="lib/nativewin.jar" basedir="native/win/" includes="some.dll"/>  

2) Sign the Jars your application :
 <target name="genkey">  
   <delete file="${keystore}"/>  
   <genkey alias="alias" keystore="${keystore}" storepass="storepass" validity="900">  
     <dname>  
       <param name="CN" value="CN"/>  
       <param name="OU" value="OU"/>  
       <param name="O" value="O"/>  
       <param name="C" value="C"/>  
     </dname>  
   </genkey>  
 </target>  
 <target name="signjar" depends="genkey">  
   <signjar alias="alias" keystore="${keystore}" storepass="storepass">  
     <fileset dir="${dest.dir}/">  
       <include name="**/*.jar" />  
     </fileset>  
   </signjar>  
 </target> 

3) Add the good tag in your JNLP :
 <resources os="Windows" arch="x86">  
      <nativelib href="lib/nativewin.jar"/>  
 </resource> 
And everything is fine. Yes sometimes everything is OK, but sometimes, for some dark reasons that I don't really understand, with some native libs and not with others, especially when you don't have time to spend on this kind of problem, and always on the production environment, because when testing on your development environment, you have forgotten to delete the native lib of your PATH ... So sometimes, the application crashes with a famous :

java.lang.UnsatisfiedLinkError: no foobar in java.library.path

Here we are. You check your JNLP : seems good. You check the jar that contains the native lib : hmm OK. It's 10pm and you're still at office, "It must be some little silly thing that I'm forgetting. Tomorrow, I'll recheck that I'll probably found the solution in 10 minutes".
Naive of you ...

The following day, you spend an entire morning checking all these little things, reboot 5 times your computer, but it's still here : the UnsatisfiedLinkErrorOfTheDeath ...

The first workaround is of course to copy the native libs in a folder that you will previously had in your PATH. The copy can be done by some installer code of the program, for example by a code that will look like this one (the native is located in the Jar, so we need to access it as a Stream) :

InputStream src = SomeClass.class.getResourceAsStream("/pathToTheLib/" + libName);

File libDestFile = new File(installLibFilePath);

FileOutputStream out = null;

try {
       out = new FileOutputStream(libDestFile);
       byte[] buffer = new byte[256];
       int read = 0;
       while ((read = src.read(buffer)) > 0) {
              out.write(buffer, 0, read);
              read = src.read(buffer);
       }
} catch (FileNotFoundException e) {
       e.printStackTrace();
} catch (IOException e) {
       e.printStackTrace();
} finally {
       // close
       try {
              if (out != null) {
                     out.close();
              }
       } catch (IOException e) {
              e.printStackTrace();
       }
}

Here we have two possibilities : either our program is loading the native lib, in this case, we replace the instruction :
java.lang.System.load(libDestFile.getAbsolutePath());
By a :
java.lang.System.load(libName);
But if it is a library (another Jar) that is loading the native lib, we are stuck. In this case, we have to set some PATH env property manually so that the ClassLoader find the native lib, and your Java developer soul cry hard when thinking of doing such a disgraceful thing.
Ok, so how do we do such a trick in Java ... Well, as it is said i the exception message, we need to add the library to the java.library.path property.
What is this property ? It is used when the java.lang.ClassLoader will load the first native library to initialize its field usr_paths which is a String array. Indeed, in the loadLibrary method, we can see this code :
if (sys_paths == null) {
       usr_paths = initializePath("java.library.path");
       sys_paths = initializePath("sun.boot.library.path");
}
So seeing this code, we understand that it is useless to override this property, by adding the folder where we will copy our library, after the JVM as been launch, because we'll be too late, the sys_paths field will be initialized, so the usr_paths will not be updated.
And of course, this field cannot be accessed directly, so our last resort is to use reflection :
Field usrPathFiled = ClassLoader.class.getDeclaredField("usr_paths");
usrPathFiled.setAccessible(true);
String[] usrPath = (String[]) usrPathFiled.get(null);
String[] newUsrPath = new String[usrPath.length + 1];
System.arraycopy(usrPath, 0, newUsrPath, 0, usrPath.length);
newUsrPath[usrPath.length] = destFile.getParentFile().getAbsolutePath();
usrPathFiled.set(null, newUsrPath);

By executing this code before using the jar that will load the native library, we have a programmatic 100% Java workaround to our problem.

It's definitely not the most beautiful way of coding in Java, some of you might say "If it's private in the JDK, there is a good reason, Son !"
Anyway, shall this article avoid other people to waste their time on this problem.

No comments:

Post a Comment