DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. JNI in Java Web Start / Applet environment

JNI in Java Web Start / Applet environment

Leo Lewis user avatar by
Leo Lewis
·
Jul. 14, 11 · Interview
Like (0)
Save
Tweet
Share
10.28K Views

Join the DZone community and get the full member experience.

Join For Free

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">  
    </jar>  

2) Sign the Jars in 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>  
    </delete></target>  
      
    <target name="signjar" depends="genkey">  
        <signjar alias="alias" keystore="${keystore}" storepass="storepass">  
            <fileset dir="${dest.dir}/">  
                <include name="**/*.jar">  
            </include></fileset>  
        </signjar>  
    </target>  

3) Add the good tag in your JNLP :

<resources os="Windows" arch="x86">  
        <nativelib href="lib/nativewin.jar">  
  
</nativelib></resources> 

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

By a :

java.lang.System.load(libDestFile.getAbsolutePath()); 

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.

From http://lewisleo.blogspot.jp/2012/08/unsatisfiedlinkerror-in-javawebstart.html

Java (programming language) Java Web Start Java Native Interface

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Introduction to Container Orchestration
  • A Gentle Introduction to Kubernetes
  • Steel Threads Are a Technique That Will Make You a Better Engineer
  • Container Security: Don't Let Your Guard Down

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: