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.ejisto.util.IOUtils.java

public static void zipDirectory(File src, String outputFilePath) throws IOException {
    Path out = Paths.get(outputFilePath);
    if (Files.exists(out)) {
        Files.delete(out);//from  ww  w  .j  a v  a  2s . c  o  m
    }
    String filePath = out.toUri().getPath();
    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    try (FileSystem targetFs = FileSystems.newFileSystem(URI.create("jar:file:" + filePath), env)) {
        Files.walkFileTree(src.toPath(), new CopyFileVisitor(src.toPath(), targetFs.getPath("/")));
    }
}

From source file:org.objectpocket.storage.blob.MultiZipBlobStore.java

private synchronized FileSystem getReadFileSystem(String name) throws IOException {
    FileSystem fileSystem = readFileSystems.get(name);
    if (fileSystem == null || !fileSystem.isOpen()) {
        Path path = Paths.get(directory + "/" + name);
        URI uri = URI.create("jar:" + path.toUri());
        Map<String, String> env = new HashMap<>();
        fileSystem = FileSystems.newFileSystem(uri, env);
        readFileSystems.put(name, fileSystem);
    }/*ww w  .  j  a va 2  s .com*/
    return fileSystem;
}

From source file:fr.mby.opa.pics.web.controller.UploadPicturesController.java

protected List<Path> processArchive(final MultipartFile multipartFile) throws IOException {
    final List<Path> archivePictures = new ArrayList<>(128);

    // We copy the archive in a tmp file
    final File tmpFile = File.createTempFile(multipartFile.getName(), ".tmp");
    multipartFile.transferTo(tmpFile);/*  w  w w.  j  a va2 s .  c  o m*/
    // final InputStream archiveInputStream = multipartFile.getInputStream();
    // Streams.copy(archiveInputStream, new FileOutputStream(tmpFile), true);
    // archiveInputStream.close();

    final Path tmpFilePath = tmpFile.toPath();
    final FileSystem archiveFs = FileSystems.newFileSystem(tmpFilePath, null);

    final Iterable<Path> rootDirs = archiveFs.getRootDirectories();
    for (final Path rootDir : rootDirs) {
        Files.walkFileTree(rootDir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path path, final BasicFileAttributes attrs)
                    throws IOException {
                final boolean isDirectory = Files.isDirectory(path);

                if (!isDirectory) {
                    final String contentType = Files.probeContentType(path);
                    if (contentType != null && contentType.startsWith("image/")) {
                        archivePictures.add(path);
                    }
                }

                return super.visitFile(path, attrs);
            }
        });
    }

    return archivePictures;
}

From source file:com.evolveum.midpoint.init.InitialDataImport.java

