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.corehunter.tests.data.simple.SimpleBiAllelicGenotypeDataTest.java

@Test
public void erroneousFiles() throws IOException {
    System.out.println(" |- Test erroneous files:");
    Path dir = Paths.get(SimpleBiAllelicGenotypeDataTest.class.getResource(ERRONEOUS_FILES_DIR).getPath());
    try (DirectoryStream<Path> directory = Files.newDirectoryStream(dir)) {
        for (Path file : directory) {
            System.out.print("  |- " + file.getFileName().toString() + ": ");
            FileType type = file.toString().endsWith(".txt") ? FileType.TXT : FileType.CSV;
            boolean thrown = false;
            try {
                SimpleBiAllelicGenotypeData.readData(file, type);
            } catch (IOException ex) {
                thrown = true;/* w  w w.  j  a v a2s  . co  m*/
                System.out.print(ex.getMessage());
            } finally {
                System.out.println();
            }
            assertTrue("File " + file + " should throw exception.", thrown);
        }
    }
}

From source file:org.roda.core.migration.MigrationManager.java

private List<String> getSolrCollections(Path indexConfigsFolder) {
    List<String> solrCollections = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(indexConfigsFolder)) {
        stream.forEach(e -> {//from  w  w w  .j  a v  a  2  s.c  o  m
            if (FSUtils.isDirectory(e)) {
                solrCollections.add(e.getFileName().toString());
            }
        });
    } catch (IOException e) {
        // do nothing
    }
    return solrCollections;
}

From source file:org.wso2.carbon.apimgt.rest.api.admin.utils.FileBasedApplicationImportExportManager.java

/**
 * Queries the list of directories available under a root directory path
 *
 * @param path full path of the root directory
 * @return Set of directory path under the root directory given by path
 * @throws IOException if an error occurs while listing directories
 *///  w  w  w  .j av  a2 s .c  om
private Set<String> getDirectoryList(String path) throws IOException {
    Set<String> directoryNames = new HashSet<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(path))) {
        for (Path directoryPath : directoryStream) {
            directoryNames.add(directoryPath.toString());
        }
    }
    return directoryNames;
}

From source file:at.tfr.securefs.ui.CopyFilesServiceBean.java

private Path validateToPath(String toPathName, ProcessFilesData pfd) throws IOException {
    Path to = Paths.get(toPathName);
    if (Files.exists(to, LinkOption.NOFOLLOW_LINKS)) {
        if (Files.isSameFile(to, Paths.get(pfd.getFromRootPath()))) {
            throw new IOException("Path " + to + " may not be same as FromPath: " + pfd.getFromRootPath());
        }//from w  ww. j av a 2 s  . co m
        if (!Files.isDirectory(to, LinkOption.NOFOLLOW_LINKS)) {
            throw new IOException("Path " + to + " is no directory");
        }
        if (!Files.isWritable(to)) {
            throw new IOException("Path " + to + " is not writable");
        }
        if (!Files.isExecutable(to)) {
            throw new IOException("Path " + to + " is not executable");
        }
        if (!pfd.isAllowOverwriteExisting()) {
            if (Files.newDirectoryStream(to).iterator().hasNext()) {
                throw new IOException("Path " + to + " is not empty, delete content copy.");
            }
        }
    }
    return to;
}

From source file:com.cinchapi.concourse.server.plugin.PluginManager.java

/**
 * Get all the {@link Plugin plugins} in the {@code bundle} and
 * {@link #launch(String, Path, Class, List) launch} them each in a separate
 * JVM.//from   w w  w .  j a  va2  s . co m
 * 
 * @param bundle the path to a bundle directory, which is a sub-directory of
 *            the {@link #home} directory.
 * @param runAfterInstallHook a flag that indicates whether the
 *            {@link Plugin#afterInstall()} hook should be run
 */
