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, DirectoryStream.Filter<? super Path> filter)
        throws IOException 

Source Link

Document

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

Usage

From source file:org.lamport.tla.toolbox.jcloud.PayloadHelper.java

public static Payload appendModel2Jar(final Path modelPath, String mainClass, Properties properties,
        IProgressMonitor monitor) throws IOException {

    /*/*from w  w w  .  j a va  2  s .c  o  m*/
     * Get the standard tla2tools.jar from the classpath as a blueprint.
     * It's located in the org.lamport.tla.toolbox.jclouds bundle in the
     * files/ directory. It uses OSGi functionality to read files/tla2tools.jar
     * from the .jclouds bundle.
     * The copy of the blueprint will contain the spec & model and 
     * additional metadata (properties, amended manifest).
     */
    final Bundle bundle = FrameworkUtil.getBundle(PayloadHelper.class);
    final URL toolsURL = bundle.getEntry("files/tla2tools.jar");
    if (toolsURL == null) {
        throw new RuntimeException("No tlatools.jar and/or spec to deploy");
    }

    /* 
     * Copy the tla2tools.jar blueprint to a temporary location on
     * disk to append model files below.
     */
    final File tempFile = File.createTempFile("tla2tools", ".jar");
    tempFile.deleteOnExit();
    try (FileOutputStream out = new FileOutputStream(tempFile)) {
        IOUtils.copy(toolsURL.openStream(), out);
    }

    /*
     * Create a virtual filesystem in jar format.
     */
    final Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    final URI uri = URI.create("jar:" + tempFile.toURI());

    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        /*
         * Copy the spec and model into the jar's model/ folder.
         * Also copy any module override (.class file) into the jar.
         */
        try (DirectoryStream<Path> modelDirectoryStream = Files.newDirectoryStream(modelPath,
                "*.{cfg,tla,class}")) {
            for (final Path file : modelDirectoryStream) {
                final Path to = fs.getPath("/model/" + file.getFileName());
                Files.copy(file, to, StandardCopyOption.REPLACE_EXISTING);
            }
        }

        /*
         * Add given class as Main-Class statement to jar's manifest. This
         * causes Java to launch this class when no other Main class is 
         * given on the command line. Thus, it shortens the command line
         * for us.
         */
        final Path manifestPath = fs.getPath("/META-INF/", "MANIFEST.MF");
        final Manifest manifest = new Manifest(Files.newInputStream(manifestPath));
        manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, mainClass);
        final PipedOutputStream ps = new PipedOutputStream();
        final PipedInputStream is = new PipedInputStream(ps);
        manifest.write(ps);
        ps.close();
        Files.copy(is, manifestPath, StandardCopyOption.REPLACE_EXISTING);

        /*
         * Add properties file to archive. The property file contains the
         * result email address... from where TLC eventually reads it.
         */

        // On Windows 7 and above the file has to be created in the system's
        // temp folder. Otherwise except file creation to fail with a
        // AccessDeniedException
        final File f = File.createTempFile("generated", "properties");
        OutputStream out = new FileOutputStream(f);
        // Append all entries in "properties" to the temp file f
        properties.store(out, "This is an optional header comment string");
        // Copy the temp file f into the jar with path /model/generated.properties.
        final Path to = fs.getPath("/model/generated.properties");
        Files.copy(f.toPath(), to, StandardCopyOption.REPLACE_EXISTING);
    } catch (final IOException e1) {
        throw new RuntimeException("No model directory found to deploy", e1);
    }

    /*
     * Compress archive with pack200 to achieve a much higher compression rate. We
     * are going to send the file on the wire after all:
     * 
     * effort: take more time choosing codings for better compression segment: use
     * largest-possible archive segments (>10% better compression) mod time: smear
     * modification times to a single value deflate: ignore all JAR deflation hints
     * in original archive
     */
    final Packer packer = Pack200.newPacker();
    final Map<String, String> p = packer.properties();
    p.put(Packer.EFFORT, "9");
    p.put(Packer.SEGMENT_LIMIT, "-1");
    p.put(Packer.MODIFICATION_TIME, Packer.LATEST);
    p.put(Packer.DEFLATE_HINT, Packer.FALSE);

    // Do not reorder which changes package names. Pkg name changes e.g. break
    // SimpleFilenameToStream.
    p.put(Packer.KEEP_FILE_ORDER, Packer.TRUE);

    // Throw an error if any of the above attributes is unrecognized.
    p.put(Packer.UNKNOWN_ATTRIBUTE, Packer.ERROR);

    final File packTempFile = File.createTempFile("tla2tools", ".pack.gz");
    try (final JarFile jarFile = new JarFile(tempFile);
            final GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(packTempFile));) {
        packer.pack(jarFile, fos);
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to pack200 the tla2tools.jar file", ioe);
    }

    /*
     * Convert the customized tla2tools.jar into a jClouds payload object. This is
     * the format it will be transfered on the wire. This is handled by jClouds
     * though.
     */
    Payload jarPayLoad = null;
    try {
        final InputStream openStream = new FileInputStream(packTempFile);
        jarPayLoad = Payloads.newInputStreamPayload(openStream);
        // manually set length of content to prevent a NPE bug
        jarPayLoad.getContentMetadata().setContentLength(Long.valueOf(openStream.available()));
    } catch (final IOException e1) {
        throw new RuntimeException("No tlatools.jar to deploy", e1);
    } finally {
        monitor.worked(5);
    }

    return jarPayLoad;
}

