Example usage for java.nio.file Files walkFileTree

List of usage examples for java.nio.file Files walkFileTree

Introduction

In this page you can find the example usage for java.nio.file Files walkFileTree.

Prototype

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:com.kotcrab.vis.editor.module.editor.ProjectIOModule.java

public void createLibGDXProject(final ProjectLibGDX project) {
    AsyncTask task = new AsyncTask("ProjectCreator") {

        @Override/*from  w  w  w  .ja  v a 2  s.  c  om*/
        public void doInBackground() {
            setMessage("Creating directory structure...");

            FileHandle projectRoot = Gdx.files.absolute(project.getRoot());
            FileHandle standardAssetsDir = project.getAssetOutputDirectory();
            FileHandle visDir = projectRoot.child("vis");
            FileHandle visAssetsDir = visDir.child("assets");

            visDir.mkdirs();
            visAssetsDir.mkdirs();

            createStandardAssetsDirs(visAssetsDir);
            visDir.child("modules").mkdirs();

            setProgressPercent(33);
            setMessage("Moving assets...");

            try {
                Files.walkFileTree(standardAssetsDir.file().toPath(),
                        new CopyFileVisitor(visAssetsDir.file().toPath()));
            } catch (IOException e) {
                failed(e.getMessage(), e);
                Log.exception(e);
            }

            setProgressPercent(66);
            setMessage("Saving project files...");

            FileHandle projectFile = visDir.child(PROJECT_FILE);
            saveProjectFile(project, projectFile);

            setProgressPercent(100);
            statusBar.setText("Project created!");

            executeOnGdx(() -> loadNewGeneratedProject(projectFile));
        }
    };

    Async.startTask(stage, "Creating project", task);
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

private static Stream<WidgetVarLocation> findWidgetVars(Path sourceDirectory, String sourcePattern,
        ThreadPoolExecutor threadPool) throws IOException {
    BlockingQueue<WidgetVarLocation> pipe = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();
    Files.walkFileTree(sourceDirectory, new FileActionVisitor(sourceDirectory, sourcePattern,
            sourceFile -> futures.add(threadPool.submit(() -> {
                try (BufferedReader br = Files.newBufferedReader(sourceFile, StandardCharsets.UTF_8)) {
                    int lineNr = 0;
                    String line;//from w w  w  .  jav a2  s.  c o  m
                    while ((line = br.readLine()) != null) {
                        lineNr++;

                        if (line.contains("widgetVar=\"")) {
                            int startIndex = line.indexOf("widgetVar=\"") + "widgetVar=\"".length();
                            int endIndex = line.indexOf('"', startIndex);
                            String var = line.substring(startIndex, endIndex);
                            WidgetVarLocation widgetVar = new WidgetVarLocation(var, sourceFile, lineNr,
                                    startIndex, line);

                            pipe.add(widgetVar);
                        }
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }))));

    return StreamSupport.stream(new PipeSpliterator(pipe, futures), true);
}

From source file:dk.dma.msiproxy.common.provider.AbstractProviderService.java

/**
 * May be called periodically to clean up the message repo folder associated
 * with the provider./* w  w w .  ja  va2s .  c om*/
 * <p>
 * The procedure will determine which repository message ID's are still active.
 * and delete folders associated with messages ID's that are not active anymore.
 */
public void cleanUpMessageRepoFolder() {

    long t0 = System.currentTimeMillis();

    // Compute the ID's for message repository folders to keep
    Set<Integer> ids = computeReferencedMessageIds(messages);

    // Build a lookup map of all the paths that ara still active
    Set<Path> paths = new HashSet<>();
    ids.forEach(id -> {
        try {
            Path path = getMessageRepoFolder(id);
            // Add the path and the hashed sub-folders above it
            paths.add(path);
            paths.add(path.getParent());
            paths.add(path.getParent().getParent());
        } catch (IOException e) {
            log.error("Failed computing " + getProviderId() + "  message repo paths for id " + id + ": "
                    + e.getMessage());
        }
    });

    // Scan all sub-folders and delete those
    Path messageRepoRoot = getRepositoryService().getRepoRoot().resolve(MESSAGE_REPO_ROOT_FOLDER)
            .resolve(getProviderId());
    paths.add(messageRepoRoot);

    try {
        Files.walkFileTree(messageRepoRoot, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                if (!paths.contains(dir)) {
                    log.info("Deleting message repo directory :" + dir);
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (!paths.contains(file.getParent())) {
                    log.info("Deleting message repo file      :" + file);
                    Files.delete(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Failed cleaning up " + getProviderId() + " message repo: " + e.getMessage());
    }

    log.info(String.format("Cleaned up %s message repo in %d ms", getProviderId(),
            System.currentTimeMillis() - t0));
}

From source file:io.fabric8.docker.client.impl.BuildImage.java

@Override
public OutputHandle fromFolder(String path) {
    try {/*  w  ww.  ja v a2  s. c om*/
        final Path root = Paths.get(path);
        final Path dockerIgnore = root.resolve(DOCKER_IGNORE);
        final List<String> ignorePatterns = new ArrayList<>();
        if (dockerIgnore.toFile().exists()) {
            for (String p : Files.readAllLines(dockerIgnore, UTF_8)) {
                ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p);
            }
        }

        final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns);

        File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile();

        try (FileOutputStream fout = new FileOutputStream(tempFile);
                BufferedOutputStream bout = new BufferedOutputStream(fout);
                BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout);
                final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) {
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    if (dockerIgnorePathMatcher.matches(dir)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (dockerIgnorePathMatcher.matches(file)) {
                        return FileVisitResult.SKIP_SUBTREE;
                    }

                    final Path relativePath = root.relativize(file);
                    final TarArchiveEntry entry = new TarArchiveEntry(file.toFile());
                    entry.setName(relativePath.toString());
                    entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);
                    entry.setSize(attrs.size());
                    tout.putArchiveEntry(entry);
                    Files.copy(file, tout);
                    tout.closeArchiveEntry();
                    return FileVisitResult.CONTINUE;
                }
            });
            fout.flush();
        }
        return fromTar(tempFile.getAbsolutePath());

    } catch (IOException e) {
        throw DockerClientException.launderThrowable(e);
    }
}

From source file:org.apdplat.superword.rule.TextAnalysis.java

public static Set<String> getFileNames(String path) {
    Set<String> fileNames = new HashSet<>();
    if (Files.isDirectory(Paths.get(path))) {
        LOGGER.info("?" + path);
    } else {//  w  w w  .ja va2  s  .c  om
        LOGGER.info("?" + path);
        fileNames.add(path);
        return fileNames;
    }
    try {
        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().getName().startsWith(".")) {
                    return FileVisitResult.CONTINUE;
                }
                String fileName = file.toFile().getAbsolutePath();
                if (!fileName.endsWith(".txt")) {
                    LOGGER.info("??txt" + fileName);
                    return FileVisitResult.CONTINUE;
                }
                fileNames.add(fileName);
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.geowebcache.sqlite.OperationsRestTest.java

private void zipDirectory(Path directoryToZip, File outputZipFile) throws IOException {
    try (FileOutputStream fileOutputStream = new FileOutputStream(outputZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream)) {
        Files.walkFileTree(directoryToZip, new SimpleFileVisitor<Path>() {

            public FileVisitResult visitFile(Path file, BasicFileAttributes fileAttributes) throws IOException {
                zipOutputStream.putNextEntry(new ZipEntry(directoryToZip.relativize(file).toString()));
                Files.copy(file, zipOutputStream);
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }/*from ww  w  . ja  v a  2 s .  co m*/

            public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attrs)
                    throws IOException {
                if (directory.equals(directoryToZip)) {
                    return FileVisitResult.CONTINUE;
                }
                // the zip structure is not tied the OS file separator
                zipOutputStream
                        .putNextEntry(new ZipEntry(directoryToZip.relativize(directory).toString() + "/"));
                zipOutputStream.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

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);/* w  w  w  .ja  v  a  2  s  . co  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:majordodo.task.BrokerTestUtils.java

@After
public void brokerTestUtilsAfter() throws Exception {
    if (startBroker) {
        server.close();//from ww w .  jav a2  s.com
        broker.close();
        server = null;
        broker = null;
    }
    if (startReplicatedBrokers) {
        brokerLocator.close();
        server2.close();
        broker2.close();
        server1.close();
        broker1.close();
        zkServer.close();
        brokerLocator = null;
        server2 = null;
        broker2 = null;
        server1 = null;
        broker1 = null;
        zkServer = null;
    }

    // Resetting brokers config
    if (startBroker) {
        brokerConfig = new BrokerConfiguration();
    }
    if (startReplicatedBrokers) {
        broker1Config = new BrokerConfiguration();
        broker2Config = new BrokerConfiguration();
    }

    if (workDir != null) {
        Files.walkFileTree(workDir, new FileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.CONTINUE;
            }

        });
    }

    if (!ignoreUnhandledExceptions && !unhandledExceptions.isEmpty()) {
        System.out.println("Errors occurred during excecution:");
        for (Throwable e : unhandledExceptions) {
            System.out.println("\n" + ExceptionUtils.getStackTrace(e) + "\n");
        }
        fail("There are " + unhandledExceptions.size() + " unhandled exceptions!");
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy every file of given {@code zipFile} beginning with given {@code zipSubPath} to {@code destDir}
 *
 * @param zipFile/*from  w  ww  .  ja v  a 2s . c  o m*/
 * @param zipSubPath must start with a "/"
 * @param destDir
 * @throws RuntimeIOException
 */
public static void unzipSubDirectoryIfExists(@Nonnull Path zipFile, @Nonnull String zipSubPath,
        @Nonnull final Path destDir) throws RuntimeIOException {
    Preconditions.checkArgument(zipSubPath.startsWith("/"), "zipSubPath '%s' must start with a '/'",
            zipSubPath);
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath(zipSubPath);
            if (Files.notExists(root)) {
                logger.trace("Zip sub path {} does not exist in {}", zipSubPath, zipFile);
                return;
            }

            //walk the zip file tree and copy files to the destination
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        final Path destFile = Paths.get(destDir.toString(), root.relativize(file).toString());
                        logger.trace("Extract file {} to {} as {}", file, destDir, destFile);
                        Files.copy(file, destFile, StandardCopyOption.REPLACE_EXISTING,
                                StandardCopyOption.COPY_ATTRIBUTES);
                    } catch (IOException | RuntimeException e) {
                        logger.warn("Exception copying file '" + file + "' with root '" + root
                                + "' to destDir '" + destDir + "', ignore file", e);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException {
                    dir.relativize(root).toString();
                    final Path dirToCreate = Paths.get(destDir.toString(), root.relativize(dir).toString());

                    if (Files.notExists(dirToCreate)) {
                        logger.trace("Create dir {}", dirToCreate);
                        Files.createDirectory(dirToCreate);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubPath + " to " + destDir, e);
    }
}

From source file:org.vpac.ndg.storage.util.TimeSliceUtil.java

public void restore(String timesliceId) {
    TimeSlice ts = timeSliceDao.retrieve(timesliceId);
    Path tsPath = getFileLocation(ts);
    try {// ww  w  .  j  ava 2  s  . c o  m
        Files.walkFileTree(tsPath, new SimpleFileVisitor<Path>() {
            /**
             * Import netcdf dataset
             */
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                String fileName = file.getFileName().toString();

                if (!fileName.endsWith("_old" + GdalFormat.NC.getExtension())) {
                    // IGNORE NON-BACKUP TILE
                    return FileVisitResult.CONTINUE;
                }

                String restoredFilename = fileName.replace("_old", "");
                Path backupTilePath = file.toAbsolutePath();
                Path restoredTilePath = Paths.get(backupTilePath.getParent().toString(), restoredFilename);
                try {
                    FileUtils.move(backupTilePath, restoredTilePath);
                    log.debug("RESTORE {} as {}", backupTilePath, restoredTilePath);
                } catch (Exception e) {
                    log.error("{}", e);
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Error restoring {} caused by {}", tsPath, e);
    }
}