private File[] getInitialImportObjects() {
    URL path = InitialDataImport.class.getClassLoader().getResource("initial-objects");
    String resourceType = path.getProtocol();

    File[] files = null;/*  w  ww .j  a v a  2 s.  co  m*/
    File folder = null;

    if ("zip".equals(resourceType) || "jar".equals(resourceType)) {
        try {
            File tmpDir = new File(configuration.getMidpointHome() + "/tmp");
            if (!tmpDir.mkdir()) {
                LOGGER.warn(
                        "Failed to create temporary directory for inital objects {}. Maybe it already exists",
                        configuration.getMidpointHome() + "/tmp");
            }

            tmpDir = new File(configuration.getMidpointHome() + "/tmp/initial-objects");
            if (!tmpDir.mkdir()) {
                LOGGER.warn(
                        "Failed to create temporary directory for inital objects {}. Maybe it already exists",
                        configuration.getMidpointHome() + "/tmp/initial-objects");
            }

            //prerequisite: we are expecting that the files are store in the same archive as the source code that is loading it
            URI src = InitialDataImport.class.getProtectionDomain().getCodeSource().getLocation().toURI();
            LOGGER.trace("InitialDataImport code location: {}", src);
            Map<String, String> env = new HashMap<>();
            env.put("create", "false");
            URI normalizedSrc = new URI(src.toString().replaceFirst("file:", "jar:file:"));
            LOGGER.trace("InitialDataImport normalized code location: {}", normalizedSrc);
            try (FileSystem zipfs = FileSystems.newFileSystem(normalizedSrc, env)) {
                Path pathInZipfile = zipfs.getPath("/initial-objects");
                //TODO: use some well defined directory, e.g. midPoint home
                final Path destDir = Paths.get(configuration.getMidpointHome() + "/tmp");
                Files.walkFileTree(pathInZipfile, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        final Path destFile = Paths.get(destDir.toString(), file.toString());
                        LOGGER.trace("Extracting file {} to {}", file, destFile);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING);
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        final Path dirToCreate = Paths.get(destDir.toString(), dir.toString());
                        if (Files.notExists(dirToCreate)) {
                            LOGGER.trace("Creating directory {}", dirToCreate);
                            Files.createDirectory(dirToCreate);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });

            }
            folder = new File(configuration.getMidpointHome() + "/tmp/initial-objects");
        } catch (IOException ex) {
            throw new RuntimeException(
                    "Failed to copy initial objects file out of the archive to the temporary directory", ex);
        } catch (URISyntaxException ex) {
            throw new RuntimeException("Failed get URI for the source code bundled with initial objects", ex);
        }
    }

    if ("file".equals(resourceType)) {
        folder = getResource("initial-objects");
    }

    files = folder.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            if (pathname.isDirectory()) {
                return false;
            }

            return true;
        }
    });
    Arrays.sort(files, new Comparator<File>() {

        @Override
        public int compare(File o1, File o2) {
            int n1 = getNumberFromName(o1);
            int n2 = getNumberFromName(o2);

            return n1 - n2;
        }
    });

    return files;
}

From source file:org.objectpocket.storage.blob.MultiZipBlobStore.java

private synchronized FileSystem getWriteFileSystem(String name) throws IOException {
    FileSystem fileSystem = writeFileSystems.get(name);
    if (fileSystem == null || !fileSystem.isOpen()) {
        closeReadFileSystem(name);// w w  w .j ava 2s .co m
        Path path = Paths.get(new File(directory + "/" + name).getAbsolutePath());
        URI uri = URI.create("jar:" + path.toUri());
        Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        fileSystem = FileSystems.newFileSystem(uri, env);
        writeFileSystems.put(name, fileSystem);
    }
    return fileSystem;
}

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

@SafeVarargs
public static void unzipFile(File src, Path outputDirectory, FileVisitor<Path>... additionalVisitor)
        throws IOException {
    if (!Files.exists(outputDirectory)) {
        Files.createDirectories(outputDirectory);
    }/*from w w w.  j a v  a 2  s .  c  o m*/
    if (!Files.isDirectory(outputDirectory)) {
        throw new IllegalStateException(outputDirectory.toUri() + " is not a directory");
    }
    try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:file:" + src.getAbsolutePath()),
            Collections.<String, Object>emptyMap())) {
        final Path srcRoot = fileSystem.getPath("/");
        FileVisitor<Path> visitor = new MultipurposeFileVisitor<>(new CopyFileVisitor(srcRoot, outputDirectory),
                additionalVisitor);
        Files.walkFileTree(srcRoot, visitor);
    }
}

From source file:org.elasticsearch.test.rest.yaml.ESClientYamlSuiteTestCase.java

/**
 * Returns a new FileSystem to read REST resources, or null if they
 * are available from classpath.//from w w w. j  a  v a  2  s  . co m
 */