From source file:ee.ria.xroad.signer.certmanager.FileBasedOcspCache.java

void reloadFromDisk() throws Exception {
    Path path = Paths.get(getOcspCachePath());

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, this::isOcspFile)) {
        for (Path entry : stream) {
            loadResponseFromFileIfNotExpired(entry.toFile(), new Date());
        }//  ww w.  j  ava 2  s . c o m
    }
}

From source file:org.kitodo.serviceloader.KitodoServiceLoader.java

/**
 * Loads bean classes and registers them to the FacesContext. Afterwards
 * they can be used in all frontend files
 *///ww w .j a  v a2 s . com
private void loadBeans() {
    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {

        for (Path f : stream) {
            try (JarFile jarFile = new JarFile(f.toString())) {

                if (hasFrontendFiles(jarFile)) {

                    Enumeration<JarEntry> e = jarFile.entries();

                    URL[] urls = { new URL("jar:file:" + f.toString() + "!/") };
                    try (URLClassLoader cl = URLClassLoader.newInstance(urls)) {
                        while (e.hasMoreElements()) {
                            JarEntry je = e.nextElement();

                            /*
                             * IMPORTANT: Naming convention: the name of the
                             * java class has to be in upper camel case or
                             * "pascal case" and must be equal to the file
                             * name of the corresponding facelet file
                             * concatenated with the word "Form".
                             *
                             * Example: template filename "sample.xhtml" =>
                             * "SampleForm.java"
                             *
                             * That is the reason for the following check
                             * (e.g. whether the JarEntry name ends with
                             * "Form.class")
                             */
                            if (je.isDirectory() || !je.getName().endsWith("Form.class")) {
                                continue;
                            }

                            String className = je.getName().substring(0, je.getName().length() - 6);
                            className = className.replace('/', '.');
                            Class c = cl.loadClass(className);

                            String beanName = className.substring(className.lastIndexOf('.') + 1).trim();

                            FacesContext facesContext = FacesContext.getCurrentInstance();
                            HttpSession session = (HttpSession) facesContext.getExternalContext()
                                    .getSession(false);

                            session.getServletContext().setAttribute(beanName, c.newInstance());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.error(ERROR, e.getMessage());
    }
}

From source file:org.roda.core.model.iterables.LogEntryFileSystemIterable.java

public LogEntryFileSystemIterable(Path logPath, Filter<? super Path> filter) throws IOException {
    this.directoryStream = Files.newDirectoryStream(logPath, filter);
}

From source file:net.fatlenny.datacitation.service.GitCitationDBService.java

@Override
public List<String> getDatasetNames() throws CitationDBException {
    checkoutBranch(REF_MASTER);/*  w  w  w.  j a va  2  s  .co  m*/

    List<String> databaseFileNames = new ArrayList<>();
    String workingTreeDir = getWorkingTreeDir();

    try (DirectoryStream<Path> ds = Files.newDirectoryStream(Paths.get(workingTreeDir), "*." + CSV_ENDING)) {
        for (Path path : ds) {
            String pathName = path.getFileName().toString();
            databaseFileNames.add(pathName.substring(0, pathName.lastIndexOf(".")));
        }
    } catch (IOException e) {
        throw new CitationDBException("Error reading data files: ", e);
    }

    return databaseFileNames;
}

From source file:org.apache.pulsar.functions.utils.io.ConnectorUtils.java

public static Connectors searchForConnectors(String connectorsDirectory) throws IOException {
    Path path = Paths.get(connectorsDirectory).toAbsolutePath();
    log.info("Searching for connectors in {}", path);

    Connectors connectors = new Connectors();

    if (!path.toFile().exists()) {
        log.warn("Connectors archive directory not found");
        return connectors;
    }/*  www. j  a  v  a2 s  .c  om*/

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "*.nar")) {
        for (Path archive : stream) {
            try {
                ConnectorDefinition cntDef = ConnectorUtils.getConnectorDefinition(archive.toString());
                log.info("Found connector {} from {}", cntDef, archive);

                if (!StringUtils.isEmpty(cntDef.getSourceClass())) {
                    connectors.sources.put(cntDef.getName(), archive);
                }

                if (!StringUtils.isEmpty(cntDef.getSinkClass())) {
                    connectors.sinks.put(cntDef.getName(), archive);
                }

                connectors.connectors.add(cntDef);
            } catch (Throwable t) {
                log.warn("Failed to load connector from {}", archive, t);
            }
        }
    }

    Collections.sort(connectors.connectors,
            (c1, c2) -> String.CASE_INSENSITIVE_ORDER.compare(c1.getName(), c2.getName()));

    return connectors;
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.RDFFilesLoader.java

/**
 * Find the paths to RDF files in this directory. Sub-directories, hidden
 * files, and markdown files are ignored.
 *//*from  www.  j  a va  2s.co m*/
private static Set<Path> getPaths(String parentDir, String... strings) {
    Path dir = Paths.get(parentDir, strings);

    Set<Path> paths = new TreeSet<>();
    if (Files.isDirectory(dir)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, RDF_FILE_FILTER)) {
            for (Path p : stream) {
                paths.add(p);
            }
        } catch (IOException e) {
            log.warn("Failed to read directory '" + dir + "'", e);
        }
    } else {
        log.debug("Directory '" + dir + "' doesn't exist.");
    }
    log.debug("Paths from '" + dir + "': " + paths);
    return paths;
}

From source file:org.onehippo.cms7.essentials.dashboard.utils.JavaSourceUtilsTest.java

@Test
public void testJcrType() throws Exception {
    final Path startDirectory = getContext().getBeansPackagePath();
    Collection<String> myTypes = new ArrayList<>();
    final List<Path> directories = new ArrayList<>();
    GlobalUtils.populateDirectories(startDirectory, directories);
    final String pattern = "*." + "txt";
    for (Path directory : directories) {
        try (final DirectoryStream<Path> stream = Files.newDirectoryStream(directory, pattern)) {
            for (Path myPath : stream) {
                final String nodeJcrType = JavaSourceUtils.getNodeJcrType(myPath);
                myTypes.add(nodeJcrType);
            }//from w  ww .j a  v  a 2 s  .  com

        } catch (IOException e) {
            log.error("Error reading java files", e);
        }
    }
    assertTrue(myTypes.size() <= NAMESPACES_TEST_SET.size());
    for (String namespace : NAMESPACES_TEST_SET) {
        if (namespace.contains("extend")) {
            continue;
        }
        assertTrue(myTypes.contains(namespace));
    }

}

From source file:io.ecarf.core.utils.UsageParser.java

public UsageParser(String folder) throws Exception {

    super();//from www . j a  v a  2s . c o  m

    boolean remote = folder.startsWith(GoogleMetaData.CLOUD_STORAGE_PREFIX);

    if (remote) {

        String bucket = StringUtils.remove(folder, GoogleMetaData.CLOUD_STORAGE_PREFIX);
        this.setUp();
        List<StorageObject> objects = this.service.listCloudStorageObjects(bucket);

        for (StorageObject object : objects) {
            String name = object.getName();
            if (name.endsWith(Constants.DOT_LOG)) {
                String localFile = FilenameUtils.getLocalFilePath(name);

                service.downloadObjectFromCloudStorage(name, localFile, bucket);

                this.files.add(localFile);
            }
        }

    } else {
        // local file
        DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
            public boolean accept(Path file) throws IOException {

                String filename = file.toString();
                return filename.contains(USAGE_PREFIX);
            }
        };

        Path dir = Paths.get(folder);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
            for (Path path : stream) {
                this.files.add(path.toString());
            }
        }
    }
}

