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.bimserver.tools.ifcloader.IfcLoader.java

private void createRecursive(Path baseDirectory, SProject parent, String mainProjectName, int nrChildren) {
    try {//from   w  w w.ja  va  2 s .  c  o  m
        if (Files.isDirectory(baseDirectory)) {
            SProject project = null;
            if (parent == null) {
                project = client.getServiceInterface().addProject(mainProjectName, "ifc2x3tc1");
            } else {
                project = client.getServiceInterface().addProjectAsSubProject(
                        baseDirectory.getFileName().toString(), parent.getOid(), "ifc2x3tc1");
            }
            List<Path> paths = new ArrayList<>();
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(baseDirectory)) {
                for (Path entry : stream) {
                    paths.add(entry);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (Path path : paths) {
                createRecursive(path, project, null, paths.size());
            }
        } else {
            SDeserializerPluginConfiguration deserializer = client.getServiceInterface()
                    .getSuggestedDeserializerForExtension("ifc", parent.getOid());
            if (nrChildren == 1) {
                try {
                    client.checkinSync(parent.getOid(), "Initial", deserializer.getOid(), false, baseDirectory);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                String folderName = baseDirectory.getFileName().toString();
                folderName = folderName.substring(0, folderName.lastIndexOf(".") - 1);
                SProject project = client.getServiceInterface().addProjectAsSubProject(folderName,
                        parent.getOid(), "ifc2x3tc1");
                try {
                    client.checkinSync(project.getOid(), "Initial", deserializer.getOid(), false,
                            baseDirectory);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (ServerException e) {
        e.printStackTrace();
    } catch (UserException e) {
        e.printStackTrace();
    } catch (PublicInterfaceNotFoundException e) {
        e.printStackTrace();
    }
}

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

public List<String> getTagNames() throws IOException {
    List<String> names = new LinkedList<>();
    Pattern pattern = Pattern.compile("/([^/]+)$");
    rrwl.readLock().lock();//from  w w w  . j a  v  a  2 s. com
    try (DirectoryStream<Path> ds = Files
            .newDirectoryStream(Paths.get(settingDao.getSetting("tags.directory")))) {
        for (Path path : ds) {
            Matcher matcher = pattern.matcher(path.toString());
            if (matcher.find() && Files.isDirectory(path))
                names.add(matcher.group(1));
        }
    } finally {
        rrwl.readLock().unlock();
    }
    return names;
}

From source file:ca.phon.plugins.praat.TextGridManager.java

/**
 * List available TextGrids for a given session.
 * /*from   w  w w . j  a v  a  2s .com*/
 * @param corpus
 * @param session
 * 
 * @return list of TextGrid files available
 */
public List<File> textGridFilesForSession(String corpus, String session) {
    List<File> retVal = new ArrayList<>();

    final Path textGridFolderPath = Paths.get(textGridFolder(corpus, session));
    if (Files.exists(textGridFolderPath)) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(textGridFolderPath)) {
            for (Path subFile : directoryStream) {
                if (subFile.getFileName().toString().endsWith(TEXTGRID_EXT)) {
                    retVal.add(subFile.toFile());
                }
            }
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

    return retVal;
}

From source file:org.carcv.web.beans.StorageBeanIT.java

/**
 * Test method for {@link org.carcv.web.beans.StorageBean#createBatchDirectory()}.
 *
 * @throws IOException//from  w  ww. j a va 2s  .  c  o  m
 */
@Test
public void testCreateBatchDirectory() throws IOException {
    Path p = storageBean.createBatchDirectory();
    assertFalse(DirectoryWatcher.isDirEmpty(storageBean.getInputDirectory()));
    DirectoryStream<Path> stream = Files.newDirectoryStream(storageBean.getInputDirectory());

    for (Path dir : stream) { // there should only be one directory, therefore the assertion should be true
        assertEquals(p, dir);
    }
}

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

/**
 * list all objects without and return ObjectListing with all elements
 * and with truncated to false/* ww w .j av  a 2 s . c o m*/
 */
@Override
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest) throws AmazonClientException {
    String bucketName = listObjectsRequest.getBucketName();
    String prefix = listObjectsRequest.getPrefix();
    String marker = listObjectsRequest.getMarker();
    String delimiter = listObjectsRequest.getDelimiter();

    ObjectListing objectListing = new ObjectListing();
    objectListing.setBucketName(bucketName);
    objectListing.setPrefix(prefix);
    objectListing.setMarker(marker);
    objectListing.setDelimiter(delimiter);

    final Path bucket = find(bucketName);
    final TreeMap<String, S3Element> elems = new TreeMap<>();
    try {
        for (Path elem : Files.newDirectoryStream(bucket)) {
            S3Element element = parse(elem, bucket);
            if (!elems.containsKey(element.getS3Object().getKey()))
                elems.put(element.getS3Object().getKey(), element);
        }
    } catch (IOException e) {
        throw new AmazonClientException(e);
    }
    Iterator<S3Element> iterator = elems.values().iterator();
    int i = 0;
    boolean waitForMarker = !StringUtils.isNullOrEmpty(marker);
    while (iterator.hasNext()) {
        S3Element elem = iterator.next();
        if (elem.getS3Object().getKey().equals("/"))
            continue;
        String key = elem.getS3Object().getKey();
        if (waitForMarker) {
            waitForMarker = !key.startsWith(marker);
            if (waitForMarker)
                continue;
        }

        if (prefix != null && key.startsWith(prefix)) {
            int beginIndex = key.indexOf(prefix) + prefix.length();
            String rest = key.substring(beginIndex);
            if (delimiter != null && delimiter.length() > 0 && rest.contains(delimiter)) {
                String substring = key.substring(0, beginIndex + rest.indexOf(delimiter));
                if (!objectListing.getCommonPrefixes().contains(substring))
                    objectListing.getCommonPrefixes().add(substring);
                continue;
            }
            S3ObjectSummary s3ObjectSummary = parseToS3ObjectSummary(elem);
            objectListing.getObjectSummaries().add(s3ObjectSummary);

            if (i + 1 == LIMIT_AWS_MAX_ELEMENTS && iterator.hasNext()) {
                objectListing.setTruncated(true);
                objectListing.setNextMarker(iterator.next().getS3Object().getKey());
                return objectListing;
            }
            objectListing.setTruncated(false);

            i++;
        }

    }
    Collections.sort(objectListing.getObjectSummaries(), new Comparator<S3ObjectSummary>() {
        @Override
        public int compare(S3ObjectSummary o1, S3ObjectSummary o2) {
            return o1.getKey().compareTo(o2.getKey());
        }
    });
    return objectListing;
}

From source file:au.org.ands.vocabs.toolkit.provider.transform.PropertyRewriterTransformProvider.java

@Override
public final boolean transform(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {
    // Prepare for rewriting.
    if (!loadRewriteMap()) {
        results.put(TaskStatus.ERROR, "PropertyRewriter unable to load rewrite map");
        return false;
    }/*  w  ww . j a  v a 2s.co m*/

    Path originalHarvestdir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
    // Use this transform name and the task ID to construct
    // the path names.
    String transformName = "PropertyRewriter_" + taskInfo.getTask().getId();
    String transformOutputDir = ToolkitFileUtils.getTaskTransformTemporaryOutputPath(taskInfo, transformName);
    Path transformOutputDirPath = Paths.get(transformOutputDir);

    try {
        ToolkitFileUtils.requireEmptyDirectory(transformOutputDir);
    } catch (IOException ex) {
        results.put(TaskStatus.EXCEPTION,
                "Exception in PropertyRewriter while cleaning old " + "transform output directory");
        logger.error("Exception in PropertyRewriter while cleaning old " + "transform output directory: ", ex);
        return false;
    }

    // Open the harvest directory ...
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(originalHarvestdir)) {
        // ... and iterate over every file in the harvest directory.
        for (Path entry : stream) {
            // First, parse the file into a model and do rewriting.
            Model model = new LinkedHashModel();
            RDFFormat format = Rio.getParserFormatForFileName(entry.toString());
            RDFParser rdfParser = Rio.createParser(format);
            ConceptHandler conceptHandler = new ConceptHandler(metadataRewriteConf, model);
            rdfParser.setRDFHandler(conceptHandler);
            FileInputStream is = new FileInputStream(entry.toString());
            logger.debug("Reading RDF:" + entry.toString());
            rdfParser.parse(is, entry.toString());
            // And now serialize the result.
            String resultFileName = transformOutputDirPath.resolve(entry.getFileName()).toString();
            FileOutputStream out = new FileOutputStream(resultFileName);
            // Write in the same format we read.
            Rio.write(model, out, format);
            out.close();
        }
    } catch (DirectoryIteratorException | IOException | RDFParseException | RDFHandlerException
            | UnsupportedRDFormatException ex) {
        results.put(TaskStatus.EXCEPTION, "Exception in PropertyRewriter while Parsing RDF");
        logger.error("Exception in PropertyRewriter while Parsing RDF:", ex);
        return false;
    }

    // Done rewriting, and was successful. Replace the old
    // harvest with the transformed files.
    if (!ToolkitFileUtils.renameTransformTemporaryOutputPath(taskInfo, transformName)) {
        results.put(TaskStatus.ERROR, "Error in PropertyRewriter when renaming output " + "directory");
        logger.error("Error in PropertyRewriter when renaming output " + "directory");
        return false;
    }

    return true;
}

From source file:com.acmutv.ontoqa.tool.io.IOManager.java

/**
 * Returns the list of all files inside {@code directory}.
 * @param directory the directory to inspect.
 * @return the list of all files inside {@code directory}.
 * @throws IOException when files cannot be listed in {@code directory}.
 *//*from  w  w w  .j  a va  2s.  com*/
public static List<Path> allFiles(String directory) throws IOException {
    List<Path> files = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(directory))) {
        directoryStream.forEach(f -> {
            if (Files.isRegularFile(f))
                files.add(f);
        });
    }
    return files;
}

From source file:org.wso2.carbon.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java

private void run() {
    while (!isWatchServiceStopped) {
        WatchKey watchKey;//from   w w  w  .j a  v a  2  s .c  o m
        try {
            watchKey = watchService.take();
        } catch (ClosedWatchServiceException e) {
            log.debug("File watch service is closed.");
            return;
        } catch (InterruptedException e) {
            log.debug("File watch service interrupted.");
            return;
        }

        for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
            if (watchEvent.kind() != StandardWatchEventKinds.ENTRY_MODIFY) {
                continue;
            }

            Path updatedDirectory = (Path) watchKey.watchable();
            @SuppressWarnings("unchecked")
            Path updatedFileName = ((WatchEvent<Path>) watchEvent).context();
            // Updating the changed html file
            Path updatedFileAbsolutePath = updatedDirectory.resolve(updatedFileName);
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(updatedFileAbsolutePath.getParent())) {
                for (Path entry : stream) {
                    if (Files.isDirectory(entry)) {
                        continue;
                    }

                    MutableHtmlRenderable mutableHtmlRenderable = watchingRenderables.get(entry);
                    if (mutableHtmlRenderable != null) {
                        try {
                            String content = new String(Files.readAllBytes(entry), StandardCharsets.UTF_8);
                            mutableHtmlRenderable.setHtml(content);
                            log.info("HTML template '" + entry + "' reloaded successfully.");
                        } catch (IOException e) {
                            log.error("An error occurred while reloading HTML template '" + entry + "'.", e);
                        }
                    }
                }
            } catch (IOException e) {
                log.error("An error occurred while reloading HTML template '" + updatedFileAbsolutePath + "'.",
                        e);
            }
        }

        boolean valid = watchKey.reset();
        if (!valid) {
            // Watch key cannot not be reset because watch service is already closed.
            break;
        }
    }
}

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

public List<String> getYears(String tagName) throws IOException {
    List<String> years = new LinkedList<>();
    rrwl.readLock().lock();/*from   ww  w  . j  a v  a 2s .  c  om*/
    try (DirectoryStream<Path> ds = Files
            .newDirectoryStream(Paths.get(settingDao.getSetting("tags.directory") + "/" + tagName))) {
        for (Path path : ds) {
            Matcher matcher = tagYearPattern.matcher(path.toString());
            if (matcher.find() && Files.isDirectory(path))
                years.add(matcher.group(1));
        }
    } finally {
        rrwl.readLock().unlock();
    }
    Collections.sort(years, new YearComparator());
    return years;

}

From source file:com.cpjit.swagger4j.util.ReflectUtils.java

/**
 * ????//from  ww  w  .ja v  a2  s . c o  m
 * 
 * @param basePackage
 * @param recursion
 *            ????
 * @return    ???null
 *          0
 *          <li>?</li>
 *          <li>package-info.java?</li>
 *          <li>?basePackage</li>
 * @since 1.0.0
 */
public static List<Package> scanPackage(final String basePackage, boolean recursion) {
    if (StringUtils.isBlank(basePackage)) {
        return Collections.emptyList();
    }

    Set<Package> packages = new HashSet<Package>();
    String pack2path = basePackage.replaceAll("\\.", "/");
    URL url = ResourceUtil.getResource(pack2path);
    if (url == null) { // ?
        return Collections.emptyList();
    }

    Path pkFile = null;
    try {
        pkFile = Paths.get(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(basePackage + "????", e);
    }
    if (!Files.isDirectory(pkFile)) {
        throw new IllegalArgumentException(basePackage + "????");
    }

    Package pk = null;
    try {
        pk = getPackage(basePackage);
    } catch (Exception e) {
    }
    if (pk != null) {
        packages.add(pk);
    }

    if (recursion && StringUtils.isNotBlank(basePackage)) { // ???
        try (DirectoryStream<Path> childs = Files.newDirectoryStream(pkFile)) {
            childs.forEach(child -> {
                if (Files.isDirectory(child)) {
                    String childPackage = basePackage + "." + child.getFileName().toString();
                    if (StringUtils.isBlank(basePackage)) { // 
                        childPackage = child.getFileName().toString();
                    }
                    packages.addAll(scanPackage(childPackage, true));
                }
            });
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    if (packages.size() < 1) { // ??
        return Collections.emptyList();
    }

    return new ArrayList<Package>(packages);
}