@SuppressForbidden(reason = "proper use of URL, hack around a JDK bug")
protected static FileSystem getFileSystem() throws IOException {
    // REST suite handling is currently complicated, with lots of filtering and so on
    // For now, to work embedded in a jar, return a ZipFileSystem over the jar contents.
    URL codeLocation = FileUtils.class.getProtectionDomain().getCodeSource().getLocation();
    boolean loadPackaged = RandomizedTest.systemPropertyAsBoolean(REST_LOAD_PACKAGED_TESTS, true);
    if (codeLocation.getFile().endsWith(".jar") && loadPackaged) {
        try {
            // hack around a bug in the zipfilesystem implementation before java 9,
            // its checkWritable was incorrect and it won't work without write permissions.
            // if we add the permission, it will open jars r/w, which is too scary! so copy to a safe r-w location.
            Path tmp = Files.createTempFile(null, ".jar");
            try (InputStream in = FileSystemUtils.openFileURLStream(codeLocation)) {
                Files.copy(in, tmp, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileSystems.newFileSystem(new URI("jar:" + tmp.toUri()), Collections.emptyMap());
        } catch (URISyntaxException e) {
            throw new IOException("couldn't open zipfilesystem: ", e);
        }
    } else {
        return null;
    }
}

From source file:org.openeos.tools.maven.plugins.GenerateEntitiesMojo.java

private List<File> findLiquibaseFiles(Artifact artifact) throws IOException {

    if (artifact == null) {
        return Collections.emptyList();
    }//from  w  w  w.j  av  a  2 s .  c  o m
    List<File> result = new ArrayList<File>();

    if (artifact.getType().equals("jar")) {
        File file = artifact.getFile();
        FileSystem fs = FileSystems.newFileSystem(Paths.get(file.getAbsolutePath()),
                this.getClass().getClassLoader());
        PathMatcher matcher = fs.getPathMatcher("glob:" + searchpath);
        JarFile jarFile = new JarFile(file);
        Enumeration<JarEntry> entries = jarFile.entries();
        TreeSet<JarEntry> setEntries = new TreeSet<JarEntry>(new Comparator<JarEntry>() {

            @Override
            public int compare(JarEntry o1, JarEntry o2) {
                return o1.getName().compareTo(o2.getName());
            }

        });
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (matcher.matches(fs.getPath(entry.getName()))) {
                setEntries.add(entry);
            }
        }
        for (JarEntry entry : setEntries) {
            File resultFile = File.createTempFile("generate-entities-maven", ".xml");
            FileOutputStream out = new FileOutputStream(resultFile);
            InputStream in = jarFile.getInputStream(entry);
            IOUtils.copy(in, out);
            in.close();
            out.close();
            result.add(resultFile);
        }
        jarFile.close();
    }
    return result;
}

From source file:org.kaaproject.kaa.server.common.dao.AbstractTest.java

protected String readSchemaFileAsString(String filePath) throws IOException {
    try {/*from  ww  w  .j  a va2  s  .  c  o m*/
        URI uri = this.getClass().getClassLoader().getResource(filePath).toURI();
        String[] array = uri.toString().split("!");
        Path path;
        if (array.length > 1) {
            LOG.info("Creating fs for {}", array[0]);
            FileSystem fs;
            try {
                fs = FileSystems.newFileSystem(URI.create(array[0]), new HashMap<String, String>());
            } catch (FileSystemAlreadyExistsException e) {
                fs = FileSystems.getFileSystem(URI.create(array[0]));
            }
            path = fs.getPath(array[1]);
        } else {
            path = Paths.get(uri);
        }
        return new String(Files.readAllBytes(path));
    } catch (URISyntaxException e) {
        LOG.error("Can't generate configs {}", e);
    }
    return null;
}

From source file:com.facebook.buck.util.unarchive.Unzip.java

/**
 * Gets a set of files that are contained in an archive
 *
 * @param archiveAbsolutePath The absolute path to the archive
 * @return A set of files (not directories) that are contained in the zip file
 * @throws IOException If there is an error reading the archive
 *///from  w w w  .j a  v  a  2s  .c om
public static ImmutableSet<Path> getZipMembers(Path archiveAbsolutePath) throws IOException {
    try (FileSystem zipFs = FileSystems.newFileSystem(archiveAbsolutePath, null)) {
        Path root = Iterables.getOnlyElement(zipFs.getRootDirectories());
        return Files.walk(root).filter(path -> !Files.isDirectory(path)).map(root::relativize)
                .map(path -> Paths.get(path.toString())) // Clear the filesystem from the path
                .collect(ImmutableSet.toImmutableSet());
    } catch (ZipError error) {
        // For some reason the zip filesystem support throws an error when an IOException would do
        // just as well.
        throw new IOException(
                String.format("Could not read %s because of %s", archiveAbsolutePath, error.toString()), error);
    }
}