Example usage for java.nio.file FileSystems newFileSystem

List of usage examples for java.nio.file FileSystems newFileSystem

Introduction

In this page you can find the example usage for java.nio.file FileSystems newFileSystem.

Prototype

public static FileSystem newFileSystem(Path path, Map<String, ?> env) throws IOException 

Source Link

Document

Constructs a new FileSystem to access the contents of a file as a file system.

Usage

From source file:com.sonar.it.scanner.msbuild.TestUtils.java

private static void replaceInZip(URI zipUri, Path src, String dest) {
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    // locate file system by using the syntax
    // defined in java.net.JarURLConnection
    URI uri = URI.create("jar:" + zipUri);
    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Path pathInZipfile = zipfs.getPath(dest);
        LOG.info("Replacing the file " + pathInZipfile + " in the zip " + zipUri + " with " + src);
        Files.copy(src, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }/*from   www.  j  av  a  2 s  .c o m*/
}

From source file:com.ejisto.util.IOUtils.java

public static Collection<String> findAllClassesInJarFile(File jarFile) throws IOException {
    final List<String> ret = new ArrayList<>();
    Map<String, String> env = new HashMap<>();
    env.put("create", "false");
    try (FileSystem targetFs = FileSystems.newFileSystem(URI.create("jar:file:" + jarFile.getAbsolutePath()),
            env)) {/*from   ww w  . ja  va 2  s. co m*/
        final Path root = targetFs.getPath("/");
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String ext = ".class";
                if (attrs.isRegularFile() && file.getFileName().toString().endsWith(ext)) {
                    String path = root.relativize(file).toString();
                    ret.add(translatePath(path.substring(0, path.length() - ext.length()), "/"));
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
    return ret;
}

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

private static Path getPathInJar(final String filename) throws JBOPClassException {
    Path file;// w  w  w.  j a  va  2  s  . co m
    final String[] fileParts = StringUtils.split(filename, "!");
    final String zipFile = fileParts[0];
    final String classFile = fileParts[1];
    FileSystem fileSystem;
    try {
        fileSystem = FileSystems.newFileSystem(Paths.get(zipFile), ClassAccessor.class.getClassLoader());
    } catch (final IOException e) {
        throw new JBOPClassException(
                "The jar containing the class (" + zipFile + ": " + classFile + ") couldn't be accessed.", e);
    }

    file = fileSystem.getPath(classFile);
    return file;
}

From source file:com.kegare.caveworld.util.CaveUtils.java

public static boolean archiveDirZip(final File dir, final File dest) {
    final Path dirPath = dir.toPath();
    final String parent = dir.getName();
    Map<String, String> env = Maps.newHashMap();
    env.put("create", "true");
    URI uri = dest.toURI();//from  w w w  .java  2 s. c o  m

    try {
        uri = new URI("jar:" + uri.getScheme(), uri.getPath(), null);
    } catch (Exception e) {
        return false;
    }

    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Files.createDirectory(zipfs.getPath(parent));

        for (File file : dir.listFiles()) {
            if (file.isDirectory()) {
                Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, zipfs.getPath(parent, dirPath.relativize(file).toString()),
                                StandardCopyOption.REPLACE_EXISTING);

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Files.createDirectory(zipfs.getPath(parent, dirPath.relativize(dir).toString()));

                        return FileVisitResult.CONTINUE;
                    }
                });
            } else {
                Files.copy(file.toPath(), zipfs.getPath(parent, file.getName()),
                        StandardCopyOption.REPLACE_EXISTING);
            }
        }

        return true;
    } catch (Exception e) {
        e.printStackTrace();

        return false;
    }
}

From source file:org.olat.repository.RepositoryEntryImportExport.java

/**
 * Read previousely exported Propertiesproperties
 *///  www .j a  v a  2  s  . c o m
private void loadConfiguration() {
    try {
        if (baseDirectory.exists()) {
            if (baseDirectory.getName().endsWith(".zip")) {
                Path fPath = FileSystems.newFileSystem(baseDirectory.toPath(), null).getPath("/");
                Path manifestPath = fPath.resolve("export").resolve(PROPERTIES_FILE);
                try (InputStream inputFile = Files.newInputStream(manifestPath, StandardOpenOption.READ)) {
                    XStream xstream = getXStream();
                    repositoryProperties = (RepositoryEntryImport) xstream.fromXML(inputFile);
                } catch (Exception e) {
                    log.error("Cannot read repo.xml im zip", e);
                }
            } else {
                File inputFile = new File(baseDirectory, PROPERTIES_FILE);
                if (inputFile.exists()) {
                    XStream xstream = getXStream();
                    repositoryProperties = (RepositoryEntryImport) xstream.fromXML(inputFile);
                } else {
                    repositoryProperties = new RepositoryEntryImport();
                }
            }
        } else {
            repositoryProperties = new RepositoryEntryImport();
        }
        propertiesLoaded = true;
    } catch (Exception ce) {
        throw new OLATRuntimeException("Error importing repository entry properties.", ce);
    }
}

From source file:io.kahu.hawaii.util.call.sql.DbRequestBuilderRepository.java

