Example usage for java.nio.file Files newDirectoryStream

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

Introduction

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

Prototype

public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException 

Source Link

Document

Opens a directory, returning a DirectoryStream to iterate over all entries in the directory.

Usage

From source file:org.osiam.OsiamHome.java

/**
 * Inspired by http://stackoverflow.com/a/5937917/3171122
 *///from  w  w  w. j  a va  2s . c o m
private boolean isEmpty(Path directory) throws IOException {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        return !directoryStream.iterator().hasNext();
    }
}

From source file:org.carcv.impl.core.io.FFMPEGVideoHandlerIT.java

/**
 * Test method for//from   w  w  w.j a v  a  2s. c o m
 * {@link org.carcv.impl.core.io.FFMPEGVideoHandler#splitIntoFrames(java.nio.file.Path, int, java.nio.file.Path)}.
 *
 * @throws IOException
 */
@Test
public void testSplitIntoFramesPathIntPath() throws IOException {
    FFMPEGVideoHandler fvh = new FFMPEGVideoHandler();
    FFMPEGVideoHandler.copyCarImagesToDir(entry.getCarImages(), videoDir);
    Path video = fvh.generateVideo(videoDir, FFMPEGVideoHandler.defaultFrameRate);

    Path dir = Paths.get(video.toString() + ".custom_dir");
    assertTrue("Split failed.", fvh.splitIntoFrames(video, FFMPEGVideoHandler.defaultFrameRate, dir));

    DirectoryStream<Path> paths = Files.newDirectoryStream(dir);
    int counter = 0;
    for (@SuppressWarnings("unused")
    Path p : paths) {
        counter++;
    }
    assertEquals(entry.getCarImages().size(), counter);

    Files.delete(video);
    DirectoryWatcher.deleteDirectory(dir);
}

From source file:com.spankingrpgs.util.LoadStateUtils.java

/**
 * Given a Loader, and a path to data files, loads the data from the files into the game using the loader.
 *
 * @param loader  The loader to use to load data into the game
 * @param dataPath  The path containing the files containing the data to load
 * @param fileGlob  A glob that describes the kinds of files to load
 * @param newLineMarker  The String to use to represent new lines
 *//* w  ww. j  a  v  a 2 s. c o  m*/
public static void loadData(Loader loader, Path dataPath, String fileGlob, String newLineMarker) {
    LOG.info(String.format("Loading %s", dataPath));
    try {
        PathMatcher jsonMatcher = FileSystems.getDefault().getPathMatcher(fileGlob);
        Collection<String> data = StreamSupport.stream(Files.newDirectoryStream(dataPath).spliterator(), false)
                .peek(path -> LOG.fine(String.format("Loading data from %s", path)))
                .filter(jsonMatcher::matches).map((Path path) -> {
                    try {
                        return String.join(newLineMarker, Files.readAllLines(path));
                    } catch (IOException e) {
                        String msg = String.format("Problem reading file: %s", path);
                        LOG.log(Level.SEVERE, String.format("%s with exception:%s", msg, e), e);
                        throw new RuntimeException(msg);
                    }
                }).collect(Collectors.toList());
        loader.load(data, GameState.getCleanInstance());
    } catch (IOException exception) {
        String msg = String.format("Problem reading files in: %s", dataPath);
        LOG.log(Level.SEVERE, String.format("%s with exception: %s", msg, exception), exception);
        throw new RuntimeException(msg);
    }
}

From source file:org.esa.snap.engine_utilities.util.ZipUtils.java

public static void zipFolder(final Path directory, final File outputZipFile) throws IOException {

    try (ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream(outputZipFile))) {

        // traverse every file in the selected directory and add them
        // to the zip file by calling addToZipFile(..)
        DirectoryStream<Path> dirStream = Files.newDirectoryStream(directory);
        dirStream.forEach(path -> addToZipFile(path.toFile(), zipStream));
    } catch (IOException e) {
        throw e;//ww w  .  ja  va 2 s  . co  m
    }
}

From source file:pinterestbackup.PINDownloader.java

