-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleLoader.java
More file actions
103 lines (86 loc) · 3.09 KB
/
ModuleLoader.java
File metadata and controls
103 lines (86 loc) · 3.09 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.sprintstack;
import java.nio.file.Files;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.URI;
import java.util.HashMap;
import java.io.IOException;
import org.json.simple.JSONObject;
import com.sprintstack.util.JSON;
public class ModuleLoader {
private static FileSystem jar;
private static Path resolve(String name) {
return resolve(name, null);
}
private static Path resolve(String name, String ext) {
// Test if we're referring to a core module
Path resource = getJarPath().getParent().resolve("../resources/" + name + ".js").normalize();
if (Files.exists(resource)) {
return resource;
} else {
// Failing that, check if we're looking for a
// local file
Path localPath = Paths.get(name);
if (Files.exists(localPath)) {
// Is localPath a file or folder?
if (Files.isRegularFile(localPath)) {
return localPath;
} else {
// Look for package.json
Path packageJson = localPath.resolve("package.json");
if (Files.exists(packageJson)) {
String mainPath = parsePackage(packageJson);
return resolve(localPath.resolve(mainPath).toString());
}
}
}
}
try {
return bouncePath(name, ext);
} catch (IOException e) {
return null;
}
}
private static Path bouncePath(String name, String ext) throws IOException {
if (ext == null) {
return resolve(name.concat(".js"), "js");
} else if (ext == "js") {
String prefix = name.substring(0, (name.length()-2));
return resolve(prefix.concat("json"), "json");
} else {
throw new IOException();
}
}
public static String resolveParent(String id) {
return resolve(id).getParent().toString();
}
public static String resolveDirect(String id) {
return resolve(id).toString();
}
private static String parsePackage(Path path) {
String json = loadFile(path);
JSONObject parsed = JSON.decode(json);
String main = (String)parsed.get("main");
return main;
}
private static Path getJarPath() {
return Paths.get(SprintStack.class.getProtectionDomain().getCodeSource().getLocation().getPath());
}
public static String loadFile(String location) {
Path path = Paths.get(location);
return loadFile(path);
}
private static String loadFile(Path path) {
try {
byte[] bytes = Files.readAllBytes(path);
return new String(bytes);
} catch (IOException e) { return null; }
}
public static String require(String name) {
Path module = resolve(name);
if (module == null) return null;
return loadFile(module.toString());
}
}