|
| 1 | +package autoweka; |
| 2 | + |
| 3 | +import com.sun.jna.Library; |
| 4 | +import com.sun.jna.Native; |
| 5 | + |
| 6 | +import java.io.File; |
| 7 | + |
| 8 | +public class SetEnvironmentVariablesForAutoWeka { |
| 9 | + |
| 10 | + public static LibCWrapper INSTANCE; |
| 11 | + |
| 12 | + private static final Object library; |
| 13 | + |
| 14 | + interface Msvcrt extends Library { |
| 15 | + int _putenv(String name); |
| 16 | + |
| 17 | + String getenv(String name); |
| 18 | + } |
| 19 | + |
| 20 | + interface LibC extends Library { |
| 21 | + int setenv(String name, String value, int overwrite); |
| 22 | + |
| 23 | + String getenv(String name); |
| 24 | + |
| 25 | + int unsetenv(String name); |
| 26 | + } |
| 27 | + |
| 28 | + public static class LibCWrapper { |
| 29 | + |
| 30 | + public int setenv(String name, String value, int overwrite) { |
| 31 | + if (library instanceof LibC) { |
| 32 | + return ((LibC) library).setenv(name, value, overwrite); |
| 33 | + } else { |
| 34 | + return ((Msvcrt) library)._putenv(name + "=" + value); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public String getenv(String name) { |
| 39 | + if (library instanceof LibC) { |
| 40 | + return ((LibC) library).getenv(name); |
| 41 | + } else { |
| 42 | + return ((Msvcrt) library).getenv(name); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public int unsetenv(String name) { |
| 47 | + if (library instanceof LibC) { |
| 48 | + return ((LibC) library).unsetenv(name); |
| 49 | + } else { |
| 50 | + return ((Msvcrt) library)._putenv(name + "="); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + public static boolean needJavaOptions() { |
| 56 | + String version = System.getProperty("java.version"); |
| 57 | + String major = version.split("\\.")[0]; |
| 58 | + return major.compareTo("1") > 0; |
| 59 | + } |
| 60 | + |
| 61 | + static { |
| 62 | + if (System.getProperty("os.name").contains("Windows")) { |
| 63 | + library = Native.load("msvcrt", Msvcrt.class); |
| 64 | + } else { |
| 65 | + library = Native.load("c", LibC.class); |
| 66 | + } |
| 67 | + INSTANCE = new LibCWrapper(); |
| 68 | + |
| 69 | + String javaHome = System.getProperty("java.home"); |
| 70 | + INSTANCE.setenv("JAVA_HOME", javaHome, 1); |
| 71 | + String pathVar = INSTANCE.getenv("PATH"); |
| 72 | + if (pathVar == null) { |
| 73 | + pathVar = ""; |
| 74 | + } |
| 75 | + INSTANCE.setenv("PATH", javaHome + "/bin" + File.pathSeparatorChar + pathVar, 1); |
| 76 | + |
| 77 | + if (needJavaOptions()) { |
| 78 | + String existingOps = INSTANCE.getenv("_JAVA_OPTIONS"); |
| 79 | + if (existingOps == null) { |
| 80 | + existingOps = ""; |
| 81 | + } |
| 82 | + INSTANCE.setenv("_JAVA_OPTIONS", existingOps + " --add-opens=java.base/java.lang=ALL-UNNAMED", 1); |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments