Debian Codegraph @

native/jpype_module/src/main/java/org/jpype/pkg/JPypePackageManager.java

raw symbols SCIP
1 /* ****************************************************************************
2 Licensed under the Apache License, Version 2.0 (the "License");
3 you may not use this file except in compliance with the License.
4 You may obtain a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS,
10 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 See the License for the specific language governing permissions and
12 limitations under the License.
13
14 See NOTICE file for details.
15 **************************************************************************** */
16 package org.jpype.pkg;
17
18 import java.io.IOException;
19 import java.net.URI;
20 import java.net.URISyntaxException;
21 import java.net.URL;
22 import java.net.URLDecoder;
23 import java.nio.charset.StandardCharsets;
24 import java.nio.file.FileSystem;
25 import java.nio.file.FileSystemNotFoundException;
26 import java.nio.file.FileSystems;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.nio.file.ProviderNotFoundException;
31 import java.nio.file.spi.FileSystemProvider;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.Enumeration;
35 import java.util.HashMap;
36 import java.util.LinkedList;
37 import java.util.List;
38 import java.util.Map;
39 import org.jpype.JPypeContext;
40 import org.jpype.JPypeKeywords;
41
42 /**
43 * Manager for the contents of a package.
44 *
45 * This class uses a number of tricks to provide a way to determine what
46 * packages are available in the class loader. It searches the jar path, the
47 * boot path (Java 8), and the module path (Java 9+). It does not currently work
48 * with alternative classloaders. This class was rumored to be unobtainium as
49 * endless posts indicated that it wasn't possible to determine the contents of
50 * a package in general nor to retrieve the package contents, but this appears
51 * to be largely incorrect as the jar and jrt file system provide all the
52 * required methods.
53 *
54 */
55 public class JPypePackageManager
56 {
57
58 final static List<FileSystem> bases = new ArrayList();
59 final static List<ModuleDirectory> modules = getModules();
60 final static FileSystemProvider jfsp = getFileSystemProvider("jar");
61 final static Map<String, String> env = new HashMap<>();
62 final static LinkedList<FileSystem> fs = new LinkedList<>();
63
64 /**
65 * Checks if a package exists.
66 *
67 * @param name is the name of the package.
68 * @return true if this is a Java package either in a jar, module, or in the
69 * boot path.
70 */
71 public static boolean isPackage(String name)
72 {
73 if (name.indexOf('.') != -1)
74 name = name.replace(".", "/");
75 if (isModulePackage(name) || isBasePackage(name) || isJarPackage(name))
76 return true;
77 return false;
78 }
79
80 /**
81 * Get the list of the contents of a package.
82 *
83 * @param packageName
84 * @return the list of all resources found.
85 */
86 public static Map<String, URI> getContentMap(String packageName)
87 {
88 Map<String, URI> out = new HashMap<>();
89 packageName = packageName.replace(".", "/");
90 // We need to merge all the file systems into one view like the classloader
91 getJarContents(out, packageName);
92 getBaseContents(out, packageName);
93 getModuleContents(out, packageName);
94 return out;
95 }
96
97 /**
98 * Convert a URI into a path.
99 *
100 * This has special magic methods to deal with jar file systems.
101 *
102 * @param uri is the location of the resource.
103 * @return the path to the uri resource.
104 */
105 static Path getPath(URI uri)
106 {
107 try
108 {
109 return Paths.get(uri);
110 } catch (java.nio.file.FileSystemNotFoundException ex)
111 {
112 }
113
114 if (uri.getScheme().equals("jar"))
115 {
116 try
117 {
118 // Limit the number of filesystems open at any one time
119 fs.add(jfsp.newFileSystem(uri, env));
120 if (fs.size() > 8)
121 fs.removeFirst().close();
122 return Paths.get(uri);
123 } catch (IOException ex)
124 {
125 }
126 }
127 throw new FileSystemNotFoundException("Unknown filesystem for " + uri);
128 }
129
130 /**
131 * Retrieve the Jar file system.
132 *
133 * @return
134 */
135 private static FileSystemProvider getFileSystemProvider(String str)
136 {
137 for (FileSystemProvider fsp : FileSystemProvider.installedProviders())
138 {
139 if (fsp.getScheme().equals(str))
140 return fsp;
141 }
142 throw new FileSystemNotFoundException("Unable to find filesystem for " + str);
143 }
144
145 //<editor-fold desc="java 8" defaultstate="collapsed">
146 /**
147 * Older versions of Java do not have a file system for boot packages. Thus
148 * rather working through the classloader, we will instead probe java to get
149 * the rt.jar. Crypto is a special case as it has its own jar. All other
150 * resources are sourced through the regular jar loading method.
151 */
152 static
153 {
154 env.put("create", "true");
155
156 ClassLoader cl = ClassLoader.getSystemClassLoader();
157 URI uri = null;
158 try
159 {
160 // This is for Java 8 and earlier in which the API jars are in rt.jar
161 // and jce.jar
162 uri = cl.getResource("java/lang/String.class").toURI();
163 if (uri != null && uri.getScheme().equals("jar"))
164 {
165 FileSystem fs = jfsp.newFileSystem(uri, env);
166 if (fs != null)
167 bases.add(fs);
168 }
169 uri = cl.getResource("javax/crypto/Cipher.class").toURI();
170 if (uri != null && uri.getScheme().equals("jar"))
171 {
172 FileSystem fs = jfsp.newFileSystem(uri, env);
173 if (fs != null)
174 bases.add(fs);
175 }
176 } catch (URISyntaxException | IOException ex)
177 {
178 }
179 }
180
181 private static void getBaseContents(Map<String, URI> out, String packageName)
182 {
183 for (FileSystem b : bases)
184 {
185 collectContents(out, b.getPath(packageName));
186 }
187 }
188
189 /**
190 * Check if a name is a package in the java bootstrap classloader.
191 *
192 * @param name
193 * @return
194 */
195 private static boolean isBasePackage(String name)
196 {
197 try
198 {
199 if (name.isEmpty())
200 return false;
201 for (FileSystem jar : bases)
202 {
203 if (Files.isDirectory(jar.getPath(name)))
204 return true;
205 }
206 return false;
207 } catch (Exception ex)
208 {
209 throw new RuntimeException("Fail checking package '" + name + "'", ex);
210 }
211 }
212
213 //</editor-fold>
214 //<editor-fold desc="java 9" defaultstate="collapsed">
215 /**
216 * Get a list of all modules.
217 *
218 * This may be many modules or just a few. Limited distributes created using
219 * jlink will only have a portion of the usual modules.
220 *
221 * @return
222 */
223 static List<ModuleDirectory> getModules()
224 {
225 ArrayList<ModuleDirectory> out = new ArrayList<>();
226 try
227 {
228 FileSystem fs = FileSystems.getFileSystem(URI.create("jrt:/"));
229 Path modulePath = fs.getPath("modules");
230 for (Path module : Files.newDirectoryStream(modulePath))
231 {
232 out.add(new ModuleDirectory(module));
233 }
234 } catch (ProviderNotFoundException | IOException ex)
235 {
236 }
237 return out;
238 }
239
240 /**
241 * Check if a name corresponds to a package in a module.
242 *
243 * @param name
244 * @return true if it is a package.
245 */
246 private static boolean isModulePackage(String name)
247 {
248 if (modules.isEmpty())
249 return false;
250 String[] split = name.split("/");
251 String search = name;
252 if (split.length > 3)
253 search = String.join("/", Arrays.copyOfRange(split, 0, 3));
254 for (ModuleDirectory module : modules)
255 {
256 if (module.contains(search))
257 {
258 if (Files.isDirectory(module.modulePath.resolve(name)))
259 return true;
260 }
261 }
262 return false;
263 }
264
265 /**
266 * Retrieve the contents of a module by package name.
267 *
268 * @param out
269 * @param name
270 */
271 private static void getModuleContents(Map<String, URI> out, String name)
272 {
273 if (modules.isEmpty())
274 return;
275 String[] split = name.split("/");
276 String search = name;
277 if (split.length > 3)
278 search = String.join("/", Arrays.copyOfRange(split, 0, 3));
279 for (ModuleDirectory module : modules)
280 {
281 if (module.contains(search))
282 {
283 Path path2 = module.modulePath.resolve(name);
284 if (Files.isDirectory(path2))
285 collectContents(out, path2);
286 }
287 }
288 }
289
290 /**
291 * Modules are stored in the jrt filesystem.
292 *
293 * However, that is not a simple flat filesystem by path as the jrt files are
294 * structured by package name. Thus we will need a separate structure which is
295 * rooted at the top of each module.
296 */
297 private static class ModuleDirectory
298 {
299
300 List<String> contents = new ArrayList<>();
301 private final Path modulePath;
302
303 ModuleDirectory(Path module)
304 {
305 this.modulePath = module;
306 listPackages(contents, module, module, 0);
307 }
308
309 boolean contains(String path)
310 {
311 for (String s : contents)
312 {
313 if (s.equals(path))
314 return true;
315 }
316 return false;
317 }
318
319 private static void listPackages(List<String> o, Path base, Path p, int depth)
320 {
321 try
322 {
323 if (depth >= 3)
324 return;
325 for (Path d : Files.newDirectoryStream(p))
326 {
327 if (Files.isDirectory(d))
328 {
329 o.add(base.relativize(d).toString());
330 listPackages(o, base, d, depth + 1);
331 }
332 }
333 } catch (IOException ex)
334 {
335 }
336 }
337 }
338
339 //</editor-fold>
340 //<editor-fold desc="jar" defaultstate="collapsed">
341 /**
342 * Checks if a name corresponds to package in a jar file or on the classpath
343 * filesystem.
344 *
345 * Classloaders provide a method to get all resources with a given name. This
346 * is needed because the same package name may appear in multiple jars or
347 * filesystems. We do not need to disambiguate it here, but just get a listing
348 * that we can use to find a resource later.
349 *
350 * @param name is the name of the package to search for.
351 * @return true if the name corresponds to a Java package.
352 */
353 private static boolean isJarPackage(String name)
354 {
355 ClassLoader cl = JPypeContext.getInstance().getClassLoader();
356 try
357 {
358 Enumeration<URL> resources = cl.getResources(name);
359 while (resources.hasMoreElements())
360 {
361 URI uri = resources.nextElement().toURI();
362 if (Files.isDirectory(getPath(uri)))
363 return true;
364 }
365 } catch (IOException | URISyntaxException ex)
366 {
367 }
368 return false;
369 }
370
371 /**
372 * Retrieve a list of packages and classes stored on a file system or in a
373 * jar.
374 *
375 * @param out is the map to store the result in.
376 * @param packageName is the name of the package
377 */
378 private static void getJarContents(Map<String, URI> out, String packageName)
379 {
380 ClassLoader cl = JPypeContext.getInstance().getClassLoader();
381 try
382 {
383 String path = packageName.replace('.', '/');
384 Enumeration<URL> resources = cl.getResources(path);
385 while (resources.hasMoreElements())
386 {
387 URI resource = resources.nextElement().toURI();
388
389 // Handle MRJAR format
390 // MRJAR may not report every directory but instead just the overlay.
391 // So we need to find the original and interogate it first before
392 // checking the version specific part. Worst case we collect the
393 // contents twice.
394 String schemePart = resource.getSchemeSpecificPart();
395 int index = schemePart.indexOf("!");
396 if (index != -1)
397 {
398 if (schemePart.substring(index + 1).startsWith("/META-INF/versions/"))
399 {
400 int index2 = schemePart.indexOf('/', index + 20);
401 schemePart = schemePart.substring(0, index + 1) + schemePart.substring(index2);
402 URI resource2 = new URI(resource.getScheme() + ":" + schemePart);
403 Path path3 = getPath(resource2);
404 collectContents(out, path3);
405 }
406 }
407
408 Path path2 = getPath(resource);
409 collectContents(out, path2);
410 }
411 } catch (IOException | URISyntaxException ex)
412 {
413 }
414 }
415
416 //</editor-fold>
417 //<editor-fold desc="utility" defaultstate="collapsed">
418 /**
419 * Collect the contents from a path.
420 *
421 * This operates on jars, modules, and filesystems to collect the names of all
422 * resources found. We skip over inner classes as those are accessed under
423 * their included classes. For now we are not screening against other private
424 * symbols.
425 *
426 * @param out is the map to store the result in.
427 * @param path2 is a path holding a directory to probe.
428 */
429 private static void collectContents(Map<String, URI> out, Path path2)
430 {
431 try
432 {
433 for (Path file : Files.newDirectoryStream(path2))
434 {
435 String filename = file.getFileName().toString();
436 if (Files.isDirectory(file))
437 {
438 // Same implementations add the path separator to the end of toString().
439 if (filename.endsWith(file.getFileSystem().getSeparator()))
440 filename = filename.substring(0, filename.length() - 1);
441 out.put(JPypeKeywords.wrap(filename), toURI(file));
442 continue;
443 }
444 // Skip inner classes
445 if (filename.contains("$"))
446 continue;
447
448 // Include class files
449 if (filename.endsWith(".class"))
450 {
451 String key = JPypeKeywords.wrap(filename.substring(0, filename.length() - 6));
452 out.put(key, toURI(file));
453 }
454
455 // We can add other types of files here and import them in JPypePackage
456 // as required.
457 }
458 } catch (IOException ex)
459 {
460 }
461 }
462
463 private static URI toURI(Path path)
464 {
465 URI uri = path.toUri();
466
467 try
468 {
469 // Java 8 bug https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8131067
470 // Zip file system provider returns doubly % encoded URIs. We resolve this
471 // by re-encoding the URI after decoding it.
472 uri = new URI(
473 uri.getScheme(),
474 URLDecoder.decode(uri.getSchemeSpecificPart(), StandardCharsets.UTF_8),
475 uri.getFragment()
476 );
477
478 // `toASCIIString` ensures the URI is URL encoded with only ascii
479 // characters. This avoids issues in `sun.nio.fs.UnixUriUtils.fromUri` that
480 // naively uses `uri.getRawPath()` despite the possibility that it contains
481 // non-ascii characters that will cause errors. By using `toASCIIString` and
482 // re-wrapping it in a URI object we ensure that the URI is properly
483 // encoded. See: https://github.com/jpype-project/jpype/issues/1194
484 return new URI(uri.toASCIIString());
485 } catch (Exception e)
486 {
487 // This exception *should* never occur as we are re-encoding a valid URI.
488 // Throwing a runtime exception avoids java exception handling boilerplate
489 // for a situation that *should* never occur.
490 throw new RuntimeException("Failed to encode URI: " + uri, e);
491 }
492 }
493 //</editor-fold>
494 }