Example usage for java.nio.file SimpleFileVisitor SimpleFileVisitor

List of usage examples for java.nio.file SimpleFileVisitor SimpleFileVisitor

Introduction

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

Prototype

protected SimpleFileVisitor() 

Source Link

Document

Initializes a new instance of this class.

Usage

From source file:science.atlarge.graphalytics.powergraph.PowergraphPlatform.java

@Override
public BenchmarkMetrics finalize(RunSpecification runSpecification) {
    stopPlatformLogging();/* ww  w .ja  v  a 2s  .co m*/
    BenchmarkRunSetup benchmarkRunSetup = runSpecification.getBenchmarkRunSetup();
    BenchmarkRun benchmarkRun = runSpecification.getBenchmarkRun();

    Path platformLogPath = benchmarkRunSetup.getLogDir().resolve("platform");

    final List<Double> superstepTimes = new ArrayList<>();

    try {
        Files.walkFileTree(platformLogPath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String logs = FileUtil.readFile(file);
                for (String line : logs.split("\n")) {
                    if (line.contains("- run algorithm:")) {
                        Pattern regex = Pattern.compile(".* - run algorithm: ([+-]?([0-9]*[.])?[0-9]+) sec.*");
                        Matcher matcher = regex.matcher(line);
                        matcher.find();
                        superstepTimes.add(Double.parseDouble(matcher.group(1)));
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (superstepTimes.size() != 0) {
        Double procTime = 0.0;
        for (Double superstepTime : superstepTimes) {
            procTime += superstepTime;
        }

        BenchmarkMetrics metrics = new BenchmarkMetrics();
        BigDecimal procTimeS = (new BigDecimal(procTime)).setScale(3, RoundingMode.CEILING);
        metrics.setProcessingTime(new BenchmarkMetric(procTimeS, "s"));

        return metrics;
    } else {
        LOG.error("Failed to find any metrics regarding superstep runtime.");
        return new BenchmarkMetrics();
    }
}

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

private void deleteRecursive(Path path) throws IOException {
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override//  w  w  w .  j a v  a  2  s.  c  o  m
        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;
        }
    });
}

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

private Set<File> checkForLocalFiles(File file) throws IOException, URISyntaxException {
    final Set<File> result = new TreeSet<File>();
    final PathMatcher matcher = FileSystems.getDefault()
            .getPathMatcher("glob:" + file.getAbsolutePath() + "/" + searchpath);
    SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {

        @Override/*from  www  . j  a v a 2 s. co m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (matcher.matches(file)) {
                result.add(file.toFile());
            }
            return FileVisitResult.CONTINUE;
        }

    };
    Files.walkFileTree(file.toPath(), fileVisitor);
    return result;
}

From source file:com.yahoo.parsec.gradle.utils.FileUtils.java

/**
 * Find files in path.// ww  w .java  2  s. c o  m
 *
 * @param path    find path
 * @param pattern find patttern
 * @return a set of path
 * @throws IOException IOException
 */
public Set<Path> findFiles(String path, String pattern) throws IOException {
    try {
        Set<Path> paths = new HashSet<>();
        PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(pattern);

        Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) {
                if (pathMatcher.matches(filePath.getFileName())) {
                    paths.add(filePath);
                }
                return FileVisitResult.CONTINUE;
            }
        });

        return paths;
    } catch (IOException e) {
        throw e;
    }
}

From source file:lucene.IndexFiles.java