From source file:org.mousephenotype.dcc.exportlibrary.fullTraverser.FullTraverserTest.java

private static SubmissionSet loadData(long trackerID, Calendar submissionDate)
        throws JAXBException, IOException {
    logger.info("one {}", System.getProperty("one"));
    logger.info("two {}", System.getProperty("two"));
    logger.info("three {}", System.getProperty("three"));
    logger.info("four {}", System.getProperty("four"));
    logger.info("five {}", System.getProperty("five"));
    logger.info("six {}", System.getProperty("six"));

    SubmissionSet submissionset = new SubmissionSet();
    Submission submission = new Submission();
    submissionset.getSubmission().add(submission);
    submission.setTrackerID(trackerID);//from w w w  . jav a 2  s .co  m
    submission.setSubmissionDate(submissionDate);

    if (new File(System.getProperty("six") + File.separator + experimentsFilename).exists()) {
        logger.info("file can be loaded");
    } else {
        logger.info("cannot");
    }

    if (new File(experimentsFilename).exists()) {
        logger.info("file can be loaded");
    } else {
        logger.info("cannot");
    }

    Path dir = Paths.get(System.getProperty("six") + "/data");
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.*")) {
        for (Path entry : stream) {
            logger.info("{}", entry.getFileName());
        }
    } catch (IOException ex) {
        logger.error("damn it");
    }
    logger.info("loading file");
    //submission.setCentreProcedure(XMLUtils.unmarshal(contextPath, CentreProcedureSet.class,System.getProperty("thirdteen") + experimentsFilename).getCentre());
    try {
        submission.setCentreProcedure(
                XMLUtils.unmarshal(contextPath, CentreProcedureSet.class, experimentsFilename).getCentre());
    } catch (JAXBException | IOException ex) {
        logger.error("only name does not work", ex);
    }
    try {
        submission.setCentreProcedure(XMLUtils.unmarshal(contextPath, CentreProcedureSet.class,
                System.getProperty("six") + File.separator + experimentsFilename).getCentre());
    } catch (JAXBException | IOException ex) {
        logger.error("project.build.testOutputDirectory does not work", ex);
    }

    logger.info("file loaded");
    return submissionset;
}