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:codes.thischwa.c5c.impl.JarFilemanagerMessageResolver.java

@Override
public void setServletContext(ServletContext servletContext) {
    ObjectMapper mapper = new ObjectMapper();
    try {/*www .j  ava  2 s . c  o m*/
        if (JarPathResolver.insideJar(getMessagesFolderPath())) {
            CodeSource src = JarFilemanagerMessageResolver.class.getProtectionDomain().getCodeSource();
            URI uri = src.getLocation().toURI();
            logger.info("Message folder is inside jar: {}", uri);

            try (FileSystem jarFS = FileSystems.newFileSystem(uri, new HashMap<String, String>())) {
                if (jarFS.getRootDirectories().iterator().hasNext()) {
                    Path rootDirectory = jarFS.getRootDirectories().iterator().next();

                    Path langFolder = rootDirectory.resolve(getMessagesFolderPath());
                    if (langFolder != null) {
                        try (DirectoryStream<Path> langFolderStream = Files.newDirectoryStream(langFolder,
                                JS_FILE_MASK)) {
                            for (Path langFile : langFolderStream) {
                                String lang = langFile.getFileName().toString();
                                InputStream is = Files.newInputStream(langFile);
                                Map<String, String> langData = mapper.readValue(is,
                                        new TypeReference<HashMap<String, String>>() {
                                        });
                                collectLangData(lang, langData);
                            }
                        }
                    } else {
                        throw new RuntimeException("Folder in jar " + langFolder + " does not exists.");
                    }
                }
            }
        } else {
            File messageFolder = JarPathResolver.getFolder(getMessagesFolderPath());
            logger.info("Message folder resolved to: {}", messageFolder);

            if (messageFolder == null || !messageFolder.exists()) {
                throw new RuntimeException("Folder " + getMessagesFolderPath() + " does not exist");
            }

            for (File file : messageFolder.listFiles(jsFilter)) {
                String lang = FilenameUtils.getBaseName(file.getName());
                Map<String, String> langData = mapper.readValue(file,
                        new TypeReference<HashMap<String, String>>() {
                        });
                collectLangData(lang, langData);
            }
        }
    } catch (URISyntaxException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.cloudfoundry.util.FileUtils.java

/**
 * Returns a normalized {@link Path}.  In the case of directories, it returns the {@link Path} as it was passed in.  In the case of files, it returns a {@link Path} representing the root of a
 * filesystem mounted using {@link FileSystems#newFileSystem}.
 *
 * @param path the {@link Path} to normalized
 * @return the normalized path/*w  w w. j  a va 2 s  . co m*/
 */
public static Path normalize(Path path) {
    try {
        return Files.isDirectory(path) ? path : FileSystems.newFileSystem(path, null).getPath("/");
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}

From source file:org.apdplat.superword.extract.SynonymAntonymExtractor.java

public static Set<SynonymAntonym> parseZip(String zipFile) {
    Set<SynonymAntonym> data = new HashSet<>();
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override//from w  ww .java  2 s.com
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
    return data;
}

From source file:org.schedulesdirect.grabber.Auditor.java

Auditor(CommandAudit opts) throws IOException {
    this.opts = opts;
    try {//from   ww w  .  j  a va2  s  . c o m
        vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", opts.getSrc().toURI())),
                Collections.<String, Object>emptyMap());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.cirdles.webServices.calamari.PrawnFileHandlerService.java

private Path zip(Path target) throws IOException {
    Path zipFilePath = target.resolveSibling("reports.zip");

    try (FileSystem zipFileFileSystem = FileSystems.newFileSystem(URI.create("jar:" + zipFilePath.toUri()),
            ZIP_FILE_ENV)) {/*  w w w. j a v  a2  s.co m*/

        Files.list(target).forEach(entry -> {
            try {
                Files.copy(entry, zipFileFileSystem.getPath("/" + entry.getFileName()));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }

    return zipFilePath;
}

From source file:io.redlink.solrlib.SolrCoreDescriptor.java

static void unpackSolrCoreZip(Path solrCoreBundle, Path solrHome, ClassLoader classLoader) throws IOException {
    final String contentType = Files.probeContentType(solrCoreBundle);
    if ("application/zip".equals(contentType) ||
    //fallback if Files.probeContentType(..) fails (such as on Max OS X)
            (contentType == null/*  w  w w.  j a v  a2  s .c  o  m*/
                    && StringUtils.endsWithAny(solrCoreBundle.getFileName().toString(), ".zip", ".jar"))) {
        LoggerFactory.getLogger(SolrCoreDescriptor.class).debug("Unpacking SolrCore zip {} to {}",
                solrCoreBundle, solrHome);
        try (FileSystem fs = FileSystems.newFileSystem(solrCoreBundle, classLoader)) {
            unpackSolrCoreDir(fs.getPath("/"), solrHome);
        }
    } else {
        throw new IllegalArgumentException(
                "Packaged solrCoreBundle '" + solrCoreBundle + "' has unsupported type: " + contentType);
    }
}

From source file:at.tfr.securefs.client.SecurefsClient.java

public void run() {
    DateTime start = new DateTime();
    try (FileSystem fs = FileSystems.newFileSystem(new URI(baseDir), null)) {

        for (Path path : files) {

            Path sec = fs.getPath(path.toString() + (asyncTest ? "." + Thread.currentThread().getId() : ""));

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }//w  ww .ja va2 s .c om

                if (path.getParent() != null) {
                    fs.provider().createDirectory(fs.getPath(path.getParent().toString()));
                }
                final OutputStream secOs = Files.newOutputStream(sec);

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + sec);

                IOUtils.copyLarge(Files.newInputStream(path), secOs, new byte[128 * 1024]);
                secOs.close();
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                final InputStream secIs = Files.newInputStream(sec);
                IOUtils.copyLarge(secIs, Files.newOutputStream(out), new byte[128 * 1024]);
                secIs.close();
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());

                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = fs.provider().deleteIfExists(sec);
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

From source file:net.geoprism.localization.LocaleManager.java

private Collection<Locale> loadCLDRs() {
    try {/*from w  w w  .ja  va 2 s  .  c  om*/

        // Get the list of known CLDR locale
        Set<Locale> locales = new HashSet<Locale>();

        Set<String> paths = new HashSet<String>();

        URL resource = this.getClass().getResource("/cldr/main");
        URI uri = resource.toURI();

        if (uri.getScheme().equals("jar")) {
            FileSystem fileSystem = FileSystems.newFileSystem(uri, new HashMap<String, Object>());
            Path path = fileSystem.getPath("/cldr/main");

            Stream<Path> walk = Files.walk(path, 1);

            try {
                for (Iterator<Path> it = walk.iterator(); it.hasNext();) {
                    Path location = it.next();

                    paths.add(location.toAbsolutePath().toString());
                }
            } finally {
                walk.close();
            }
        } else {
            String url = resource.getPath();
            File root = new File(url);

            File[] files = root.listFiles(new DirectoryFilter());

            if (files != null) {
                for (File file : files) {
                    paths.add(file.getAbsolutePath());
                }
            }
        }

        for (String path : paths) {
            File file = new File(path);

            String filename = file.getName();

            locales.add(LocaleManager.getLocaleForName(filename));
        }

        return locales;
    } catch (Exception e) {
        throw new ProgrammingErrorException(e);
    }
}

From source file:org.apdplat.superword.extract.HyphenExtractor.java

public static Map<String, AtomicInteger> parseZip(String zipFile) {
    Map<String, AtomicInteger> data = new HashMap<>();
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override/*from  w w  w.  jav  a2s  .com*/
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    Map<String, AtomicInteger> rs = parseFile(temp.toFile().getAbsolutePath());
                    rs.keySet().forEach(k -> {
                        data.putIfAbsent(k, new AtomicInteger());
                        data.get(k).addAndGet(rs.get(k).get());
                    });
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
    return data;
}

From source file:de.fatalix.bookery.bl.background.importer.CalibriImporter.java

private void processArchive(final Path zipFile, final int batchSize) throws IOException {
    try (FileSystem zipFileSystem = FileSystems.newFileSystem(zipFile, null)) {
        final List<BookEntry> bookEntries = new ArrayList<>();
        Path root = zipFileSystem.getPath("/");
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

            @Override/*w  w w.  ja v  a2  s  .  c  om*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.toString().contains("__MACOSX")) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
                    BookEntry bookEntry = new BookEntry().setUploader("admin");
                    for (Path path : directoryStream) {
                        if (!Files.isDirectory(path)) {
                            if (path.toString().contains(".opf")) {
                                bookEntry = parseOPF(path, bookEntry);
                            }
                            if (path.toString().contains(".mobi")) {
                                bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI");
                            }
                            if (path.toString().contains(".epub")) {
                                bookEntry.setEpub(Files.readAllBytes(path));
                            }
                            if (path.toString().contains(".jpg")) {
                                bookEntry.setCover(Files.readAllBytes(path));
                                ByteArrayOutputStream output = new ByteArrayOutputStream();
                                Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200)
                                        .toOutputStream(output);
                                bookEntry.setThumbnail(output.toByteArray());
                                bookEntry.setThumbnailGenerated("done");
                            }
                        }
                    }
                    if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) {
                        bookEntries.add(bookEntry);
                        if (bookEntries.size() > batchSize) {
                            logger.info("Adding " + bookEntries.size() + " Books...");
                            try {
                                solrHandler.addBeans(bookEntries);
                            } catch (SolrServerException ex) {
                                logger.error(ex, ex);
                            }
                            bookEntries.clear();
                        }
                    }
                } catch (IOException ex) {
                    logger.error(ex, ex);
                }
                return super.preVisitDirectory(dir, attrs);
            }
        });
        try {
            if (!bookEntries.isEmpty()) {
                logger.info("Adding " + bookEntries.size() + " Books...");
                solrHandler.addBeans(bookEntries);
            }
        } catch (SolrServerException ex) {
            logger.error(ex, ex);
        }
    } finally {
        Files.delete(zipFile);
    }
}