Java Code Examples for java.nio.file.FileSystems#newFileSystem()

The following examples show how to use java.nio.file.FileSystems#newFileSystem() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JdepsConfiguration.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
SystemModuleFinder(String javaHome) throws IOException {
    if (javaHome == null) {
        // --system none
        this.fileSystem = null;
        this.root = null;
        this.systemModules = Collections.emptyMap();
    } else {
        if (Files.isRegularFile(Paths.get(javaHome, "lib", "modules")))
            throw new IllegalArgumentException("Invalid java.home: " + javaHome);

        // alternate java.home
        Map<String, String> env = new HashMap<>();
        env.put("java.home", javaHome);
        // a remote run-time image
        this.fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), env);
        this.root = fileSystem.getPath("/modules");
        this.systemModules = walk(root);
    }
}
 
Example 2
Source File: ConcSemanticsTests.java    From Concurnas with MIT License 6 votes vote down vote up
@Test
public void mainifestMissingEntryPointJar() throws IOException {
	ConccTestMockFileLoader mockFL = new ConccTestMockFileLoader();
	
	Path jarPath = mockFL.fs.getPath("thing.jar");
	URI jarUri = URI.create("jar:" + jarPath.toUri());
	
	Map<String, String> env = new HashMap<String, String>();
	env.put("create", "true");
	try (FileSystem zipfs = FileSystems.newFileSystem(jarUri, env)) {
		Files.createDirectories(zipfs.getPath("/META-INF/"));
		Path manifest = zipfs.getPath("/META-INF/MANIFEST.MF");
		Files.write(manifest, ListMaker.make(""), StandardCharsets.UTF_8);
	}
	
	Conc concc = new Conc("thing.jar", mockFL);// ok
	
	TestCase.assertEquals("Manifest file META-INF/MANIFEST.MF is missing 'Main-Class' entry", concc.validateConcInstance(concc.getConcInstance()).validationErrs);
}
 
Example 3
Source File: SchemaLoader.java    From raptor with Apache License 2.0 6 votes vote down vote up
public Schema load() throws IOException {
  if (sources.isEmpty()) {
    throw new IllegalStateException("No sources added.");
  }

  try (Closer closer = Closer.create()) {
    // Map the physical path to the file system root. For regular directories the key and the
    // value are equal. For ZIP files the key is the path to the .zip, and the value is the root
    // of the file system within it.
    Map<Path, Path> directories = new LinkedHashMap<>();
    for (Path source : sources) {
      if (Files.isRegularFile(source)) {
        FileSystem sourceFs = FileSystems.newFileSystem(source, getClass().getClassLoader());
        closer.register(sourceFs);
        directories.put(source, getOnlyElement(sourceFs.getRootDirectories()));
      } else {
        directories.put(source, source);
      }
    }
    return loadFromDirectories(directories);
  }
}
 
Example 4
Source File: FileSystemUtils.java    From vind with Apache License 2.0 6 votes vote down vote up
/**
 * Convert a local URL (file:// or jar:// protocol) to a {@link Path}
 * @param resource the URL resource
 * @return the Path
 * @throws URISyntaxException
 * @throws IOException
 */
public static Path toPath(URL resource) throws IOException, URISyntaxException {
    if (resource == null) return null;

    final String protocol = resource.getProtocol();
    if ("file".equals(protocol)) {
        return Paths.get(resource.toURI());
    } else if ("jar".equals(protocol)) {
        final String s = resource.toString();
        final int separator = s.indexOf("!/");
        final String entryName = s.substring(separator + 2);
        final URI fileURI = URI.create(s.substring(0, separator));

        final FileSystem fileSystem;
        synchronized (jarFileSystems) {
            if (jarFileSystems.add(fileURI)) {
                fileSystem = FileSystems.newFileSystem(fileURI, Collections.<String, Object>emptyMap());
            } else {
                fileSystem = FileSystems.getFileSystem(fileURI);
            }
        }
        return fileSystem.getPath(entryName);
    } else {
        throw new IOException("Can't read " + resource + ", unknown protocol '" + protocol + "'");
    }
}
 
Example 5
Source File: FrontendUtils.java    From j2cl with Apache License 2.0 6 votes vote down vote up
public static FileSystem initZipOutput(String output, Problems problems) {
  Path outputPath = Paths.get(output);
  if (Files.isDirectory(outputPath)) {
    problems.fatal(FatalError.OUTPUT_LOCATION, outputPath);
  }

  // Ensures that we will not fail if the zip already exists.
  outputPath.toFile().delete();

  try {
    return FileSystems.newFileSystem(
        URI.create("jar:" + outputPath.toAbsolutePath().toUri()),
        ImmutableMap.of("create", "true"));
  } catch (IOException e) {
    problems.fatal(FatalError.CANNOT_CREATE_ZIP, outputPath, e.getMessage());
    return null;
  }
}
 
Example 6
Source File: ZipCat.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The main method for the ZipCat program. Run the program with an empty
 * argument list to see possible arguments.
 *
 * @param args the argument list for ZipCat
 */
