java-org.hwo/src/org/hwo/nativeloader/NativeLoader.java

81 lines
2.0 KiB
Java

package org.hwo.nativeloader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.management.RuntimeErrorException;
import org.hwo.os.OsDetect;
public class NativeLoader {
public static void loadLibrary(String libName)
{
try
{
System.loadLibrary(libName);
return;
} catch (UnsatisfiedLinkError e)
{
System.err.println("Native Library not found, trying to load from JAR-File");
System.err.println(e);
e.printStackTrace();
}
String platformLibName;
String resourcePath;
switch (OsDetect.getOperatingSystem())
{
case LINUX:
platformLibName = String.format("lib%s.so",libName);
break;
case OSX:
platformLibName = String.format("lib%s.dylib",libName);
break;
case WINDOWS:
platformLibName = String.format("%s.dll",libName);
break;
default:
throw new RuntimeException("Betriebssystem nicht unterstŸtzt!");
}
System.err.println(String.format("NativeLoader: Platform dependent Name: %s",platformLibName));
resourcePath = "/native/" + platformLibName;
System.err.println(String.format("NativeLoader: Resource name: %s",resourcePath));
InputStream libInputStream = NativeLoader.class.getResourceAsStream(resourcePath);
if (libInputStream == null)
{
System.err.println("Resource wurde nicht gefunden!");
}
try {
File tempLibFile = File.createTempFile("native-", platformLibName);
FileOutputStream fos = new FileOutputStream(tempLibFile);
System.err.println(String.format("Using Temp File: %s",tempLibFile.getAbsoluteFile()));
System.err.println(String.format("Size: %d",libInputStream.available()));
byte[] buffer = new byte[libInputStream.available()];
libInputStream.read(buffer);
fos.write(buffer);
fos.close();
System.err.println(String.format("Loading: %s", tempLibFile.getAbsolutePath()));
System.load(tempLibFile.getAbsolutePath());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}