Home | History | Annotate | Download | only in java-jni
      1 package org.clearsilver;
      2 
      3 /**
      4  * Loads the ClearSilver JNI library.
      5  *
      6  * <p>By default, it attempts to load the library 'clearsilver-jni' from the
      7  * path specified in the 'java.library.path' system property.</p>
      8  *
      9  * <p>If this fails, the JVM exits with a code of 1. However, this strategy
     10  * can be changed using {@link #setFailureCallback(Runnable)}.</p>
     11  */
     12 public class JNI {
     13 
     14   /**
     15    * Failure callback strategy that writes a message to sysout, then calls
     16    * System.exit(1).
     17    */
     18   public static Runnable EXIT_JVM = new Runnable() {
     19     public void run() {
     20       System.out.println("Could not load '" + libraryName + "'");
     21       System.out.println("java.library.path = "
     22           + System.getProperty("java.library.path"));
     23       System.exit(1);
     24     }
     25   };
     26 
     27   /**
     28    * Failure callback strategy that throws an UnsatisfiedLinkError, which
     29    * should be caught be client code.
     30    */
     31   public static Runnable THROW_ERROR = new Runnable() {
     32     public void run() {
     33       throw new UnsatisfiedLinkError("Could not load '" + libraryName + "'");
     34     }
     35   };
     36 
     37   private static Runnable failureCallback = EXIT_JVM;
     38 
     39   private static Object callbackLock = new Object();
     40 
     41   private static String libraryName = "clearsilver-jni";
     42 
     43   /**
     44    * Attempts to load the ClearSilver JNI library.
     45    *
     46    * @see #setFailureCallback(Runnable)
     47    */
     48   public static void loadLibrary() {
     49     try {
     50       System.loadLibrary(libraryName);
     51     } catch (UnsatisfiedLinkError e) {
     52       synchronized (callbackLock) {
     53         if (failureCallback != null) {
     54           failureCallback.run();
     55         }
     56       }
     57     }
     58   }
     59 
     60   /**
     61    * Sets a callback for what should happen if the JNI library cannot
     62    * be loaded. The default is {@link #EXIT_JVM}.
     63    *
     64    * @see #EXIT_JVM
     65    * @see #THROW_ERROR
     66    */
     67   public static void setFailureCallback(Runnable failureCallback) {
     68     synchronized(callbackLock) {
     69       JNI.failureCallback = failureCallback;
     70     }
     71   }
     72 
     73   /**
     74    * Set name of JNI library to load. Default is 'clearsilver-jni'.
     75    */
     76   public static void setLibraryName(String libraryName) {
     77     JNI.libraryName = libraryName;
     78   }
     79 
     80 }