public static void main(String[] args) {
    if (args.length != 2) {
        System.out.println("Usage: ZipCat zipfile fileToPrint");
    }
    /*
     * Creates AutoCloseable FileSystem and BufferedReader.
     * They will be closed automatically after the try block.
     * If reader initialization fails, then zipFileSystem will be closed
     * automatically.
     */
    try (FileSystem zipFileSystem
            = FileSystems.newFileSystem(Paths.get(args[0]),null);
            InputStream input
            = Files.newInputStream(zipFileSystem.getPath(args[1]))) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = input.read(buffer)) != -1) {
                    System.out.write(buffer, 0, len);
                }

    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}
 
Example 7
Source File: ModelUtils.java    From quarkus with Apache License 2.0 6 votes vote down vote up
static Model readAppModel(Path appJar) throws IOException {
    try (FileSystem fs = FileSystems.newFileSystem(appJar, (ClassLoader) null)) {
        final Path metaInfMaven = fs.getPath("META-INF", "maven");
        if (Files.exists(metaInfMaven)) {
            try (DirectoryStream<Path> groupIds = Files.newDirectoryStream(metaInfMaven)) {
                for (Path groupIdPath : groupIds) {
                    if (!Files.isDirectory(groupIdPath)) {
                        continue;
                    }
                    try (DirectoryStream<Path> artifactIds = Files.newDirectoryStream(groupIdPath)) {
                        for (Path artifactIdPath : artifactIds) {
                            if (!Files.isDirectory(artifactIdPath)) {
                                continue;
                            }
                            final Path pomXml = artifactIdPath.resolve("pom.xml");
                            if (Files.exists(pomXml)) {
                                return readModel(pomXml);
                            }
                        }
                    }
                }
            }
        }
        throw new IOException("Failed to located META-INF/maven/<groupId>/<artifactId>/pom.xml in " + appJar);
    }
}
 
Example 8
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void checkModule(String mn, String... packages) throws IOException {
    // verify ModuleDescriptor from the runtime module
    ModuleDescriptor md = ModuleLayer.boot().findModule(mn).get()
                               .getDescriptor();
    checkModuleDescriptor(md, packages);

    // verify ModuleDescriptor from module-info.class read from ModuleReader
    try (InputStream in = ModuleFinder.ofSystem().find(mn).get()
        .open().open("module-info.class").get()) {
        checkModuleDescriptor(ModuleDescriptor.read(in), packages);
    }

    // verify ModuleDescriptor from module-info.class read from jimage
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
        Collections.emptyMap());
    Path path = fs.getPath("/", "modules", mn, "module-info.class");
    checkModuleDescriptor(ModuleDescriptor.read(Files.newInputStream(path)), packages);
}
 
