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.sonarlint.intellij.core.SonarLintServerManager.java

private URL[] loadPlugins() throws IOException, URISyntaxException {
    URL pluginsDir = this.getClass().getClassLoader().getResource("plugins");

    if (pluginsDir == null) {
        throw new IllegalStateException("Couldn't find plugins");
    }// w w w  .  j  a  va  2 s.  c  o  m

    List<URL> pluginsUrls = new ArrayList<>();
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get(pluginsDir.toURI()),
            "*.jar")) {
        for (Path path : directoryStream) {
            globalLogOutput.log("Found plugin: " + path.getFileName().toString(), LogOutput.Level.DEBUG);
            pluginsUrls.add(path.toUri().toURL());
        }
    }
    return pluginsUrls.toArray(new URL[pluginsUrls.size()]);
}

From source file:org.opencastproject.staticfiles.impl.StaticFileServiceImpl.java

/**
 * Deletes all files found in the temporary storage section of an organization.
 *
 * @param org/*from   ww w  .j  a  v a  2 s. c o m*/
 *          The organization identifier
 * @throws IOException
 *           if there was an error while deleting the files.
 */
void purgeTemporaryStorageSection(final String org, final long lifetime) throws IOException {
    logger.info("Purge temporary storage section of organization '{}'", org);
    final Path temporaryStorageDir = getTemporaryStorageDir(org);
    if (Files.exists(temporaryStorageDir)) {
        try (DirectoryStream<Path> tempFilesStream = Files.newDirectoryStream(temporaryStorageDir,
                new DirectoryStream.Filter<Path>() {
                    @Override
                    public boolean accept(Path path) throws IOException {
                        return (Files.getLastModifiedTime(path).toMillis() < (new Date()).getTime() - lifetime);
                    }
                })) {
            for (Path file : tempFilesStream) {
                FileUtils.deleteQuietly(file.toFile());
            }
        }
    }
}

From source file:business.services.FileService.java

public List<String> getAccessLogFilenames() {
    try {/*from w  w w.  j  a  v  a2s  .com*/
        List<String> logFiles = new ArrayList<String>();
        for (Path p : Files.newDirectoryStream(fileSystem.getPath("./logs/"), "dntp-access*.log")) {
            logFiles.add(p.getFileName().toString());
        }
        Collections.sort(logFiles, Collections.reverseOrder());
        return logFiles;
    } catch (IOException e) {
        log.error(e);
        throw new FileDownloadError();
    }
}

From source file:org.apache.storm.daemon.supervisor.AdvancedFSOps.java

public DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)
        throws IOException {
    return Files.newDirectoryStream(dir, filter);
}

From source file:org.apache.zeppelin.interpreter.InterpreterSettingManager.java

private void init() throws InterpreterException, IOException, RepositoryException {
    String interpreterJson = zeppelinConfiguration.getInterpreterJson();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    if (Files.exists(interpreterDirPath)) {
        for (Path interpreterDir : Files.newDirectoryStream(interpreterDirPath, new Filter<Path>() {
            @Override/*from w w w . j  a va 2 s.c  om*/
            public boolean accept(Path entry) throws IOException {
                return Files.exists(entry) && Files.isDirectory(entry);
            }
        })) {
            String interpreterDirString = interpreterDir.toString();

            /**
             * Register interpreter by the following ordering
             * 1. Register it from path {ZEPPELIN_HOME}/interpreter/{interpreter_name}/
             *    interpreter-setting.json
             * 2. Register it from interpreter-setting.json in classpath
             *    {ZEPPELIN_HOME}/interpreter/{interpreter_name}
             * 3. Register it by Interpreter.register
             */
            if (!registerInterpreterFromPath(interpreterDirString, interpreterJson)) {
                if (!registerInterpreterFromResource(cl, interpreterDirString, interpreterJson)) {
                    /*
                     * TODO(jongyoul)
                     * - Remove these codes below because of legacy code
                     * - Support ThreadInterpreter
                    */
                    URLClassLoader ccl = new URLClassLoader(recursiveBuildLibList(interpreterDir.toFile()), cl);
                    for (String className : interpreterClassList) {
                        try {
                            // Load classes
                            Class.forName(className, true, ccl);
                            Set<String> interpreterKeys = Interpreter.registeredInterpreters.keySet();
                            for (String interpreterKey : interpreterKeys) {
                                if (className.equals(Interpreter.registeredInterpreters.get(interpreterKey)
                                        .getClassName())) {
                                    Interpreter.registeredInterpreters.get(interpreterKey)
                                            .setPath(interpreterDirString);
                                    logger.info("Interpreter " + interpreterKey + " found. class=" + className);
                                    cleanCl.put(interpreterDirString, ccl);
                                }
                            }
                        } catch (Throwable t) {
                            // nothing to do
                        }
                    }
                }
            }
        }
    }

    for (RegisteredInterpreter registeredInterpreter : Interpreter.registeredInterpreters.values()) {
        logger.debug("Registered: {} -> {}. Properties: {}", registeredInterpreter.getInterpreterKey(),
                registeredInterpreter.getClassName(), registeredInterpreter.getProperties());
    }

    // RegisteredInterpreters -> interpreterSettingRef
    InterpreterInfo interpreterInfo;
    for (RegisteredInterpreter r : Interpreter.registeredInterpreters.values()) {
        interpreterInfo = new InterpreterInfo(r.getClassName(), r.getName(), r.isDefaultInterpreter(),
                r.getEditor());
        add(r.getGroup(), interpreterInfo, r.getProperties(), defaultOption, r.getPath(), r.getRunner());
    }

    for (String settingId : interpreterSettingsRef.keySet()) {
        InterpreterSetting setting = interpreterSettingsRef.get(settingId);
        logger.info("InterpreterSettingRef name {}", setting.getName());
    }

    loadFromFile();

    // if no interpreter settings are loaded, create default set
    if (0 == interpreterSettings.size()) {
        Map<String, InterpreterSetting> temp = new HashMap<>();
        InterpreterSetting interpreterSetting;
        for (InterpreterSetting setting : interpreterSettingsRef.values()) {
            interpreterSetting = createFromInterpreterSettingRef(setting);
            temp.put(setting.getName(), interpreterSetting);
        }

        for (String group : interpreterGroupOrderList) {
            if (null != (interpreterSetting = temp.remove(group))) {
                interpreterSettings.put(interpreterSetting.getId(), interpreterSetting);
            }
        }

        for (InterpreterSetting setting : temp.values()) {
            interpreterSettings.put(setting.getId(), setting);
        }

        saveToFile();
    }

    for (String settingId : interpreterSettings.keySet()) {
        InterpreterSetting setting = interpreterSettings.get(settingId);
        logger.info("InterpreterSetting group {} : id={}, name={}", setting.getGroup(), settingId,
                setting.getName());
    }
}

