@Test public void itShouldReturnNullIfNotValidJarProvider() { fileSupport = new FakeFileSupport(set(), set()) { @Override public Path getJarFileSystemRoot(Path jarFile) { super.getJarFileSystemRoot(jarFile); throw new ProviderNotFoundException(); } }; fileSupport.setJarFileSystemRoot(null); target = new JarSourceProvider(fileSupport); ClassSource result = target.findSource("foobar", new FakeSearchPath("foo/bar")); Assert.assertEquals(set(mkpath("foo/bar")), fileSupport.getCheckedJarFileSystemRoots()); Assert.assertNull(result); }
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException { this.archivePath = archivePath; if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) { Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue); FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider(); Assert.checkNonNull(jarFSProvider, "should have been caught before!"); this.fileSystem = jarFSProvider.newFileSystem(archivePath, env); } else { this.fileSystem = FileSystems.newFileSystem(archivePath, null); } packages = new HashMap<>(); for (Path root : fileSystem.getRootDirectories()) { Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { if (isValid(dir.getFileName())) { packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir); return FileVisitResult.CONTINUE; } else { return FileVisitResult.SKIP_SUBTREE; } } }); } }
/** * Retrieves a file system using the default {@link FileSystems#getFileSystem(URI)}. If this * throws a * @param uri * @return */ public static FileSystem getFileSystem(URI uri) { try { return FileSystems.getFileSystem(uri); } catch (FileSystemNotFoundException | ProviderNotFoundException e) { LOG.debug("File system scheme " + uri.getScheme() + " not found in the default installed providers list, attempting to find this in the " + "list of additional providers"); } for (WeakReference<FileSystemProvider> providerRef : providers) { FileSystemProvider provider = providerRef.get(); if (provider != null && uri.getScheme().equals(provider.getScheme())) { return provider.getFileSystem(uri); } } throw new ProviderNotFoundException("Could not find provider for scheme '" + uri.getScheme() + "'"); }
public void handleRequest(TransportChannel channel, Request request) { Response response = new Response(); Class<?> interfaceClass = request.getInterfaceClass(); response.setRequestId(request.getRequestId()); Object providerInstance = providerContainer.getProvider(interfaceClass); if (providerInstance == null) { response.setResult(new ProviderNotFoundException("No Provider For " + request.getClass().getName())); channel.write(response); return; } MethodAccess methodAccess = methodAccessCache.computeIfAbsent(interfaceClass, key -> MethodAccess.get(key)); try { Object result = methodAccess.invoke(providerInstance, request.getMethodName(), request.getArgs()); response.setResult(result); } catch (Throwable t) { response.setResult(t); } channel.write(response); return; }
private ClassSource createSource(Path jarFile) { try { Path jarRootPath = fileSupport.getJarFileSystemRoot(jarFile); if (jarRootPath == null) { return null; } ClassLoader classLoader = fileSupport.createClassLoader(jarFile); return new JarFileSource(jarFile, jarRootPath, classLoader); } catch (ProviderNotFoundException | MalformedURLException e) { } return null; }
public static boolean isAvailable() { try { FileSystems.getFileSystem(URI.create("jrt:/")); return true; } catch (ProviderNotFoundException | FileSystemNotFoundException e) { return false; } }
static void checkNoUOE() throws IOException, URISyntaxException { String dir = System.getProperty("test.dir", "."); String fileName = dir + File.separator + "foo.bar"; Path path = Paths.get(fileName); Path file = Files.createFile(path); try { URI uri = new URI("jar", file.toUri().toString(), null); System.out.println(uri); FileSystem fs = FileSystems.newFileSystem(uri, new HashMap()); fs.close(); } catch (ProviderNotFoundException pnfe) { System.out.println("Expected ProviderNotFoundException caught: " + "\"" + pnfe.getMessage() + "\""); } }
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException { this.archivePath = archivePath; if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) { Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue); this.fileSystem = getJarFSProvider().newFileSystem(archivePath, env); } else { this.fileSystem = FileSystems.newFileSystem(archivePath, null); } }
private FileSystemProvider getJarFSProvider() throws IOException { if (jarFSProvider != null) { return jarFSProvider; } for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { if (provider.getScheme().equals("jar")) { return (jarFSProvider = provider); } } throw new ProviderNotFoundException("no provider found for .jar files"); }
private static boolean isPosixCompliant() { try { if (FileSystems.getDefault() .supportedFileAttributeViews() .contains("posix")) { return true; } return false; } catch (FileSystemNotFoundException | ProviderNotFoundException | SecurityException e) { return false; } }
private void bindNativeLibs() { Set<Path> pathStream; try { pathStream = new NativeLibsJarIntrospectSearch().getNativeLibraries(); } catch (ProviderNotFoundException e) { log.error(e.getMessage()); pathStream = new NativeLibsIDEIntrospectSearch().getNativeLibraries(); } new NativeLibsBinder().bindLibs(pathStream); }
public List<InputSplit> getSplits( List<InputSplit> splits, Configuration cfg) throws IOException { final List<InputSplit> origSplits = removeIndexFiles(splits); // Align the splits so that they don't cross blocks. // addIndexedSplits() requires the given splits to be sorted by file // path, so do so. Although FileInputFormat.getSplits() does, at the time // of writing this, generate them in that order, we shouldn't rely on it. Collections.sort(origSplits, new Comparator<InputSplit>() { public int compare(InputSplit a, InputSplit b) { FileSplit fa = (FileSplit)a, fb = (FileSplit)b; return fa.getPath().compareTo(fb.getPath()); } }); final List<InputSplit> newSplits = new ArrayList<InputSplit>(origSplits.size()); for (int i = 0; i < origSplits.size();) { try { i = addIndexedSplits (origSplits, i, newSplits, cfg); } catch (IOException | ProviderNotFoundException e) { if (cfg.getBoolean(ENABLE_BAI_SPLIT_CALCULATOR, false)) { try { i = addBAISplits (origSplits, i, newSplits, cfg); } catch (IOException | ProviderNotFoundException e2) { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } else { i = addProbabilisticSplits (origSplits, i, newSplits, cfg); } } } return filterByInterval(newSplits, cfg); }
public static synchronized JavaInstallation getDefault() throws IOException { if (instance == null) { List<Path> cp; try { cp = getJrtFs(); } catch (ProviderNotFoundException e) { cp = getJava8(); } instance = new JavaInstallation(cp); } return instance; }
@VisibleForTesting static FileSystem newFileSystem(URI uri, Configuration config) { checkArgument( URI_SCHEME.equals(uri.getScheme()), "uri (%s) must have scheme %s", uri, URI_SCHEME); try { // Create the FileSystem. It uses JimfsFileSystemProvider as its provider, as that is // the provider that actually implements the operations needed for Files methods to work. JimfsFileSystem fileSystem = JimfsFileSystems.newFileSystem(JimfsFileSystemProvider.instance(), uri, config); /* * Now, call FileSystems.newFileSystem, passing it the FileSystem we just created. This * allows the system-loaded SystemJimfsFileSystemProvider instance to cache the FileSystem * so that methods like Paths.get(URI) work. * We do it in this awkward way to avoid issues when the classes in the API (this class * and Configuration, for example) are loaded by a different classloader than the one that * loads SystemJimfsFileSystemProvider using ServiceLoader. See * https://github.com/google/jimfs/issues/18 for gory details. */ try { ImmutableMap<String, ?> env = ImmutableMap.of(FILE_SYSTEM_KEY, fileSystem); FileSystems.newFileSystem(uri, env, SystemJimfsFileSystemProvider.class.getClassLoader()); } catch (ProviderNotFoundException | ServiceConfigurationError ignore) { // See the similar catch block below for why we ignore this. // We log there rather than here so that there's only typically one such message per VM. } return fileSystem; } catch (IOException e) { throw new AssertionError(e); } }
public void addFile(Path file, boolean warn) { if (contains(file)) { // discard duplicates return; } if (!fsInfo.exists(file)) { /* No such file or directory exists */ if (warn) { log.warning(Lint.LintCategory.PATH, Warnings.PathElementNotFound(file)); } super.add(file); return; } Path canonFile = fsInfo.getCanonicalFile(file); if (canonicalValues.contains(canonFile)) { /* Discard duplicates and avoid infinite recursion */ return; } if (fsInfo.isFile(file)) { /* File is an ordinary file. */ if ( !file.getFileName().toString().endsWith(".jmod") && !file.endsWith("modules")) { if (!isArchive(file)) { /* Not a recognized extension; open it to see if it looks like a valid zip file. */ try { FileSystems.newFileSystem(file, null).close(); if (warn) { log.warning(Lint.LintCategory.PATH, Warnings.UnexpectedArchiveFile(file)); } } catch (IOException | ProviderNotFoundException e) { // FIXME: include e.getLocalizedMessage in warning if (warn) { log.warning(Lint.LintCategory.PATH, Warnings.InvalidArchiveFile(file)); } return; } } else { if (fsInfo.getJarFSProvider() == null) { log.error(Errors.NoZipfsForArchive(file)); return ; } } } } /* Now what we have left is either a directory or a file name conforming to archive naming convention */ super.add(file); canonicalValues.add(canonFile); if (expandJarClassPaths && fsInfo.isFile(file) && !file.endsWith("modules")) { addJarClassPath(file, warn); } }
private void initSystemModules() throws IOException { if (moduleTable != null) return; if (systemJavaHome == null) { moduleTable = new ModuleTable(); return; } if (modules == null) { try { URI jrtURI = URI.create("jrt:/"); FileSystem jrtfs; if (isCurrentPlatform(systemJavaHome)) { jrtfs = FileSystems.getFileSystem(jrtURI); } else { try { Map<String, String> attrMap = Collections.singletonMap("java.home", systemJavaHome.toString()); jrtfs = FileSystems.newFileSystem(jrtURI, attrMap); } catch (ProviderNotFoundException ex) { URL javaHomeURL = systemJavaHome.resolve("jrt-fs.jar").toUri().toURL(); ClassLoader currentLoader = Locations.class.getClassLoader(); URLClassLoader fsLoader = new URLClassLoader(new URL[] {javaHomeURL}, currentLoader); jrtfs = FileSystems.newFileSystem(jrtURI, Collections.emptyMap(), fsLoader); closeables.add(fsLoader); } closeables.add(jrtfs); } modules = jrtfs.getPath("/modules"); } catch (FileSystemNotFoundException | ProviderNotFoundException e) { modules = systemJavaHome.resolve("modules"); if (!Files.exists(modules)) throw new IOException("can't find system classes", e); } } moduleTable = new ModuleTable(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(modules, Files::isDirectory)) { for (Path entry : stream) { String moduleName = entry.getFileName().toString(); String name = location.getName() + "[" + moduleName + "]"; ModuleLocationHandler h = new ModuleLocationHandler(this, name, moduleName, Collections.singletonList(entry), false); moduleTable.add(h); } } }
static List<Class<?>> getClasses(int count) throws Exception { List<Class<?>> classes = new ArrayList<>(); FileSystem fs = null; try { fs = FileSystems.getFileSystem(URI.create("jrt:/")); } catch (ProviderNotFoundException | FileSystemNotFoundException e) { throw new RuntimeException("FAIL - JRT Filesystem not found"); } List<String> fileNames; Path modules = fs.getPath("/modules"); Predicate<String> startsWithJavaBase = path -> path.toString().startsWith("java.base/java"); Predicate<String> startsWithJavaDesktop = path -> path.toString().startsWith("java.desktop/java"); Predicate<String> startsWithJavaDataTransfer = path -> path.toString().startsWith("java.datatransfer/java"); Predicate<String> startsWithJavaRMI = path -> path.toString().startsWith("java.rmi/java"); Predicate<String> startsWithJavaSmartCardIO = path -> path.toString().startsWith("java.smartcardio/java"); Predicate<String> startsWithJavaManagement = path -> path.toString().startsWith("java.management/java"); Predicate<String> startsWithJavaXML = path -> path.toString().startsWith("java.xml/java"); Predicate<String> startsWithJavaXMLBind = path -> path.toString().startsWith("java.xml.bind/java"); Predicate<String> startsWithJavaScripting = path -> path.toString().startsWith("java.scripting/java"); Predicate<String> startsWithJavaNaming = path -> path.toString().startsWith("java.naming/java"); Predicate<String> startsWithJavaSQL = path -> path.toString().startsWith("java.sql/java"); Predicate<String> startsWithJavaActivation = path -> path.toString().startsWith("java.activation/java"); Predicate<String> startsWithJavaCompiler = path -> path.toString().startsWith("java.compiler/java"); Predicate<String> startsWithJavaAnnotations = path -> path.toString().startsWith("java.annotations/java"); Predicate<String> startsWithJavaTransaction = path -> path.toString().startsWith("java.transaction/java"); Predicate<String> startsWithJavaLogging = path -> path.toString().startsWith("java.logging/java"); Predicate<String> startsWithJavaCorba = path -> path.toString().startsWith("java.corba/java"); Predicate<String> startsWithJavaPrefs = path -> path.toString().startsWith("java.prefs/java"); fileNames = Files.walk(modules) .map(Path::toString) .filter(path -> path.toString().contains("java")) .map(s -> s.substring(9)) // remove /modules/ from beginning .filter(startsWithJavaBase .or(startsWithJavaDesktop) .or(startsWithJavaDataTransfer) .or(startsWithJavaRMI) .or(startsWithJavaSmartCardIO) .or(startsWithJavaManagement) .or(startsWithJavaXML) .or(startsWithJavaXMLBind) .or(startsWithJavaScripting) .or(startsWithJavaNaming) .or(startsWithJavaSQL) .or(startsWithJavaActivation) .or(startsWithJavaCompiler) .or(startsWithJavaAnnotations) .or(startsWithJavaTransaction) .or(startsWithJavaLogging) .or(startsWithJavaCorba) .or(startsWithJavaPrefs)) .map(s -> s.replace('/', '.')) .filter(path -> path.toString().endsWith(".class")) .map(s -> s.substring(0, s.length() - 6)) // drop .class .map(s -> s.substring(s.indexOf("."))) .filter(path -> path.toString().contains("java")) .map(s -> s.substring(s.indexOf("java"))) .collect(Collectors.toList()); for (String name : fileNames) { classes.add(Class.forName(name)); if (count == classes.size()) { break; } } return classes; }
public static void main(String[] args) throws Exception { List<String> bootClasses = new ArrayList<>(); FileSystem fs; try { fs = FileSystems.getFileSystem(URI.create("jrt:/")); } catch (ProviderNotFoundException | FileSystemNotFoundException e) { System.out.println("Not an image build, test skipped."); return; } // Build the set of locations expected in the Image Consumer<Path> c = (p) -> { // take only the .class resources. if (Files.isRegularFile(p) && p.toString().endsWith(".class") && !p.toString().endsWith("module-info.class")) { String loc = p.toString().substring("/modules".length()); bootClasses.add(loc); } }; Path javabase = fs.getPath("/modules/java.base"); Path mgtbase = fs.getPath("/modules/java.management"); try (Stream<Path> stream = Files.walk(javabase)) { stream.forEach(c); } try (Stream<Path> stream = Files.walk(mgtbase)) { stream.forEach(c); } if (bootClasses.isEmpty()) { throw new RuntimeException("No boot class to check against"); } File jdkHome = new File(System.getProperty("test.jdk")); // JPRT not yet ready for jmods Helper helper = Helper.newHelper(); if (helper == null) { System.err.println("Test not run, NO jmods directory"); return; } // Generate the sample image String module = "mod1"; String[] classes = {module + ".Main"}; helper.generateDefaultJModule(module, Arrays.asList(classes), "java.management"); Path image = helper.generateDefaultImage(module).assertSuccess(); Path extractedDir = JImageGenerator.getJImageTask() .dir(helper.createNewExtractedDir("modules")) .image(image.resolve("lib").resolve("modules")) .extract().assertSuccess(); }
public void test() throws Exception { FileSystem fs; try { fs = FileSystems.getFileSystem(URI.create("jrt:/")); } catch (ProviderNotFoundException | FileSystemNotFoundException e) { System.err.println("Not an image build, test skipped."); return; } Path javabase = fs.getPath("/modules/java.base"); checkCompress(gatherResources(javabase), new ZipPlugin(), null, new ResourceDecompressorFactory[]{ new ZipDecompressorFactory() }); ResourcePool classes = gatherClasses(javabase); // compress = String sharing checkCompress(classes, new StringSharingPlugin(), null, new ResourceDecompressorFactory[]{ new StringSharingDecompressorFactory()}); // compress level 0 == no compression Properties options0 = new Properties(); options0.setProperty(DefaultCompressPlugin.NAME, "0"); checkCompress(classes, new DefaultCompressPlugin(), options0, new ResourceDecompressorFactory[]{ }); // compress level 1 == String sharing Properties options1 = new Properties(); options1.setProperty(DefaultCompressPlugin.NAME, "1"); checkCompress(classes, new DefaultCompressPlugin(), options1, new ResourceDecompressorFactory[]{ new StringSharingDecompressorFactory() }); // compress level 1 == String sharing + filter options1.setProperty(DefaultCompressPlugin.FILTER, "**Exception.class"); options1.setProperty(DefaultCompressPlugin.NAME, "1"); checkCompress(classes, new DefaultCompressPlugin(), options1, new ResourceDecompressorFactory[]{ new StringSharingDecompressorFactory() }, Collections.singletonList(".*Exception.class")); // compress level 2 == ZIP Properties options2 = new Properties(); options2.setProperty(DefaultCompressPlugin.FILTER, "**Exception.class"); options2.setProperty(DefaultCompressPlugin.NAME, "2"); checkCompress(classes, new DefaultCompressPlugin(), options2, new ResourceDecompressorFactory[]{ new ZipDecompressorFactory() }, Collections.singletonList(".*Exception.class")); // compress level 2 == ZIP + filter options2.setProperty(DefaultCompressPlugin.FILTER, "**Exception.class"); options2.setProperty(DefaultCompressPlugin.NAME, "2"); checkCompress(classes, new DefaultCompressPlugin(), options2, new ResourceDecompressorFactory[]{ new ZipDecompressorFactory(), }, Collections.singletonList(".*Exception.class")); }
private void initSystemModules() throws IOException { if (systemModules != null) { return; } if (systemJavaHome == null) { systemModules = Collections.emptyMap(); return; } if (modules == null) { try { URI jrtURI = URI.create("jrt:/"); FileSystem jrtfs; if (isCurrentPlatform(systemJavaHome)) { jrtfs = FileSystems.getFileSystem(jrtURI); } else { try { Map<String, String> attrMap = Collections.singletonMap("java.home", systemJavaHome.toString()); jrtfs = FileSystems.newFileSystem(jrtURI, attrMap); } catch (ProviderNotFoundException ex) { URL javaHomeURL = systemJavaHome.resolve("jrt-fs.jar").toUri().toURL(); ClassLoader currentLoader = Locations.class.getClassLoader(); URLClassLoader fsLoader = new URLClassLoader(new URL[] {javaHomeURL}, currentLoader); jrtfs = FileSystems.newFileSystem(jrtURI, Collections.emptyMap(), fsLoader); closeables.add(fsLoader); } closeables.add(jrtfs); } modules = jrtfs.getPath("/modules"); } catch (FileSystemNotFoundException | ProviderNotFoundException e) { modules = systemJavaHome.resolve("modules"); if (!Files.exists(modules)) throw new IOException("can't find system classes", e); } } systemModules = new LinkedHashMap<>(); try (DirectoryStream<Path> stream = Files.newDirectoryStream(modules, Files::isDirectory)) { for (Path entry : stream) { String moduleName = entry.getFileName().toString(); String name = location.getName() + "[" + moduleName + "]"; ModuleLocationHandler h = new ModuleLocationHandler(name, moduleName, Collections.singleton(entry), false, true); systemModules.put(moduleName, h); } } }