/**
135   * Indexes the given file using the given writer, or if a directory is given,
136   * recurses over files and directories found under the given directory.
137   * //from  w ww .  ja  va  2  s  . com
138   * NOTE: This method indexes one document per input file.  This is slow.  For good
139   * throughput, put multiple documents into your input file(s).  An example of this is
140   * in the benchmark module, which can create "line doc" files, one document per line,
141   * using the
142   * <a href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html"
143   * >WriteLineDocTask</a>.
144   *  
145   * @param writer Writer to the index where the given file/dir info will be stored
146   * @param path The file to index, or the directory to recurse into to find files to index
147   * @throws IOException If there is a low-level I/O error
148   */
static void indexDocs(final IndexWriter writer, Path path) throws IOException {
    System.out.println("Test 2.1");

    if (Files.isDirectory(path)) {
        System.out.println("Test 2.2");
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try {
                    System.out.println("Test 2.3");
                    System.out.println(file.toString());
                    indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
                    System.out.println("Test 2.4");
                } catch (IOException ignore) {
                    // don't index files that can't be read.
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
    }
}

From source file:org.apache.taverna.robundle.manifest.Manifest.java

public void populateFromBundle() throws IOException {
    final Set<Path> potentiallyEmptyFolders = new LinkedHashSet<>();

    final Set<URI> existingAggregationsToPrune = new HashSet<>(aggregates.keySet());

    walkFileTree(bundle.getRoot(), new SimpleFileVisitor<Path>() {
        @SuppressWarnings("deprecation")
        @Override//from  ww  w.ja v a 2 s.  c o  m
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            super.postVisitDirectory(dir, exc);
            if (potentiallyEmptyFolders.remove(dir)) {
                URI uri = relativeToBundleRoot(dir.toUri());
                existingAggregationsToPrune.remove(uri);
                PathMetadata metadata = aggregates.get(uri);
                if (metadata == null) {
                    metadata = new PathMetadata();
                    aggregates.put(uri, metadata);
                }
                metadata.setFile(withSlash(dir));
                metadata.setFolder(withSlash(dir.getParent()));
                metadata.setProxy();
                metadata.setCreatedOn(getLastModifiedTime(dir));
                potentiallyEmptyFolders.remove(withSlash(dir.getParent()));
                return CONTINUE;
            }
            return CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (dir.startsWith(RO) || dir.startsWith(META_INF))
                return SKIP_SUBTREE;
            potentiallyEmptyFolders.add(withSlash(dir));
            potentiallyEmptyFolders.remove(withSlash(dir.getParent()));
            return CONTINUE;
        }

        @SuppressWarnings("deprecation")
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            potentiallyEmptyFolders.remove(withSlash(file.getParent()));
            if (file.startsWith(MIMETYPE))
                return CONTINUE;
            if (manifest.contains(file))
                // Don't aggregate the manifests
                return CONTINUE;

            // super.visitFile(file, attrs);
            URI uri = relativeToBundleRoot(file.toUri());
            existingAggregationsToPrune.remove(uri);
            PathMetadata metadata = aggregates.get(uri);
            if (metadata == null) {
                metadata = new PathMetadata();
                aggregates.put(uri, metadata);
            }
            metadata.setFile(file);
            if (metadata.getMediatype() == null)
                // Don't override if already set
                metadata.setMediatype(guessMediaType(file));
            metadata.setFolder(withSlash(file.getParent()));
            metadata.setProxy();
            metadata.setCreatedOn(getLastModifiedTime(file));
            potentiallyEmptyFolders.remove(file.getParent());
            return CONTINUE;
        }
    });
    for (URI preExisting : existingAggregationsToPrune) {
        PathMetadata meta = aggregates.get(preExisting);
        if (meta.getFile() != null)
            /*
             * Don't remove 'virtual' resources, only aggregations that went
             * to files
             */
            aggregates.remove(preExisting);
    }
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected void addFolder(Path testFilePath, JsonNode stepJsonNode) throws Exception {

    SyncSite syncSite = getSyncSite(stepJsonNode);

    String dependency = getString(stepJsonNode, "dependency");

    final Path dependencyFilePath = getDependencyFilePath(testFilePath, dependency);

    FileSystem fileSystem = FileSystems.getDefault();

    final Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(),
            dependency.replace("common" + fileSystem.getSeparator(), "")));

    Files.walkFileTree(dependencyFilePath, new SimpleFileVisitor<Path>() {

        @Override/*w  w w .j  av  a 2  s  . co  m*/
        public FileVisitResult preVisitDirectory(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.createDirectories(targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.copy(filePath, targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:org.roda.core.storage.fs.FSUtils.java

/**
 * Copies a directory/file from one path to another
 * //  w w  w.ja  v  a 2  s.c  om
 * @param sourcePath
 *          source path
 * @param targetPath
 *          target path
 * @param replaceExisting
 *          true if the target directory/file should be replaced if it already
 *          exists; false otherwise
 * @throws AlreadyExistsException
 * @throws GenericException
 */
public static void copy(final Path sourcePath, final Path targetPath, boolean replaceExisting)
        throws AlreadyExistsException, GenericException {

    // check if we can replace existing
    if (!replaceExisting && FSUtils.exists(targetPath)) {
        throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath);
    }

    // ensure parent directory exists or can be created
    try {
        if (targetPath != null) {
            Files.createDirectories(targetPath.getParent());
        }
    } catch (IOException e) {
        throw new GenericException("Error while creating target directory parent folder", e);
    }

    if (FSUtils.isDirectory(sourcePath)) {
        try {
            Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.copy(file, targetPath.resolve(sourcePath.relativize(file)));
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new GenericException("Error while copying one directory into another", e);
        }
    } else {
        try {

            CopyOption[] copyOptions = replaceExisting
                    ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
                    : new CopyOption[] {};
            Files.copy(sourcePath, targetPath, copyOptions);
        } catch (IOException e) {
            throw new GenericException("Error while copying one file into another", e);
        }

    }

}

From source file:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java

private Set<File> walkDirectory(Path directory) {
    final Set<File> walkedFiles = new LinkedHashSet<File>();
    try {/*  w  w  w  .j  a  v  a  2  s  .c  o  m*/
        registerWatch(directory);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
                // No need to monitor the git metadata
                if (dir.toFile().getPath().contains(".git")) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                registerWatch(dir);
                return fileVisitResult;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.visitFile(file, attrs);
                walkedFiles.add(file.toFile());
                return fileVisitResult;
            }

        });
    } catch (IOException e) {
        log.error("Failed to walk directory: " + directory.toString(), e);
    }
    return walkedFiles;
}

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

public static boolean emptyDir(File file) {
    Path directory = file.toPath();
    if (!Files.isDirectory(directory)) {
        return true;
    }/*from   w w  w  .ja  va  2s .c o  m*/
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<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 {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.TERMINATE;
            }
        });
    } catch (IOException e) {
        IOUtils.log.error(format("error while trying to empty the directory %s", directory.toString()), e);
        return false;
    }
    return true;
}