From source file:org.onehippo.cms7.essentials.dashboard.services.ContentBeansService.java

private Map<String, Path> findExitingBeans() {
    final Path startDir = context.getBeansPackagePath();
    final Map<String, Path> existingBeans = new HashMap<>();
    final List<Path> directories = new ArrayList<>();
    GlobalUtils.populateDirectories(startDir, directories);
    final String pattern = "*.java";
    for (Path directory : directories) {
        try (final DirectoryStream<Path> stream = Files.newDirectoryStream(directory, pattern)) {
            for (Path path : stream) {
                final String nodeJcrType = JavaSourceUtils.getNodeJcrType(path);
                if (nodeJcrType != null) {
                    existingBeans.put(nodeJcrType, path);
                }//from   w  w w. j  a v  a 2  s  .  c  om
            }
        } catch (IOException e) {
            log.error("Error reading java files", e);
        }
    }
    return existingBeans;

}

From source file:org.esa.s2tbx.dataio.s2.Sentinel2ProductReader.java

/**
 * get an iterator to image files in pathToImages containing files for the given resolution
 * <p>//from  w  w  w .  j a v a  2 s .  c  om
 * This method is based on band names, if resolution can't be based on band names or if image files are not in
 * pathToImages (like for L2A products), this method has to be overriden
 *
 * @param pathToImages the path to the directory containing the images
 * @param resolution   the resolution for which we want to get images
 * @return a {@link DirectoryStream<Path>}, iterator on the list of image path
 * @throws IOException if an I/O error occurs
 */
protected DirectoryStream<Path> getImageDirectories(Path pathToImages, S2SpatialResolution resolution)
        throws IOException {
    return Files.newDirectoryStream(pathToImages, entry -> {
        String[] bandNames = getBandNames(resolution);
        if (bandNames != null) {
            for (String bandName : bandNames) {
                if (entry.toString().endsWith(bandName + ".jp2")) {
                    return true;
                }
            }
        }
        return false;
    });
}

From source file:dk.dma.msinm.common.repo.RepositoryService.java

/**
 * Returns a list of files in the folder specified by the path
 * @param path the path// w w w.j a v a  2  s. c o  m
 * @return the list of files in the folder specified by the path
 */
@GET
@javax.ws.rs.Path("/list/{folder:.+}")
@Produces("application/json;charset=UTF-8")
@NoCache
public List<RepoFileVo> listFiles(@PathParam("folder") String path) throws IOException {

    List<RepoFileVo> result = new ArrayList<>();
    Path folder = repoRoot.resolve(path);

    if (Files.exists(folder) && Files.isDirectory(folder)) {

        // Filter out directories, hidden files, thumbnails and map images
        DirectoryStream.Filter<Path> filter = file -> Files.isRegularFile(file)
                && !file.getFileName().toString().startsWith(".")
                && !file.getFileName().toString().matches(".+_thumb_\\d{1,3}\\.\\w+") && // Thumbnails
                !file.getFileName().toString().matches("map_\\d{1,3}\\.png"); // Map image

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder, filter)) {
            stream.forEach(f -> {
                RepoFileVo vo = new RepoFileVo();
                vo.setName(f.getFileName().toString());
                vo.setPath(WebUtils.encodeURI(path + "/" + f.getFileName().toString()));
                vo.setDirectory(Files.isDirectory(f));
                try {
                    vo.setUpdated(new Date(Files.getLastModifiedTime(f).toMillis()));
                    vo.setSize(Files.size(f));
                } catch (Exception e) {
                    log.trace("Error reading file attribute for " + f);
                }
                result.add(vo);
            });
        }
    }
    return result;
}