Example 9
Source File: TestClassIndexer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public static Index indexTestClasses(Class<?> testClass) {
    final Indexer indexer = new Indexer();
    final Path testClassesLocation = getTestClassesLocation(testClass);
    try {
        if (Files.isDirectory(testClassesLocation)) {
            indexTestClassesDir(indexer, testClassesLocation);
        } else {
            try (FileSystem jarFs = FileSystems.newFileSystem(testClassesLocation, null)) {
                for (Path p : jarFs.getRootDirectories()) {
                    indexTestClassesDir(indexer, p);
                }
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException("Unable to index the test-classes/ directory.", e);
    }
    return indexer.complete();
}
 
Example 10
Source File: ZipUtils.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * This call is not thread safe, a single of FileSystem can be created for the
 * profided uri until it is closed.
 * 
 * @param uri The uri to the zip file.
 * @param env Env map.
 * @return A new FileSystem.
 * @throws IOException in case of a failure
 */
public static FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException {
    // If Multi threading required, logic should be added to wrap this fs
    // onto a fs that handles a reference counter and close the fs only when all thread are done
    // with it.
    try {
        return FileSystems.newFileSystem(uri, env);
    } catch (IOException | ZipError ioe) {
        // TODO: (at a later date) Get rid of the ZipError catching (and instead only catch IOException)
        //  since it's a JDK bug which threw the undeclared ZipError instead of an IOException.
        //  Java 9 fixes it https://bugs.openjdk.java.net/browse/JDK-8062754

        // include the URI for which the filesystem creation failed
        throw new IOException("Failed to create a new filesystem for " + uri, ioe);
    }
}
 
Example 11
Source File: Main.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static boolean hasModuleTarget(String modName) throws IOException {
    FileSystem fs = FileSystems.newFileSystem(URI.create("jrt:/"),
                                              Collections.emptyMap());
    Path path = fs.getPath("/", "modules", modName, "module-info.class");
    try (InputStream in = Files.newInputStream(path)) {
        return hasModuleTarget(in);
    }
}
 
Example 12
Source File: ClassPathJarResource.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isReadable() {
   boolean rtn = false;
   try (FileSystem fileSystem = FileSystems.newFileSystem(this.jarRoot, Collections.<String, Object> emptyMap())) {
      Path fsPath = fileSystem.getPath(this.jarPath);
      rtn = fsPath != null && Files.isReadable(fsPath);
   }
   catch (IOException e) {
      logger.warn("Failed to close jar filesystem root [{}] during isReadable check of [{}]", this.jarRoot, this.path, e);
   }

   return rtn;
}
 
Example 13
Source File: JavacPathFileManager.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private FileSystem getFileSystem(Path p) throws IOException {
    FileSystem fs = fileSystems.get(p);
    if (fs == null) {
        fs = FileSystems.newFileSystem(p, null);
        fileSystems.put(p, fs);
    }
    return fs;
}
 
Example 14
Source File: Plugin.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void walkResources(FileVisitor<? super Path> visitor) throws URISyntaxException, IOException {
  try (FileSystem zipFs =
               FileSystems.newFileSystem(artifactURL.toURI(), new HashMap<>())) {
    Path resourcesPath = zipFs.getPath("/resources");
    if(Files.isDirectory(resourcesPath)) {
      Files.walkFileTree(resourcesPath, visitor);
    }
  }
}
 
Example 15
Source File: PetsciiArtGallery.java    From petscii-bbs with Mozilla Public License 2.0 5 votes vote down vote up
public List<Path> getDirContent(String path) throws URISyntaxException, IOException {
    List<Path> result = new ArrayList<>();
    URL jar = getClass().getProtectionDomain().getCodeSource().getLocation();
    Path jarFile = Paths.get(jar.toURI());
    try (FileSystem fs = FileSystems.newFileSystem(jarFile, NULL_CLASSLOADER);
        DirectoryStream<Path> directoryStream = Files.newDirectoryStream(fs.getPath(path))) {
        for (Path p : directoryStream) {
            result.add(p);
        }

        result.sort((o1, o2) -> o1 == null || o2 == null ? 0 :
                o1.getFileName().toString().compareTo(o2.getFileName().toString()));
        return result;
    }
}
 
Example 16
Source File: ModulesInCustomFileSystem.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Opens a JAR file as a file system
 */
private void testJarFileSystem(Path jar) throws Exception {
    ClassLoader scl = ClassLoader.getSystemClassLoader();
    try (FileSystem fs = FileSystems.newFileSystem(jar, scl)) {
        // ModuleFinder to find modules in top-level directory
        Path top = fs.getPath("/");
        ModuleFinder finder = ModuleFinder.of(top);

        // list the modules
        listAllModules(finder);

        // load modules into child layer, invoking m1/p.Main
        loadAndRunModule(finder);
    }
}
 
Example 17
Source File: Plugin.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void copyResources(File dir) throws URISyntaxException, IOException {

  if(!hasResources())
    throw new UnsupportedOperationException(
        "this plugin doesn't have any resources you can copy as you would know had you called hasResources first :P");
  
  Path target = Paths.get(dir.toURI());
  try (FileSystem zipFs =
      FileSystems.newFileSystem(getArtifactURL().toURI(), new HashMap<>());) {

    Path pathInZip = zipFs.getPath("/resources");

    Files.walkFileTree(pathInZip, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path filePath,
          BasicFileAttributes attrs) throws IOException {
        // Make sure that we conserve the hierachy of files and folders
        // inside the zip
        Path relativePathInZip = pathInZip.relativize(filePath);
        Path targetPath = target.resolve(relativePathInZip.toString());
        Files.createDirectories(targetPath.getParent());

        // And extract the file
        Files.copy(filePath, targetPath,
            StandardCopyOption.REPLACE_EXISTING);

        return FileVisitResult.CONTINUE;
      }
    });
  } catch(Exception e) {
    // TODO Auto-generated catch block
    throw new IOException(e);
  }
}
 
Example 18
Source File: ZipResourceLoader.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T loadResource(String name, ResourceInputStreamConsumer<T> consumer) throws IOException {
    try (FileSystem fs = FileSystems.newFileSystem(zip, (ClassLoader) null)) {
        final Path p = fs.getPath("/", name);
        if (!Files.exists(p)) {
            throw new IOException("Failed to locate " + name + " in " + zip);
        }
        try (InputStream is = Files.newInputStream(p)) {
            return consumer.consume(is);
        }
    }
}
 
Example 19
Source File: JavacPathFileManager.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private FileSystem getFileSystem(Path p) throws IOException {
    FileSystem fs = fileSystems.get(p);
    if (fs == null) {
        fs = FileSystems.newFileSystem(p, null);
        fileSystems.put(p, fs);
    }
    return fs;
}
 
Example 20
Source File: ModularRuntimeImage.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Constructs an instance using the JRT file system implementation from a specific Java Home.
 *
 * @param javaHome
 *            Path to a Java 9 or greater home.
 *
 * @throws IOException
 *             an I/O error occurs accessing the file system
 */
public ModularRuntimeImage(final String javaHome) throws IOException {
    final Map<String, ?> emptyMap = Collections.emptyMap();
    final Path jrePath = Paths.get(javaHome);
    final Path jrtFsPath = jrePath.resolve("lib").resolve("jrt-fs.jar");
    this.classLoader = new URLClassLoader(new URL[] {jrtFsPath.toUri().toURL() });
    this.fileSystem = FileSystems.newFileSystem(URI.create("jrt:/"), emptyMap, classLoader);
}