private void populateFileMap(Path pathDir) {
    //Read all file in pathDir and store in the local hashmap
    this.localFiles.clear();

    if (pathDir != null) {
        try {//from   ww w . j  av a 2 s  .  c o m
            DirectoryStream<Path> stream = Files.newDirectoryStream(pathDir);
            for (Path path : stream) {
                this.localFiles.put(path.toString(), Boolean.FALSE);
            }
        } catch (IOException ex) {
            Logger.getLogger(PinterestBackup.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.opennms.features.topology.plugins.topo.graphml.GraphMLEdgeStatusProvider.java

@Override
public Map<EdgeRef, Status> getStatusForEdges(EdgeProvider edgeProvider, Collection<EdgeRef> edges,
        Criteria[] criteria) {/*from  ww w  . jav  a2  s  .  c  o  m*/
    final List<StatusScript> scripts = Lists.newArrayList();
    try (final DirectoryStream<Path> stream = Files.newDirectoryStream(getScriptPath())) {
        for (final Path path : stream) {
            final String extension = FilenameUtils.getExtension(path.toString());
            final ScriptEngine scriptEngine = this.scriptEngineManager.getEngineByExtension(extension);
            if (scriptEngine == null) {
                LOG.warn("No script engine found for extension '{}'", extension);
                continue;
            }
            LOG.debug("Found script: path={}, extension={}, engine={}", path, extension, scriptEngine);
            try (final Stream<String> lines = Files.lines(path, Charset.defaultCharset())) {
                final String source = lines.collect(Collectors.joining("\n"));
                scripts.add(new StatusScript(scriptEngine, source));
            }
        }
    } catch (final IOException e) {
        LOG.error("Failed to walk template directory: {}", getScriptPath());
        return Collections.emptyMap();
    }

    return serviceAccessor.getTransactionOperations()
            .execute(transactionStatus -> edges.stream().filter(eachEdge -> eachEdge instanceof GraphMLEdge)
                    .map(edge -> (GraphMLEdge) edge)
                    .map(edge -> new HashMap.SimpleEntry<>(edge, computeEdgeStatus(scripts, edge)))
                    .filter(e -> e.getValue() != null)
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
}

From source file:company.gonapps.loghut.dao.TagDao.java

public List<String> getMonths(String tagName, int year) throws IOException {
    List<String> months = new LinkedList<>();
    rrwl.readLock().lock();//from  ww w .j  av  a2  s . co m
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get(
            settingDao.getSetting("tags.directory") + "/" + tagName + "/" + String.format("%04d", year)))) {

        for (Path path : ds) {
            Matcher matcher = tagMonthPattern.matcher(path.toString());
            if (matcher.find() && path.toFile().isDirectory())
                months.add(matcher.group(1));
        }
    }
    rrwl.readLock().unlock();
    Collections.sort(months, new MonthComparator());
    return months;
}

From source file:org.fao.geonet.kernel.harvest.harvester.localfilesystem.LocalFilesystemHarvester.java

/**
 * Aligns new results from filesystem harvesting. Contrary to practice in e.g. CSW Harvesting,
 * files removed from the harvesting source are NOT removed from the database. Also, no checks
 * on modification date are done; the result gets inserted or replaced if the result appears to
 * be in a supported schema./*from w  ww  .  jav  a 2s  .  co  m*/
 *
 * @param root the directory to visit
 */
private HarvestResult align(Path root) throws Exception {
    log.debug("Start of alignment for : " + params.getName());
    final LocalFsHarvesterFileVisitor visitor = new LocalFsHarvesterFileVisitor(cancelMonitor, context, params,
            this, log);
    if (params.recurse) {
        Files.walkFileTree(root, visitor);
    } else {
        try (DirectoryStream<Path> paths = Files.newDirectoryStream(root)) {
            for (Path path : paths) {
                if (path != null && Files.isRegularFile(path)) {
                    visitor.visitFile(path, Files.readAttributes(path, BasicFileAttributes.class));
                }
            }
        }
    }
    result = visitor.getResult();
    log.debug(String.format("Scan directory is done. %d files analyzed.", result.totalMetadata));
    Set<Integer> idsForHarvestingResult = visitor.getListOfRecords();
    Set<Integer> idsResultHs = Sets.newHashSet(idsForHarvestingResult);

    if (!params.nodelete) {
        log.debug("Starting to delete locally existing metadata " + "from the same source if they "
                + " were not in this harvesting result...");
        List<Integer> existingMetadata = context.getBean(MetadataRepository.class)
                .findAllIdsBy(MetadataSpecs.hasHarvesterUuid(params.getUuid()));
        for (Integer existingId : existingMetadata) {

            if (cancelMonitor.get()) {
                return this.result;
            }
            if (!idsResultHs.contains(existingId)) {
                log.debug("  Removing: " + existingId);
                dataMan.deleteMetadata(context, existingId.toString());
                result.locallyRemoved++;
            }
        }
    }

    log.debug("Starting indexing in batch thread pool...");

    List<Integer> listOfRecordsToIndex = Lists.newArrayList(visitor.getListOfRecordsToIndex());
    log.debug(String.format("Starting indexing in batch thread pool of %d updated records ...",
            listOfRecordsToIndex.size()));
    dataMan.batchIndexInThreadPool(context, listOfRecordsToIndex);

    log.debug("End of alignment for : " + params.getName());
    return result;
}

From source file:cc.kave.commons.pointsto.evaluation.ProjectTrainValidateEvaluation.java

private List<ProjectUsageStore> getUsageStores(Path dir) throws IOException {
    List<ProjectUsageStore> stores = new ArrayList<>();
    try (DirectoryStream<Path> dirStream = Files.newDirectoryStream(dir)) {
        for (Path storeDir : dirStream) {
            if (Files.isDirectory(storeDir)) {
                stores.add(new ProjectUsageStore(storeDir));
            }//from w w  w.  ja v a2s .c om
        }
    }

    return stores;
}

From source file:org.tinymediamanager.core.movie.MovieExporter.java

/**
 * exports movie list according to template file.
 * //from ww w .  ja va  2  s  .c o m
 * @param moviesToExport
 *          list of movies
 * @param exportDir
 *          the path to export
 * @throws Exception
 *           the exception
 */
@Override
public <T extends MediaEntity> void export(List<T> moviesToExport, Path exportDir) throws Exception {
    LOGGER.info("preparing movie export; using " + properties.getProperty("name"));

    // register own renderers
    engine.registerNamedRenderer(new NamedDateRenderer());
    engine.registerNamedRenderer(new MovieFilenameRenderer());
    engine.registerNamedRenderer(new ArtworkCopyRenderer(exportDir));

    // prepare export destination
    if (!Files.exists(exportDir)) {
        try {
            Files.createDirectories(exportDir);
        } catch (Exception e) {
            throw new Exception("error creating export directory");
        }
    }

    // prepare listfile
    Path listExportFile = null;
    if (fileExtension.equalsIgnoreCase("html")) {
        listExportFile = exportDir.resolve("index.html");
    }
    if (fileExtension.equalsIgnoreCase("xml")) {
        listExportFile = exportDir.resolve("movielist.xml");
    }
    if (fileExtension.equalsIgnoreCase("csv")) {
        listExportFile = exportDir.resolve("movielist.csv");
    }
    if (listExportFile == null) {
        throw new Exception("error creating movie list file");
    }

    // create list
    LOGGER.info("generating movie list");
    Utils.deleteFileSafely(listExportFile);

    Map<String, Object> root = new HashMap<>();
    root.put("movies", new ArrayList<>(moviesToExport));

    String output = engine.transform(listTemplate, root);

    Utils.writeStringToFile(listExportFile, output);
    LOGGER.info("movie list generated: " + listExportFile);

    // create details for
    if (StringUtils.isNotBlank(detailTemplate)) {
        Path detailsDir = exportDir.resolve("movies");
        if (Files.isDirectory(detailsDir)) {
            Utils.deleteDirectoryRecursive(detailsDir);
        }
        Files.createDirectory(detailsDir);

        for (MediaEntity me : moviesToExport) {
            Movie movie = (Movie) me;
            LOGGER.debug("processing movie " + movie.getTitle());
            // get preferred movie name like set up in movie renamer
            String detailFilename = MovieRenamer.createDestinationForFilename(
                    MovieModuleManager.MOVIE_SETTINGS.getMovieRenamerFilename(), movie);
            if (StringUtils.isBlank(detailFilename)) {
                detailFilename = movie.getVideoBasenameWithoutStacking();
                // FilenameUtils.getBaseName(Utils.cleanStackingMarkers(movie.getMediaFiles(MediaFileType.VIDEO).get(0).getFilename()));
            }
            Path detailsExportFile = detailsDir.resolve(detailFilename + "." + fileExtension);

            root = new HashMap<>();
            root.put("movie", movie);

            output = engine.transform(detailTemplate, root);
            Utils.writeStringToFile(detailsExportFile, output);

        }

        LOGGER.info("movie detail pages generated: " + exportDir);
    }

    // copy all non .jtme/template.conf files to destination dir
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(templateDir)) {
        for (Path path : directoryStream) {
            if (Utils.isRegularFile(path)) {
                if (path.getFileName().toString().endsWith(".jmte")
                        || path.getFileName().toString().endsWith("template.conf")) {
                    continue;
                }
                Files.copy(path, exportDir.resolve(path.getFileName()), StandardCopyOption.REPLACE_EXISTING);
            } else if (Files.isDirectory(path)) {
                Utils.copyDirectoryRecursive(path, exportDir.resolve(path.getFileName()));
            }
        }
    } catch (IOException ex) {
        LOGGER.error("could not copy resources: ", ex);
    }
}