From source file:org.ow2.authzforce.pap.dao.flatfile.FlatFileDAORefPolicyProviderModule.java

private FlatFileDAORefPolicyProviderModule(final Path policyParentDirectory, final String suffix,
        final XACMLParserFactory xacmlParserFactory, final ExpressionFactory expressionFactory,
        final CombiningAlgRegistry combiningAlgRegistry, final int maxPolicySetRefDepth)
        throws IllegalArgumentException {
    assert policyParentDirectory != null;
    assert xacmlParserFactory != null;
    assert expressionFactory != null;
    assert combiningAlgRegistry != null;

    FlatFileDAOUtils.checkFile("RefPolicyProvider's policy directory", policyParentDirectory, true, false);
    final Map<String, Map<PolicyVersion, PolicyEvaluatorSupplier>> updatablePolicyMap = HashObjObjMaps
            .newUpdatableMap();//w ww  .j  av  a 2 s . com
    // filter matching specifc file suffix for policy files
    final Filter<? super Path> policyFilenameSuffixMatchingDirStreamFilter = new SuffixMatchingDirectoryStreamFilter(
            suffix);
    try (final DirectoryStream<Path> policyParentDirStream = Files.newDirectoryStream(policyParentDirectory,
            FlatFileDAOUtils.SUB_DIRECTORY_STREAM_FILTER)) {
        // Browse directories of policies, one for each policy ID
        for (final Path policyVersionsDir : policyParentDirStream) {
            /*
             * FindBugs considers there is a potential NullPointerException
             * here since getFileName() may be null
             */
            final Path lastPathSegment = policyVersionsDir.getFileName();
            if (lastPathSegment == null) {
                throw new IllegalArgumentException(
                        "Invalid policy directory: no filename (root of filesystem?): " + policyVersionsDir);
            }

            final String policyDirName = lastPathSegment.toString();
            final String policyId;
            try {
                policyId = FlatFileDAOUtils.base64UrlDecode(policyDirName);
            } catch (final IllegalArgumentException e) {
                throw new IllegalArgumentException(
                        "Invalid policy directory: bad filename (not Base64URL-encoded): " + policyDirName, e);
            }

            final Map<PolicyVersion, PolicyEvaluatorSupplier> policySetSuppliersByVersion = HashObjObjMaps
                    .newUpdatableMap();
            // Browse policy versions, one policy file for each version of
            // the current policy
            try (final DirectoryStream<Path> policyVersionsDirStream = Files
                    .newDirectoryStream(policyVersionsDir, policyFilenameSuffixMatchingDirStreamFilter)) {
                for (final Path policyVersionFile : policyVersionsDirStream) {
                    /*
                     * The PolicyEvaluator supplier (from file) allows to
                     * instantiate the Evaluator only if needed, because the
                     * instantiation of a PolicyEvaluator from a file is
                     * expensive.
                     */
                    policySetSuppliersByVersion.put(
                            new PolicyVersion(FlatFileDAOUtils.getPrefix(policyVersionFile, suffix.length())),
                            new PolicyEvaluatorSupplier(policyVersionFile));
                }
            } catch (final IOException e) {
                throw new IllegalArgumentException("Error listing files of each version of policy '" + policyId
                        + "' in directory: " + policyParentDirectory, e);
            }

            updatablePolicyMap.put(policyId, policySetSuppliersByVersion);
        }
    } catch (final IOException e) {
        throw new IllegalArgumentException(
                "Error listing files in policies parent directory '" + policyParentDirectory, e);
    }

    this.policyCache = new PolicyMap<>(updatablePolicyMap);
    this.xacmlParserFactory = xacmlParserFactory;
    this.expressionFactory = expressionFactory;
    this.combiningAlgRegistry = combiningAlgRegistry;
    this.maxPolicyRefDepth = maxPolicySetRefDepth;
}

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

/**
 * Loads jars from the pluginsFolder to the classpath, so the ServiceLoader
 * can find them.//from  w  ww  . j  av  a 2s .c om
 */
private void loadModulesIntoClasspath() {
    Path moduleFolder = FileSystems.getDefault().getPath(modulePath);

    URLClassLoader sysLoader;
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(moduleFolder, JAR)) {
        for (Path f : stream) {
            File loc = new File(f.toString());
            sysLoader = (URLClassLoader) this.getClass().getClassLoader();
            ArrayList<URL> urls = new ArrayList<>(Arrays.asList(sysLoader.getURLs()));
            URL udir = loc.toURI().toURL();

            if (!urls.contains(udir)) {
                Class<URLClassLoader> sysClass = URLClassLoader.class;
                Method method = sysClass.getDeclaredMethod("addURL", URL.class);
                method.setAccessible(true);
                method.invoke(sysLoader, udir);
            }
        }
    } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        logger.error(ERROR, e.getMessage());
    }
}