private void walkDirectory(final String directory) {
    try {//w w w.  ja v  a  2s.c om
        URI uri = this.getClass().getResource(directory).toURI();
        Path myPath;
        if (uri.getScheme().equals("jar")) {
            FileSystem fileSystem = null;
            try {
                fileSystem = FileSystems.getFileSystem(uri);
            } catch (Exception e) {
                // ignore
            }
            if (fileSystem == null) {
                fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap());
            }
            myPath = fileSystem.getPath(directory);
        } else {
            myPath = Paths.get(uri);
        }
        Stream<Path> walk = Files.walk(myPath, 1);
        walk.forEach((path) -> {
            String name = path.getFileName().toString();
            if (name.endsWith(".sql")) {
                DbRequestPrototype p = createPrototype(directory, name);
                if (p != null) {
                    try {
                        add(new DbRequestBuilder(p));
                    } catch (ServerException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java

/**
 * Create a jar file from the given directory.
 * @param dir source directory/*from www.j  a va 2 s .c  o m*/
 * @param jarFile jar file name
 * @throws IOException when file cannot be created
 */
public static void createJar(File dir, File jarFile) throws IOException {

    final Map<String, ?> env = Collections.singletonMap("create", "true");
    if (jarFile.exists() && !jarFile.delete()) {
        throw new RuntimeException("Failed to remove " + jarFile);
    }
    URI uri = URI.create("jar:" + jarFile.toURI());
    try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {

        File manifestFile = new File(dir, JarFile.MANIFEST_NAME);
        Files.createDirectory(zipfs.getPath("META-INF"));
        try (final OutputStream out = Files.newOutputStream(zipfs.getPath(JarFile.MANIFEST_NAME))) {
            if (!manifestFile.exists()) {
                new Manifest().write(out);
            } else {
                FileUtils.copyFile(manifestFile, out);
            }
        }

        final java.nio.file.Path root = dir.toPath();
        Files.walkFileTree(root, new java.nio.file.SimpleFileVisitor<Path>() {
            String relativePath;

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                relativePath = root.relativize(dir).toString();
                if (!relativePath.isEmpty()) {
                    if (!relativePath.endsWith("/")) {
                        relativePath += "/";
                    }
                    if (!relativePath.equals("META-INF/")) {
                        final Path dstDir = zipfs.getPath(relativePath);
                        Files.createDirectory(dstDir);
                    }
                }
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String name = relativePath + file.getFileName();
                if (!JarFile.MANIFEST_NAME.equals(name)) {
                    try (final OutputStream out = Files.newOutputStream(zipfs.getPath(name))) {
                        FileUtils.copyFile(file.toFile(), out);
                    }
                }
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                relativePath = root.relativize(dir.getParent()).toString();
                if (!relativePath.isEmpty() && !relativePath.endsWith("/")) {
                    relativePath += "/";
                }
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}

From source file:com.romeikat.datamessie.core.base.util.FileUtil.java

private Path createZipFile(final String dir, String filename, final List<Path> files) throws IOException {
    filename = normalizeFilename(filename);
    // Create ZIP file
    Path zipFile = Paths.get(dir, filename + ".zip");
    zipFile = getNonExisting(zipFile);/*from w w  w . j ava 2 s.  com*/
    Files.createFile(zipFile);
    final URI zipUri = URI.create("jar:file:" + zipFile.toUri().getPath());
    Files.delete(zipFile);
    final Map<String, String> zipProperties = new HashMap<String, String>();
    zipProperties.put("create", "true");
    zipProperties.put("encoding", "UTF-8");
    final FileSystem zipFS = FileSystems.newFileSystem(zipUri, zipProperties);
    // Copy TXT files to ZIP file
    for (final Path file : files) {
        final Path fileToZip = file;
        final Path pathInZipfile = zipFS.getPath(file.getFileName().toString());
        Files.copy(fileToZip, pathInZipfile);
    }
    // Done
    zipFS.close();
    return zipFile;
}

From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java

/**
 * Writes file to disk and copy the contents of the input byte array.
 *
 * @param file   a Path with file path./* w ww  .  j a  va2 s .c  om*/
 * @param zipUrl a remote zip url to be saved as file
 * @throws IOException
 */
private void writeZipFile(final Path file, final URL zipUrl) throws URISyntaxException, IOException {
    final URI resourceURI = zipUrl.toURI();
    final Map<String, String> env = new HashMap<>();
    final String resourceUriStr = URLDecoder.decode(resourceURI.toString(), "UTF-8");
    final int indexOfSeparator = resourceUriStr.indexOf("!");
    final ZipFileSystem fs = (ZipFileSystem) FileSystems.newFileSystem(resourceURI, env);
    final Path path = fs.getPath(resourceUriStr.substring(indexOfSeparator + 1));
    try {
        Files.copy(path, file, StandardCopyOption.REPLACE_EXISTING);
    } finally {
        fs.close();
    }
}

From source file:com.streamsets.datacollector.cluster.EmrClusterProvider.java

void replaceFileInJar(String absolutePath, String fileToBeCopied) throws IOException {
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    URI uri = URI.create("jar:file:" + absolutePath);

    try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
        Path externalTxtFile = Paths.get(fileToBeCopied);
        Path pathInZipfile = zipfs.getPath("cluster_sdc.properties");
        Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
    }//from   w  ww .ja  va2  s .  c  o  m
}