Search code examples
javabrowserappletjava-web-startjnlp

How to load a library from JAR file loaded from browser?


I have a C++ library that I have compiled for OS X, Windows & Unix. For each one I have created a separate project in Eclipse and have exported them with the name convention: library-OS.jar.

Each jar basically contains:

library-OS.jar |

-> library.ext

What I was thinking was from my main Jar applet to load them by extracting them to a temp location and using system.loadlibrary.

Unfortunately I don't know how to get the resource.

I was trying to do it using Extract and load DLL from JAR but it is for relative paths and not online browser applets.

So my question is how to load the C library based on the OS of the client. I'm using JNI to talk to it and that one is in a separate JAR as well which loads the library. I was looking into JNLP but I don't know how to get the Jar name if I use JNLP. :/

EDIT:

public static void loadJarDll(String name) throws IOException {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
    byte[] buffer = new byte[1024];
    int read = -1;
    File temp = new File(new File(System.getProperty("java.io.tmpdir")), name);
    FileOutputStream fos = new FileOutputStream(temp);

    while((read = in.read(buffer)) != -1) {
        fos.write(buffer, 0, read);
    }
    fos.close();
    in.close();

    System.load(temp.getAbsolutePath());
}

This is the code I'm currently using. In order to load the library I pass the name variable which MUST contain the extension of the library. What I want to do is just request the library with it's generic name for each OS (like if it's foobar.dll for windows and foobar.so for unix to just call it foobar when loading). I want to load it like this because when I use JNLP I will only have one JAR containing the native library for that specific OS and platform.


Solution

  • Java Web Start already has inbuilt support for partitioning and loading natives.

    1. Partitioning: Add the Jar to a system specific resources section. Each OS will only download the resources intended for it.
    2. Loading: Put the natives in the root of the Jar mentioned above, and it will be extracted and placed on the run-time class-path of the app.