-
Notifications
You must be signed in to change notification settings - Fork 0
/
NativeLibraryUtils.java
75 lines (62 loc) · 2.15 KB
/
NativeLibraryUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import lombok.experimental.UtilityClass;
import org.apache.commons.io.IOUtils;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
import com.ibm.jzos.FileAttribute;
@UtilityClass
class NativeLibraryUtils {
/**
* Collection of a loaded file to avoid loading the same library multiple times
*/
private final Set<String> loaded = new HashSet<>();
private File extract(String filename) {
// create a copy of library in the temporary folder
File libFile;
try (InputStream is = NativeLibraryUtils.class.getResourceAsStream(filename)) {
libFile = File.createTempFile(filename, ".so");
try (OutputStream os = new FileOutputStream(libFile)) {
IOUtils.copy(is, os);
}
} catch (IOException ioe) {
throw new IllegalStateException("Could not load native library `" + filename + "`", ioe);
}
// change file to be executable and program-controlled
libFile.setExecutable(true);
FileAttribute.setProgramControlled(libFile.getAbsolutePath(), true);
// clean up file after application will be stopped
libFile.deleteOnExit();
return libFile;
}
private void load(String fileName) {
// check if the file has not been loaded yet, if not load it
synchronized (NativeLibraryUtils.class) {
if (!loaded.contains(fileName)) {
File file = extract(fileName);
System.load(file.getAbsolutePath());
loaded.add(fileName);
}
}
}
public void loadLibrary(String libraryName) {
// construct name of file
StringBuilder sb = new StringBuilder();
sb.append("/lib/").append(libraryName);
if ("32".equals(System.getProperty("com.ibm.vm.bitmode"))) {
sb.append("-31");
} else {
sb.append("-64");
}
sb.append(".so");
// load the library
load(sb.toString());
}
// using filename
static {
System.load("/z/user/libfeature.so");
}
// using library name
static {
System.loadLibrary("feature");
}
}