1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.bcel.util;
20
21 import java.io.Closeable;
22 import java.io.File;
23 import java.io.IOException;
24 import java.net.URI;
25 import java.net.URL;
26 import java.net.URLClassLoader;
27 import java.nio.file.DirectoryStream;
28 import java.nio.file.FileSystem;
29 import java.nio.file.FileSystems;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.List;
36 import java.util.Map;
37
38 import org.apache.commons.io.IOUtils;
39
40
41
42
43
44
45 public class ModularRuntimeImage implements Closeable {
46
47 static final String MODULES_PATH = File.separator + "modules";
48 static final String PACKAGES_PATH = File.separator + "packages";
49
50 private final URLClassLoader classLoader;
51 private final FileSystem fileSystem;
52
53
54
55
56 @SuppressWarnings("resource")
57 public ModularRuntimeImage() {
58 this(null, FileSystems.getFileSystem(URI.create("jrt:/")));
59 }
60
61
62
63
64
65
66
67 public ModularRuntimeImage(final String javaHome) throws IOException {
68 final Map<String, ?> emptyMap = Collections.emptyMap();
69 final Path jrePath = Paths.get(javaHome);
70 final Path jrtFsPath = jrePath.resolve("lib").resolve("jrt-fs.jar");
71 this.classLoader = URLClassLoader.newInstance(new URL[] {jrtFsPath.toUri().toURL()});
72 this.fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), emptyMap, classLoader);
73 }
74
75 private ModularRuntimeImage(final URLClassLoader cl, final FileSystem fs) {
76 this.classLoader = cl;
77 this.fileSystem = fs;
78 }
79
80 @Override
81 public void close() throws IOException {
82 IOUtils.close(classLoader);
83 if (fileSystem != null) {
84 try {
85 fileSystem.close();
86 } catch (final UnsupportedOperationException e) {
87
88 }
89 }
90 }
91
92
93
94
95
96
97 public FileSystem getFileSystem() {
98 return fileSystem;
99 }
100
101
102
103
104
105
106
107
108 public List<Path> list(final Path dirPath) throws IOException {
109 final List<Path> list = new ArrayList<>();
110 try (DirectoryStream<Path> ds = Files.newDirectoryStream(dirPath)) {
111 ds.forEach(list::add);
112 }
113 return list;
114 }
115
116
117
118
119
120
121
122
123 public List<Path> list(final String dirName) throws IOException {
124 return list(fileSystem.getPath(dirName));
125 }
126
127
128
129
130
131
132
133 public List<Path> modules() throws IOException {
134 return list(MODULES_PATH);
135 }
136
137
138
139
140
141
142
143 public List<Path> packages() throws IOException {
144 return list(PACKAGES_PATH);
145 }
146
147 }