From Fedora Project Wiki

Revision as of 17:51, 23 January 2014 by Sochotni (talk | contribs) (Created page with "=== Example === To satisfy this Fedora requirement of using "System.load()" instead of "System.loadLibrary()" while still providing 32-bit versus 64-bit usability as well as c...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Example

To satisfy this Fedora requirement of using "System.load()" instead of "System.loadLibrary()" while still providing 32-bit versus 64-bit usability as well as complying with Java's write-once-run-anywhere goal, most JNI jar file should contain code similar to the following (as used in the pki-symkey JNI package):

    static boolean tryLoad(String filename) {
        try {
            System.load(filename);
        } catch (Exception e) {
            return false;
        } catch (UnsatisfiedLinkError e) {
            return false;
        }

        return true;
    }

    // Load native library
    static {
        boolean mNativeLibrariesLoaded = false;
        String os = System.getProperty("os.name");
        if ((os.equals("Linux"))) {
            // Check for 64-bit library availability
            // prior to 32-bit library availability.
            mNativeLibrariesLoaded =
                    tryLoad("/usr/lib64/symkey/libsymkey.so");
            if (mNativeLibrariesLoaded) {
                System.out.println("64-bit symkey library loaded");
            } else {
                // REMINDER:  May be trying to run a 32-bit app
                //            on 64-bit platform.
                mNativeLibrariesLoaded =
                        tryLoad("/usr/lib/symkey/libsymkey.so");
                if (mNativeLibrariesLoaded) {
                    System.out.println("32-bit symkey library loaded");
                } else {
                    System.out.println("FAILED loading symkey library!");
                    System.exit(-1);
                }
            }
        } else {
            try {
                System.loadLibrary("symkey");
                System.out.println("symkey library loaded");
                mNativeLibrariesLoaded = true;
            } catch (Throwable t) {
                // This is bad news, the program is doomed at this point
                t.printStackTrace();
            }
        }
    }

Packages utilizing approach of bundling so files as resources within JAR files themselves do not have these issues and are more self-contained.