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:org.apache.jmeter.report.dashboard.HtmlTemplateExporter.java

@Override
public void export(SampleContext context, File file, ReportGeneratorConfiguration configuration)
        throws ExportException {
    Validate.notNull(context, MUST_NOT_BE_NULL, "context");
    Validate.notNull(file, MUST_NOT_BE_NULL, "file");
    Validate.notNull(configuration, MUST_NOT_BE_NULL, "configuration");

    LOG.debug("Start template processing");

    // Create data context and populate it
    DataContext dataContext = new DataContext();

    // Get the configuration of the current exporter
    final ExporterConfiguration exportCfg = configuration.getExportConfigurations().get(getName());

    // Get template directory property value
    File templateDirectory = getPropertyFromConfig(exportCfg, TEMPLATE_DIR,
            new File(JMeterUtils.getJMeterBinDir(), TEMPLATE_DIR_NAME_DEFAULT), File.class);
    if (!templateDirectory.isDirectory()) {
        String message = String.format(INVALID_TEMPLATE_DIRECTORY_FMT, templateDirectory.getAbsolutePath());
        LOG.error(message);/*from   w  ww . ja v a 2  s .  c o  m*/
        throw new ExportException(message);
    }

    // Get output directory property value
    File outputDir = getPropertyFromConfig(exportCfg, OUTPUT_DIR,
            new File(JMeterUtils.getJMeterBinDir(), OUTPUT_DIR_NAME_DEFAULT), File.class);
    String globallyDefinedOutputDir = JMeterUtils.getProperty(JMeter.JMETER_REPORT_OUTPUT_DIR_PROPERTY);
    if (!StringUtils.isEmpty(globallyDefinedOutputDir)) {
        outputDir = new File(globallyDefinedOutputDir);
    }

    JOrphanUtils.canSafelyWriteToFolder(outputDir);

    LOG.info("Will generate dashboard in folder:" + outputDir.getAbsolutePath());

    // Add the flag defining whether only sample series are filtered to the
    // context
    final boolean filtersOnlySampleSeries = exportCfg.filtersOnlySampleSeries();
    addToContext(DATA_CTX_FILTERS_ONLY_SAMPLE_SERIES, Boolean.valueOf(filtersOnlySampleSeries), dataContext);

    // Add the series filter to the context
    final String seriesFilter = exportCfg.getSeriesFilter();
    Pattern filterPattern = null;
    if (StringUtils.isNotBlank(seriesFilter)) {
        try {
            filterPattern = Pattern.compile(seriesFilter);
        } catch (PatternSyntaxException ex) {
            LOG.error(String.format("Invalid series filter: \"%s\", %s", seriesFilter, ex.getDescription()));
        }
    }
    addToContext(DATA_CTX_SERIES_FILTER, seriesFilter, dataContext);

    // Add the flag defining whether only controller series are displayed
    final boolean showControllerSeriesOnly = exportCfg.showControllerSeriesOnly();
    addToContext(DATA_CTX_SHOW_CONTROLLERS_ONLY, Boolean.valueOf(showControllerSeriesOnly), dataContext);

    JsonizerVisitor jsonizer = new JsonizerVisitor();
    Map<String, Object> storedData = context.getData();

    // Add begin date consumer result to the data context
    addResultToContext(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add end date summary consumer result to the data context
    addResultToContext(ReportGenerator.END_DATE_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add Apdex summary consumer result to the data context
    addResultToContext(ReportGenerator.APDEX_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add errors summary consumer result to the data context
    addResultToContext(ReportGenerator.ERRORS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add requests summary consumer result to the data context
    addResultToContext(ReportGenerator.REQUESTS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Add statistics summary consumer result to the data context
    addResultToContext(ReportGenerator.STATISTICS_SUMMARY_CONSUMER_NAME, storedData, dataContext, jsonizer);

    // Collect graph results from sample context and transform them into
    // Json strings to inject in the data context
    ExtraOptionsResultCustomizer customizer = new ExtraOptionsResultCustomizer();
    EmptyGraphChecker checker = new EmptyGraphChecker(filtersOnlySampleSeries, showControllerSeriesOnly,
            filterPattern);
    for (Map.Entry<String, GraphConfiguration> graphEntry : configuration.getGraphConfigurations().entrySet()) {
        final String graphId = graphEntry.getKey();
        final GraphConfiguration graphConfiguration = graphEntry.getValue();
        final SubConfiguration extraOptions = exportCfg.getGraphExtraConfigurations().get(graphId);

        // Initialize customizer and checker
        customizer.setExtraOptions(extraOptions);
        checker.setExcludesControllers(graphConfiguration.excludesControllers());
        checker.setGraphId(graphId);

        // Export graph data
        addResultToContext(graphId, storedData, dataContext, jsonizer, customizer, checker);
    }

    // Replace the begin date with its formatted string and store the old
    // timestamp
    long oldTimestamp = formatTimestamp(ReportGenerator.BEGIN_DATE_CONSUMER_NAME, dataContext);

    // Replace the end date with its formatted string
    formatTimestamp(ReportGenerator.END_DATE_CONSUMER_NAME, dataContext);

    // Add time zone offset (that matches the begin date) to the context
    TimeZone timezone = TimeZone.getDefault();
    addToContext(DATA_CTX_TIMEZONE_OFFSET, Integer.valueOf(timezone.getOffset(oldTimestamp)), dataContext);

    // Add report title to the context
    if (!StringUtils.isEmpty(configuration.getReportTitle())) {
        dataContext.put(DATA_CTX_REPORT_TITLE, StringEscapeUtils.escapeHtml4(configuration.getReportTitle()));
    }

    // Add the test file name to the context
    addToContext(DATA_CTX_TESTFILE, file.getName(), dataContext);

    // Add the overall filter property to the context
    addToContext(DATA_CTX_OVERALL_FILTER, configuration.getSampleFilter(), dataContext);

    // Walk template directory to copy files and process templated ones
    Configuration templateCfg = new Configuration(Configuration.getVersion());
    try {
        templateCfg.setDirectoryForTemplateLoading(templateDirectory);
        templateCfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        LOG.info("Report will be generated in:" + outputDir.getAbsolutePath() + ", creating folder structure");
        FileUtils.forceMkdir(outputDir);
        TemplateVisitor visitor = new TemplateVisitor(templateDirectory.toPath(), outputDir.toPath(),
                templateCfg, dataContext);
        Files.walkFileTree(templateDirectory.toPath(), visitor);
    } catch (IOException ex) {
        throw new ExportException("Unable to process template files.", ex);
    }

    LOG.debug("End of template processing");

}

From source file:org.openremote.beehive.configuration.www.UsersAPI.java

private void removeTemporaryFiles(java.nio.file.Path directory) {
    if (directory == null) {
        return;/*from w  w  w. j  a v a2  s. c  o  m*/
    }
    try {
        Files.walkFileTree(directory, new SimpleFileVisitor<java.nio.file.Path>() {
            @Override
            public FileVisitResult visitFile(java.nio.file.Path file, BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(java.nio.file.Path dir, IOException exc)
                    throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        log.error("Could not clean-up temporary folder used to create openremote.zip file", e);
    }
}

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

/**
 * Copy content for {@code srcDir} to {@code destDir}
 *
 * @param srcDir//from   www  . ja  va  2s  .c o  m
 * @param destDir
 * @throws RuntimeIOException
 */
public static void copyDirectoryContent(@Nonnull final Path srcDir, @Nonnull final Path destDir)
        throws RuntimeIOException {
    logger.trace("Copy from {} to {}", srcDir, destDir);

    FileVisitor<Path> copyDirVisitor = new SimpleFileVisitor<Path>() {

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Path targetPath = destDir.resolve(srcDir.relativize(dir));
            if (!Files.exists(targetPath)) {
                Files.createDirectory(targetPath);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.copy(file, destDir.resolve(srcDir.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
            return FileVisitResult.CONTINUE;
        }
    };
    try {
        Files.walkFileTree(srcDir, copyDirVisitor);
    } catch (IOException e) {
        throw new RuntimeIOException("Exception copying content of dir " + srcDir + " to " + destDir, e);
    }
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public void doDump(OutputStream out) throws IOException {
    final ZipOutputStream zout = new ZipOutputStream(out);
    final int cutLength = this.repositoryRoot.toString().length() + 1;

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

        @Override/*from ww  w  .  ja v  a  2s  .  com*/
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            if (dir.endsWith(".git")) {
                return FileVisitResult.SKIP_SUBTREE;
            } else {
                return FileVisitResult.CONTINUE;
            }
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            String name = file.toString().substring(cutLength);
            ZipEntry ze = new ZipEntry(name);
            try {
                ze.setTime(Files.getLastModifiedTime(file).toMillis());
                ze.setSize(Files.size(file));
                zout.putNextEntry(ze);
                Files.copy(file, zout);
                zout.closeEntry();
            } catch (IOException e) {
                FilebasedRepository.logger.debug(e.getMessage());
            }
            return FileVisitResult.CONTINUE;
        }
    });
    zout.close();
}

From source file:org.apache.openaz.xacml.std.pap.StdEngine.java

@Override
public void removeGroup(PDPGroup group, PDPGroup newGroup) throws PAPException, NullPointerException {
    if (group == null) {
        throw new NullPointerException();
    }/*from   www  .ja  va  2  s  . co  m*/
    //
    // Does this group exist?
    //
    if (!this.groups.contains(group)) {
        logger.error("This group doesn't exist.");
        throw new PAPException("The group '" + group.getId() + "' does not exist");
    }
    //
    // Is it the default group?
    //
    if (group.isDefaultGroup()) {
        throw new PAPException("You cannot delete the default group.");
    }
    Set<PDP> pdps = group.getPdps();
    //
    // Are there PDPs? If so, then we need a target group
    //
    if (!pdps.isEmpty() && newGroup == null) {
        throw new NullPointerException(
                "Group targeted for deletion has PDPs, you must provide a new group for them.");
    }
    //
    // Move the PDPs
    //
    if (!pdps.isEmpty()) {
        if (!(newGroup instanceof StdPDPGroup)) {
            throw new PAPException("Unexpected class for newGroup: " + newGroup.getClass().getCanonicalName());
        }
        // The movePDP function will modify the set of PDPs in the group.
        // To avoid concurrent modification exceptions we need to duplicate the list before calling that
        // function.
        List<PDP> pdpList = new ArrayList<PDP>();
        for (PDP pdp : pdps) {
            pdpList.add(pdp);
        }
        // now we can use the PDPs from the list without having ConcurrentAccessExceptions
        for (PDP pdp : pdpList) {
            this.movePDP(pdp, newGroup);
        }
    }
    //
    // remove the directory for the group
    //
    String id = group.getId();
    Path groupPath = Paths.get(this.repository.toString(), id);
    //
    // If it exists already
    //
    if (!Files.exists(groupPath)) {
        logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString());
    } else {
        try {
            Files.walkFileTree(groupPath, new SimpleFileVisitor<Path>() {

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

            });
            //
            // delete the directory
            //
            Files.delete(groupPath);
        } catch (IOException e) {
            logger.error("Failed to delete " + groupPath + ": " + e);
            throw new PAPException("Failed to delete " + id);
        }
    }

    // remove the group from the set of all groups
    groups.remove(group);

    //
    // Save changes
    //
    changed();
    this.doSave();
}

From source file:com.payex.utils.formatter.FormatExecutor.java

public void execute(String path) {
    Path startingDir = Paths.get(path);
    FormatExecutorRecursive pf = new FormatExecutorRecursive(this);
    try {/*from ww  w  .  j a  v  a 2 s  .c  om*/
        log.debug("Will recurse into " + path);
        Files.walkFileTree(startingDir, pf);
        pf.finalize();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.aol.advertising.qiao.injector.PatternMatchFileInjector.java

/**
 * Find a file matching with the defined pattern from the source directory.
 *
 * @return//from   w  w w  .ja  v a  2s  .co  m
 * @throws IOException
 */
private Path getNextFile() throws IOException {
    if (matchedFileSet.size() == 0) {
        finder.reset();
        Files.walkFileTree(srcDirPath, finder);
        List<Path> files = finder.getMatchedFiles();
        for (Path f : files) {
            if (logger.isDebugEnabled())
                logger.debug("found " + f.toString());
            matchedFileSet.add(f);
        }
    }

    if (matchedFileSet.size() > 0) {
        Path ans = null;
        Iterator<Path> it = matchedFileSet.iterator();
        if (it.hasNext()) {
            ans = it.next();
            it.remove();
        }

        return ans;
    }

    return null;
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Called every hour to clean up the batch job "[jobName]/execution" folders for expired files
 *//*ww  w.j a v  a  2s .c  om*/
@Schedule(persistent = false, second = "30", minute = "42", hour = "*/1")
protected void cleanUpExpiredBatchJobFiles() {

    long t0 = System.currentTimeMillis();

    // Resolve the list of batch job "execution" folders
    List<Path> executionFolders = getBatchJobSubFolders("execution");

    // Compute the expiry time
    Calendar expiryDate = Calendar.getInstance();
    expiryDate.add(Calendar.DATE, -batchFileExpiryDays);

    // Clean up the files
    executionFolders.forEach(folder -> {
        try {
            Files.walkFileTree(folder, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    if (isDirEmpty(dir)) {
                        log.debug("Deleting batch job directory :" + dir);
                        Files.delete(dir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (FileUtils.isFileOlder(file.toFile(), expiryDate.getTime())) {
                        log.debug("Deleting batch job file      :" + file);
                        Files.delete(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            log.error("Failed cleaning up " + folder + " batch job directory: " + e.getMessage(), e);
        }
    });

    log.debug(String.format("Cleaned up expired batch job files in %d ms", System.currentTimeMillis() - t0));
}

From source file:com.upplication.s3fs.util.AmazonS3ClientMock.java

private Path find(String bucketName, final String key) {
    final Path bucket = find(bucketName);
    if (bucket == null || !Files.exists(bucket)) {
        return null;
    }//w ww  . j  a v a  2 s.c  o  m
    try {
        final String fileKey = key.replaceAll("/", "%2F");
        final List<Path> matches = new ArrayList<Path>();
        Files.walkFileTree(bucket, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                String relativize = bucket.relativize(dir).toString();
                if (relativize.equals(fileKey)) {
                    matches.add(dir);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String relativize = bucket.relativize(file).toString();
                if (relativize.equals(fileKey)) {
                    matches.add(file);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        if (!matches.isEmpty())
            return matches.iterator().next();
    } catch (IOException e) {
        throw new AmazonServiceException("Problem getting mock S3Element: ", e);
    }

    return null;
}

From source file:org.hawk.orientdb.OrientDatabase.java

private static void deleteRecursively(File f) throws IOException {
    if (!f.exists())
        return;/*www  . j a v  a 2 s .  co m*/

    Files.walkFileTree(f.toPath(), 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 {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

    });
}