protected void activate(String bundle, boolean runAfterInstallHook) {
    try {
        String lib = home + File.separator + bundle + File.separator + "lib" + File.separator;
        Path prefs = Paths.get(home, bundle, PluginConfiguration.PLUGIN_PREFS_FILENAME);
        Iterator<Path> content = Files.newDirectoryStream(Paths.get(lib)).iterator();

        // Go through all the jars in the plugin's lib directory and compile
        // the appropriate classpath while identifying jars that might
        // contain plugin endpoints.
        List<URL> urls = Lists.newArrayList();
        List<String> classpath = Lists.newArrayList();
        while (content.hasNext()) {
            String filename = content.next().getFileName().toString();
            URL url = new File(lib + filename).toURI().toURL();
            if (!SYSTEM_JARS.contains(filename)) {
                // NOTE: by checking for exact name matches, we will
                // accidentally include system jars that contain different
                // versions.
                urls.add(url);
            }
            classpath.add(url.getFile());
        }

        // Create a ClassLoader that only contains jars with possible plugin
        // endpoints and search for any applicable classes.
        URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0]), null);
        Class parent = loader.loadClass(Plugin.class.getName());
        Class realTimeParent = loader.loadClass(RealTimePlugin.class.getName());
        Reflections reflection = new Reflections(new ConfigurationBuilder().addClassLoader(loader)
                .addUrls(ClasspathHelper.forClassLoader(loader)));
        Set<Class<?>> plugins = reflection.getSubTypesOf(parent);
        for (final Class<?> plugin : plugins) {
            if (runAfterInstallHook) {
                Object instance = Reflection.newInstance(plugin);
                Reflection.call(instance, "afterInstall");
            }
            launch(bundle, prefs, plugin, classpath);
            startEventLoop(plugin.getName());
            if (realTimeParent.isAssignableFrom(plugin)) {
                initRealTimeStream(plugin.getName());
            }
        }

    } catch (IOException | ClassNotFoundException e) {
        Logger.error("An error occurred while trying to activate the plugin bundle '{}'", bundle, e);
        throw Throwables.propagate(e);
    }
}

From source file:org.roda.core.plugins.plugins.base.InventoryReportPlugin.java

@Override
public Report afterAllExecute(IndexService index, ModelService model, StorageService storage)
        throws PluginException {
    CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator("\n");
    Path csvTempFolder = getJobCSVTempFolder();

    if (csvTempFolder != null) {
        List<Path> partials = new ArrayList<>();
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(csvTempFolder);
                FileWriter fileWriter = new FileWriter(output.toFile());
                CSVPrinter csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);) {
            if (enableHeaders) {
                csvFilePrinter.printRecord(fields);
            }//  ww  w .  ja v  a 2  s.  co m
            for (Path path : directoryStream) {
                partials.add(path);
            }
        } catch (IOException e) {
            LOGGER.error("Error while merging partial CSVs", e);
        }
        try {
            InventoryReportPluginUtils.mergeFiles(partials, output);
            FSUtils.deletePathQuietly(csvTempFolder);
        } catch (IOException e) {
            LOGGER.error("Error while merging partial CSVs", e);
        }
    }
    return new Report();
}

From source file:org.corehunter.tests.data.simple.SimpleFrequencyGenotypeDataTest.java

@Test
public void erroneousFiles() throws IOException {
    System.out.println(" |- Test erroneous files:");
    Path dir = Paths.get(SimpleFrequencyGenotypeDataTest.class.getResource(ERRONEOUS_FILES_DIR).getPath());
    try (DirectoryStream<Path> directory = Files.newDirectoryStream(dir)) {
        for (Path file : directory) {
            System.out.print("  |- " + file.getFileName().toString() + ": ");
            FileType type = file.toString().endsWith(".txt") ? FileType.TXT : FileType.CSV;
            boolean thrown = false;
            try {
                SimpleFrequencyGenotypeData.readData(file, type);
            } catch (IOException ex) {
                thrown = true;//from w  w  w .  jav  a 2 s .c o m
                System.out.print(ex.getMessage());
            } finally {
                System.out.println();
            }
            assertTrue("File " + file + " should throw exception.", thrown);
        }
    }
}

From source file:org.structr.rest.resource.LogResource.java

private void collectFilesAndStore(final Context context, final Path dir, final int level)
        throws FrameworkException {

    if (level == 1) {
        logger.log(Level.INFO, "Path {0}", dir);
    }//from   w w w  .j a va 2s .co  m

    try (final DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {

        for (final Path p : stream) {

            if (Files.isDirectory(p)) {

                collectFilesAndStore(context, p, level + 1);

            } else {

                context.update(storeLogEntry(p));

                // update object count and commit
                context.commit(true);
            }

            Files.delete(p);

        }

    } catch (IOException ioex) {
        ioex.printStackTrace();
    }
}

From source file:org.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

private List<Path> listPaths(Path dir) throws IOException {
    List<Path> result = new ArrayList<>();
    if (Files.exists(dir)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path entry : stream) {
                result.add(entry);//w  w  w. ja  v a 2s  .c  o  m
            }
        } catch (DirectoryIteratorException ex) {
            // I/O error encounted during the iteration, the cause is an IOException
            throw ex.getCause();
        }
    }
    return result;
}

From source file:org.tinymediamanager.core.tvshow.TvShowRenamer.java

private static void cleanEmptyDir(Path dir) {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
        if (!directoryStream.iterator().hasNext()) {
            // no iterator = empty
            LOGGER.debug("Deleting empty Directory " + dir);
            Files.delete(dir); // do not use recursive her
            return;
        }//from ww w. j  a v  a  2s  .c o  m
    } catch (IOException ex) {
    }

    // FIXME: recursive backward delete?! why?!
    // if (Files.isDirectory(dir)) {
    // cleanEmptyDir(dir.getParent());
    // }
}