3 import java.io.FileOutputStream;
4 import java.io.InputStream;
5 import java.io.OutputStream;
8 public final class NativeLib {
10 public static String getPath() {
11 String prefix = "NATIVE";
12 String os = System.getProperty("os.name");
13 String arch = System.getProperty("os.arch");
15 if (os.toLowerCase().startsWith("^win"))
17 else if (os.contains("OS X"))
20 if (arch.matches("^i[3-6]86$"))
22 else if (arch.equalsIgnoreCase("amd64"))
25 os = os.replace(' ', '_');
26 arch = arch.replace(' ', '_');
28 return prefix + "/" + os + "/" + arch + "/";
30 public static void nativeInit(String name) {
32 /* prefer the version on disk, if existing */
33 System.loadLibrary(name);
34 } catch (UnsatisfiedLinkError e) {
35 /* If not found, unpack the one bundled into the jar file and use it */
40 private static void loadLib (String name) {
41 String Path = NativeLib.getPath();
44 InputStream in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
47 filename = "lib"+name+".so";
48 in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
51 filename = name+".dll";
52 in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
55 filename = "lib"+name+".dll";
56 in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
59 filename = "lib"+name+".dylib";
60 in = NativeLib.class.getClassLoader().getResourceAsStream(Path+filename);
63 throw new RuntimeException("Cannot find library "+name+" in path "+Path+". Sorry, but this jar does not seem to be usable on your machine.");
66 // We must write the lib onto the disk before loading it -- stupid operating systems
67 File fileOut = new File(filename);
68 fileOut = File.createTempFile(name+"-", ".tmp");
69 // don't leak the file on disk, but remove it on JVM shutdown
70 Runtime.getRuntime().addShutdownHook(new Thread(new FileCleaner(fileOut.getAbsolutePath())));
71 OutputStream out = new FileOutputStream(fileOut);
73 /* copy the library in position */
74 byte[] buffer = new byte[4096];
76 while ((bytes_read = in.read(buffer)) != -1) // Read until EOF
77 out.write(buffer, 0, bytes_read);
79 /* close all file descriptors, and load that shit */
82 System.load(fileOut.getAbsolutePath());
84 } catch (Exception e) {
85 System.err.println("Cannot load the bindings to the "+name+" library: ");
87 System.err.println("This jar file does not seem to fit your system, sorry");
92 /* A hackish mechanism used to remove the file containing our library when the JVM shuts down */
93 private static class FileCleaner implements Runnable {
94 private String target;
95 public FileCleaner(String name) {
100 new File(target).delete();
101 } catch(Exception e) {
102 System.out.println("Unable to clean temporary file "+target+" during shutdown.");
109 public static void main(String[] args) {
110 System.out.println(getPath());