1 /*
2 * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package jdk.internal.jrtfs;
26
27 import java.io.IOException;
28 import java.io.UncheckedIOException;
29 import java.nio.file.DirectoryStream;
30 import java.nio.file.FileSystemException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.attribute.BasicFileAttributes;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Objects;
39 import java.util.stream.Stream;
40
41 import jdk.internal.jimage.ImageReader.Node;
42
43 /**
44 * A jrt file system built on $JAVA_HOME/modules directory ('exploded modules
45 * build')
46 *
47 * @implNote This class needs to maintain JDK 8 source compatibility.
48 *
49 * It is used internally in the JDK to implement jimage/jrtfs access,
50 * but also compiled and delivered as part of the jrtfs.jar to support access
51 * to the jimage file provided by the shipped JDK by tools running on JDK 8.
52 */
53 class ExplodedImage extends SystemImage {
54
55 private static final String MODULES = "/modules/";
56 private static final String PACKAGES = "/packages/";
57
58 private final Path modulesDir;
59 private final String separator;
60 private final Map<String, PathNode> nodes = new HashMap<>();
61 private final BasicFileAttributes modulesDirAttrs;
62
63 ExplodedImage(Path modulesDir) throws IOException {
64 this.modulesDir = modulesDir;
65 String str = modulesDir.getFileSystem().getSeparator();
66 separator = str.equals("/") ? null : str;
67 modulesDirAttrs = Files.readAttributes(modulesDir, BasicFileAttributes.class);
68 initNodes();
69 }
70
71 // A Node that is backed by actual default file system Path
72 private final class PathNode extends Node {
73
74 // Path in underlying default file system
75 private Path path;
76 private PathNode link;
77 private List<Node> children;
78
79 private PathNode(String name, Path path, BasicFileAttributes attrs) { // path
80 super(name, attrs);
81 this.path = path;
82 }
83
84 private PathNode(String name, Node link) { // link
85 super(name, link.getFileAttributes());
86 this.link = (PathNode)link;
87 }
88
89 private PathNode(String name, List<Node> children) { // dir
90 super(name, modulesDirAttrs);
91 this.children = children;
92 }
93
94 @Override
95 public boolean isResource() {
96 return link == null && !getFileAttributes().isDirectory();
97 }
98
99 @Override
100 public boolean isDirectory() {
101 return children != null ||
102 (link == null && getFileAttributes().isDirectory());
103 }
104
105 @Override
106 public boolean isLink() {
107 return link != null;
108 }
109
110 @Override
111 public PathNode resolveLink(boolean recursive) {
112 if (link == null)
113 return this;
114 return recursive && link.isLink() ? link.resolveLink(true) : link;
115 }
116
117 private byte[] getContent() throws IOException {
118 if (!getFileAttributes().isRegularFile())
119 throw new FileSystemException(getName() + " is not file");
120 return Files.readAllBytes(path);
121 }
122
123 @Override
124 public Stream<String> getChildNames() {
125 if (!isDirectory())
126 throw new IllegalArgumentException("not a directory: " + getName());
127 if (children == null) {
128 List<Node> list = new ArrayList<>();
129 try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) {
130 for (Path p : stream) {
131 p = modulesDir.relativize(p);
132 String pName = MODULES + nativeSlashToFrontSlash(p.toString());
133 Node node = findNode(pName);
134 if (node != null) { // findNode may choose to hide certain files!
135 list.add(node);
136 }
137 }
138 } catch (IOException x) {
139 return null;
140 }
141 children = list;
142 }
143 return children.stream().map(Node::getName);
144 }
145
146 @Override
147 public long size() {
148 try {
149 return isDirectory() ? 0 : Files.size(path);
150 } catch (IOException ex) {
151 throw new UncheckedIOException(ex);
152 }
153 }
154 }
155
156 @Override
157 public synchronized void close() throws IOException {
158 nodes.clear();
159 }
160
161 @Override
162 public byte[] getResource(Node node) throws IOException {
163 return ((PathNode)node).getContent();
164 }
165
166 @Override
167 public synchronized Node findNode(String name) {
168 PathNode node = nodes.get(name);
169 if (node != null) {
170 return node;
171 }
172 // If null, this was not the name of "/modules/..." node, and since all
173 // "/packages/..." nodes were created and cached in advance, the name
174 // cannot reference a valid node.
175 Path path = underlyingModulesPath(name);
176 if (path == null) {
177 return null;
178 }
179 // This can still return null for hidden files.
180 return createModulesNode(name, path);
181 }
182
183 /**
184 * Lazily creates and caches a {@code Node} for the given "/modules/..." name
185 * and corresponding path to a file or directory.
186 *
187 * @param name a resource or directory node name, of the form "/modules/...".
188 * @param path the path of a file for a resource or directory.
189 * @return the newly created and cached node, or {@code null} if the given
190 * path references a file which must be hidden in the node hierarchy.
191 */
192 private Node createModulesNode(String name, Path path) {
193 assert !nodes.containsKey(name) : "Node must not already exist: " + name;
194 assert isNonEmptyModulesPath(name) : "Invalid modules name: " + name;
195
196 try {
197 // We only know if we're creating a resource of directory when we
198 // look up file attributes, and we only do that once. Thus, we can
199 // only reject "marker files" here, rather than by inspecting the
200 // given name string, since it doesn't apply to directories.
201 BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
202 if (attrs.isRegularFile()) {
203 Path f = path.getFileName();
204 if (f.toString().startsWith("_the.")) {
205 return null;
206 }
207 } else if (!attrs.isDirectory()) {
208 return null;
209 }
210 PathNode node = new PathNode(name, path, attrs);
211 nodes.put(name, node);
212 return node;
213 } catch (IOException x) {
214 // Since the path reference a file, any errors should not be ignored.
215 throw new UncheckedIOException(x);
216 }
217 }
218
219 /**
220 * Returns the expected file path for name in the "/modules/..." namespace,
221 * or {@code null} if the name is not in the "/modules/..." namespace or the
222 * path does not reference a file.
223 */
224 private Path underlyingModulesPath(String name) {
225 if (isNonEmptyModulesPath(name)) {
226 Path path = modulesDir.resolve(frontSlashToNativeSlash(name.substring(MODULES.length())));
227 return Files.exists(path) ? path : null;
228 }
229 return null;
230 }
231
232 private static boolean isNonEmptyModulesPath(String name) {
233 // Don't just check the prefix, there must be something after it too
234 // (otherwise you end up with an empty string after trimming).
235 return name.startsWith(MODULES) && name.length() > MODULES.length();
236 }
237
238 // convert "/" to platform path separator
239 private String frontSlashToNativeSlash(String str) {
240 return separator == null ? str : str.replace("/", separator);
241 }
242
243 // convert platform path separator to "/"
244 private String nativeSlashToFrontSlash(String str) {
245 return separator == null ? str : str.replace(separator, "/");
246 }
247
248 // convert "/"s to "."s
249 private String slashesToDots(String str) {
250 return str.replace(separator != null ? separator : "/", ".");
251 }
252
253 // initialize file system Nodes
254 private void initNodes() throws IOException {
255 // same package prefix may exist in multiple modules. This Map
256 // is filled by walking "jdk modules" directory recursively!
257 Map<String, List<String>> packageToModules = new HashMap<>();
258 try (DirectoryStream<Path> stream = Files.newDirectoryStream(modulesDir)) {
259 for (Path module : stream) {
260 if (Files.isDirectory(module)) {
261 String moduleName = module.getFileName().toString();
262 // make sure "/modules/<moduleName>" is created
263 Objects.requireNonNull(createModulesNode(MODULES + moduleName, module));
264 try (Stream<Path> contentsStream = Files.walk(module)) {
265 contentsStream.filter(Files::isDirectory).forEach((p) -> {
266 p = module.relativize(p);
267 String pkgName = slashesToDots(p.toString());
268 // skip META-INF and empty strings
269 if (!pkgName.isEmpty() && !pkgName.startsWith("META-INF")) {
270 packageToModules
271 .computeIfAbsent(pkgName, k -> new ArrayList<>())
272 .add(moduleName);
273 }
274 });
275 }
276 }
277 }
278 }
279 // create "/modules" directory
280 // "nodes" map contains only /modules/<foo> nodes only so far and so add all as children of /modules
281 PathNode modulesRootNode = new PathNode("/modules", new ArrayList<>(nodes.values()));
282 nodes.put(modulesRootNode.getName(), modulesRootNode);
283
284 // create children under "/packages"
285 List<Node> packagesChildren = new ArrayList<>(packageToModules.size());
286 for (Map.Entry<String, List<String>> entry : packageToModules.entrySet()) {
287 String pkgName = entry.getKey();
288 List<String> moduleNameList = entry.getValue();
289 List<Node> moduleLinkNodes = new ArrayList<>(moduleNameList.size());
290 for (String moduleName : moduleNameList) {
291 Node moduleNode = Objects.requireNonNull(nodes.get(MODULES + moduleName));
292 PathNode linkNode = new PathNode(PACKAGES + pkgName + "/" + moduleName, moduleNode);
293 nodes.put(linkNode.getName(), linkNode);
294 moduleLinkNodes.add(linkNode);
295 }
296 PathNode pkgDir = new PathNode(PACKAGES + pkgName, moduleLinkNodes);
297 nodes.put(pkgDir.getName(), pkgDir);
298 packagesChildren.add(pkgDir);
299 }
300 // "/packages" dir
301 PathNode packagesRootNode = new PathNode("/packages", packagesChildren);
302 nodes.put(packagesRootNode.getName(), packagesRootNode);
303
304 // finally "/" dir!
305 List<Node> rootChildren = new ArrayList<>();
306 rootChildren.add(packagesRootNode);
307 rootChildren.add(modulesRootNode);
308 PathNode root = new PathNode("/", rootChildren);
309 nodes.put(root.getName(), root);
310 }
311 }
|
1 /*
2 * Copyright (c) 2015, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25 package jdk.internal.jrtfs;
26
27 import java.io.IOException;
28 import java.io.UncheckedIOException;
29 import java.nio.file.DirectoryStream;
30 import java.nio.file.FileSystemException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.nio.file.attribute.BasicFileAttributes;
35 import java.util.ArrayList;
36 import java.util.HashMap;
37 import java.util.LinkedHashSet;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.Objects;
41 import java.util.Set;
42 import java.util.function.UnaryOperator;
43 import java.util.stream.Collectors;
44 import java.util.stream.Stream;
45 import java.util.stream.StreamSupport;
46
47 import jdk.internal.jimage.ImageReader.Node;
48
49 /**
50 * A jrt file system built on $JAVA_HOME/modules directory ('exploded modules
51 * build')
52 *
53 * @implNote This class needs to maintain JDK 8 source compatibility.
54 *
55 * It is used internally in the JDK to implement jimage/jrtfs access,
56 * but also compiled and delivered as part of the jrtfs.jar to support access
57 * to the jimage file provided by the shipped JDK by tools running on JDK 8.
58 */
59 class ExplodedImage extends SystemImage {
60
61 private static final String MODULES = "/modules/";
62 private static final String PACKAGES = "/packages/";
63 // This directory cannot be preview overridden.
64 private static final Path META_INF_DIR = Paths.get("META-INF");
65 // Root of the preview override of a module relative to root of that module.
66 // This directory never appears in either non-preview or preview images.
67 private static final Path PREVIEW_DIR = META_INF_DIR.resolve("preview");
68
69 private final Path modulesDir;
70 private final boolean isPreviewMode;
71 private final Map<String, PathNode> nodes = new HashMap<>();
72 private final BasicFileAttributes modulesDirAttrs;
73
74 ExplodedImage(Path modulesDir, boolean isPreviewMode) throws IOException {
75 this.modulesDir = modulesDir;
76 this.isPreviewMode = isPreviewMode;
77 modulesDirAttrs = Files.readAttributes(modulesDir, BasicFileAttributes.class);
78 initNodes();
79 }
80
81 // A Node that is backed by absolute Paths on the default FS
82 // This is thread-safe, guaranteed by synchronized findNode
83 private final class PathNode extends Node {
84 // Regular file
85 private final Path file;
86 // Symbolic link
87 private final PathNode link;
88 // Directories
89 // `directories` is written before and read after `childNames`
90 private List<Path> directories;
91 private volatile List<String> childNames; // Has no duplicates
92
93 /**
94 * Creates a file based node with the given file attributes.
95 * Used for all /modules/... files.
96 */
97 private PathNode(String name, Path file, BasicFileAttributes attrs) {
98 super(name, attrs);
99 this.file = Objects.requireNonNull(file);
100 this.link = null;
101 this.directories = null;
102 this.childNames = null;
103 }
104
105 /**
106 * Creates a directory based node with the given file attributes.
107 * Used for all /modules/... directories. It is created in an
108 * "incomplete" state, and its child names are determined lazily.
109 */
110 private PathNode(String name, List<Path> directories, BasicFileAttributes attrs) {
111 super(name, attrs);
112 this.file = null;
113 this.link = null;
114 this.directories = Objects.requireNonNull(directories);
115 this.childNames = null;
116 }
117
118 /**
119 * Creates a symbolic link node to the specified target.
120 * Used for each module-named directory that are leafs of /packages/...
121 */
122 private PathNode(String name, PathNode link) {
123 super(name, link.getFileAttributes());
124 this.file = null;
125 this.link = Objects.requireNonNull(link);
126 this.directories = null;
127 this.childNames = null;
128 }
129
130 /**
131 * Creates a completed directory node based a list of child nodes.
132 * Used for the root, /modules, /packages, and /packages/... non-leaf
133 * directories, all created in initNodes().
134 */
135 private PathNode(String name, List<PathNode> children) {
136 super(name, modulesDirAttrs);
137 this.file = null;
138 this.link = null;
139 this.directories = null;
140 this.childNames = children.stream().map(Node::getName).collect(Collectors.toList());
141 }
142
143 @Override
144 public boolean isResource() {
145 return file != null;
146 }
147
148 @Override
149 public boolean isDirectory() {
150 return childNames != null || directories != null;
151 }
152
153 @Override
154 public boolean isLink() {
155 return link != null;
156 }
157
158 @Override
159 public PathNode resolveLink(boolean recursive) {
160 if (link == null)
161 return this;
162 return recursive && link.isLink() ? link.resolveLink(true) : link;
163 }
164
165 private byte[] getContent() throws IOException {
166 if (!isResource())
167 throw new FileSystemException(getName() + " is not file");
168 return Files.readAllBytes(file);
169 }
170
171 @Override
172 public Stream<String> getChildNames() {
173 if (!isDirectory())
174 throw new IllegalStateException("not a directory: " + getName());
175 List<String> names = childNames;
176 if (names == null) {
177 names = completeDirectory();
178 }
179 return names.stream();
180 }
181
182 private synchronized List<String> completeDirectory() {
183 if (childNames != null) {
184 return childNames;
185 }
186
187 Set<String> childNameSet = new LinkedHashSet<>();
188 for (Path path : directories) {
189 collectChildNodeNames(path, childNameSet);
190 }
191 directories = null;
192 return childNames = new ArrayList<>(childNameSet);
193 }
194
195 private void collectChildNodeNames(Path absPath, Set<String> childNameSet) {
196 try (DirectoryStream<Path> stream = Files.newDirectoryStream(absPath)) {
197 for (Path p : stream) {
198 PathNode node = (PathNode) findNode(getName() + "/" + p.getFileName().toString());
199 if (node != null) { // findNode may choose to hide certain files!
200 childNameSet.add(node.getName());
201 }
202 }
203 } catch (IOException ex) {
204 throw new UncheckedIOException(ex);
205 }
206 }
207
208 @Override
209 public long size() {
210 try {
211 return !isResource() ? 0 : Files.size(file);
212 } catch (IOException ex) {
213 throw new UncheckedIOException(ex);
214 }
215 }
216 }
217
218 @Override
219 public synchronized void close() throws IOException {
220 nodes.clear();
221 }
222
223 @Override
224 public byte[] getResource(Node node) throws IOException {
225 return ((PathNode)node).getContent();
226 }
227
228 @Override
229 public synchronized Node findNode(String name) {
230 PathNode node = nodes.get(name);
231 if (node != null) {
232 return node;
233 }
234
235 return createPathInModulesNodeIfValid(name);
236 }
237
238 // `rest` nullable means name points to the root of a module
239 private Path candidatePath(Path module, Path rest, boolean preview) {
240 if (preview && rest != null && rest.startsWith(META_INF_DIR)) {
241 // Nothing in META-INF has a preview override
242 return null;
243 }
244 Path now = modulesDir.resolve(module);
245 if (preview) {
246 now = now.resolve(PREVIEW_DIR);
247 }
248 if (rest != null) {
249 now = now.resolve(rest);
250 }
251 return Files.exists(now) ? now : null;
252 }
253
254 /**
255 * Lazily creates and caches a {@code Node} for the given "/modules/..." name
256 * and corresponding path to a file or directory.
257 *
258 * @param name a resource or directory node name, of the form "/modules/...".
259 * @return the newly created and cached node, or {@code null} if the given
260 * path references a file which must be hidden in the node hierarchy.
261 */
262 private PathNode createPathInModulesNodeIfValid(String name) {
263 // We anticipate the name of a "/modules/..." node for lazy creation.
264 // All "/packages/..." nodes are created by initNodes() instead.
265 if (!isPathInModulesName(name)) {
266 return null;
267 }
268
269 assert !nodes.containsKey(name) : "Node must not already exist: " + name;
270
271 // Extract the module name and the remaining parts of the path
272 Path moduleName; // Exactly a single name element
273 Path remainderPath; // May be null
274 {
275 String relativeName = name.substring(MODULES.length());
276 Path relativePath = Paths.get("", relativeName.split("/"));
277
278 moduleName = relativePath.getName(0);
279 int nameCount = relativePath.getNameCount();
280 remainderPath = nameCount > 1 ? relativePath.subpath(1, nameCount) : null;
281 }
282
283 // Filter any path to in META-INF/preview consistently
284 if (remainderPath != null && remainderPath.startsWith(PREVIEW_DIR)) {
285 return null;
286 }
287
288 // Find valid regular and preview paths
289 Path regularPath = candidatePath(moduleName, remainderPath, false);
290 Path previewPath = isPreviewMode ? candidatePath(moduleName, remainderPath, true) : null;
291 if (regularPath == null && previewPath == null) {
292 return null;
293 }
294
295 // Select a path for source of attributes
296 Path selected;
297 if (regularPath != null && Files.isDirectory(regularPath)) {
298 // Non-preview directories take precedence.
299 selected = regularPath;
300 } else {
301 // Otherwise prefer preview resources over non-preview ones.
302 selected = previewPath == null ? regularPath : previewPath;
303 }
304
305 // Read the file attributes
306 BasicFileAttributes attrs;
307 try {
308 attrs = Files.readAttributes(selected, BasicFileAttributes.class);
309 } catch (IOException x) {
310 // Since the path references a file, errors should not be ignored.
311 throw new UncheckedIOException(x);
312 }
313
314 // Create the right PathNode
315 PathNode node;
316 if (attrs.isRegularFile()) {
317 Path f = selected.getFileName();
318 // Only reject "marker files", doesn't apply to directories
319 if (f.toString().startsWith("_the.")) {
320 return null;
321 }
322 node = new PathNode(name, selected, attrs);
323 } else if (attrs.isDirectory()) {
324 List<Path> directories = Stream.of(regularPath, previewPath)
325 .filter(Objects::nonNull)
326 .collect(Collectors.toList());
327 node = new PathNode(name, directories, attrs);
328 } else {
329 return null;
330 }
331 nodes.put(name, node);
332 return node;
333 }
334
335 // Ensures this is a name taking form /modules/... with no trailing slash.
336 private static boolean isPathInModulesName(String name) {
337 // Don't just check the prefix, there must be something after it too
338 // (otherwise you end up with an empty string after trimming).
339 // Also make sure we can't be tricked by "/modules//absolute/path" or
340 // "/modules/../../escaped/path".
341 // Don't use regex as 'name' is untrusted (avoids stack overflow risk)
342 // and performance isn't an issue here.
343 return name.startsWith("/modules/")
344 && !name.contains("//")
345 && !name.contains("/./")
346 && !name.contains("/../")
347 && !name.endsWith("/")
348 && !name.endsWith("/.")
349 && !name.endsWith("/..");
350 }
351
352 // initialize the root /modules, /packages, and the symbolic link Nodes
353 private void initNodes() throws IOException {
354 // same package prefix may exist in multiple modules. This Map
355 // is filled by walking "jdk modules" directory recursively!
356 Map<String, List<String>> packageToModules = new HashMap<>();
357 List<PathNode> modules = new ArrayList<>();
358 try (DirectoryStream<Path> stream = Files.newDirectoryStream(modulesDir, Files::isDirectory)) {
359 for (Path moduleDir : stream) {
360 modules.add(findPackagesAndCreateModuleNode(moduleDir, packageToModules));
361 }
362 }
363 // create "/modules" directory
364 PathNode modulesRootNode = new PathNode("/modules", modules);
365 nodes.put(modulesRootNode.getName(), modulesRootNode);
366
367 // create children under "/packages"
368 List<PathNode> packagesChildren = new ArrayList<>(packageToModules.size());
369 for (Map.Entry<String, List<String>> entry : packageToModules.entrySet()) {
370 String pkgName = entry.getKey();
371 List<String> moduleNameList = entry.getValue();
372 List<PathNode> moduleLinkNodes = new ArrayList<>(moduleNameList.size());
373 for (String moduleName : moduleNameList) {
374 PathNode moduleNode = Objects.requireNonNull(nodes.get(MODULES + moduleName));
375 PathNode linkNode = new PathNode(PACKAGES + pkgName + "/" + moduleName, moduleNode);
376 nodes.put(linkNode.getName(), linkNode);
377 moduleLinkNodes.add(linkNode);
378 }
379 PathNode pkgDir = new PathNode(PACKAGES + pkgName, moduleLinkNodes);
380 nodes.put(pkgDir.getName(), pkgDir);
381 packagesChildren.add(pkgDir);
382 }
383 // "/packages" dir
384 PathNode packagesRootNode = new PathNode("/packages", packagesChildren);
385 nodes.put(packagesRootNode.getName(), packagesRootNode);
386
387 // finally "/" dir!
388 List<PathNode> rootChildren = new ArrayList<>();
389 rootChildren.add(packagesRootNode);
390 rootChildren.add(modulesRootNode);
391 PathNode root = new PathNode("/", rootChildren);
392 nodes.put(root.getName(), root);
393 }
394
395 private PathNode findPackagesAndCreateModuleNode(Path moduleDir, Map<String, List<String>> packageToModules)
396 throws IOException {
397 String moduleName = moduleDir.getFileName().toString();
398 UnaryOperator<Path> previewExtractor = isPreviewMode
399 ? (p -> p.startsWith(PREVIEW_DIR) ? PREVIEW_DIR.relativize(p) : p)
400 : UnaryOperator.identity();
401 try (Stream<Path> contentsStream = Files.find(moduleDir, Integer.MAX_VALUE, (path, attr) -> attr.isDirectory())) {
402 contentsStream
403 .map(moduleDir::relativize)
404 // When in preview mode, map paths inside preview directory
405 // to non-preview versions.
406 .map(previewExtractor)
407 // Ignore the special META-INF directory (including
408 // unextracted preview).
409 .filter(p -> !p.startsWith(META_INF_DIR))
410 // Extract unique package names.
411 .map(str -> StreamSupport.stream(str.spliterator(), false)
412 .map(Path::toString)
413 .collect(Collectors.joining(".")))
414 // Ignore the root directories, regular or preview
415 .filter(st -> !st.isEmpty())
416 .distinct()
417 .forEach(pkgName ->
418 packageToModules
419 .computeIfAbsent(pkgName, k -> new ArrayList<>())
420 .add(moduleName));
421 }
422 return Objects.requireNonNull(createPathInModulesNodeIfValid(MODULES + moduleName));
423 }
424 }
|