Example usage for org.apache.commons.io FileUtils listFiles

List of usage examples for org.apache.commons.io FileUtils listFiles

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils listFiles.

Prototype

public static Collection listFiles(File directory, String[] extensions, boolean recursive) 

Source Link

Document

Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.

Usage

From source file:com.meltmedia.cadmium.core.config.impl.YamlConfigurationParser.java

/**
 * This will only parse the files with the extensions of <code>.yml</code> or <code>.yaml</code> in the directory specified.
 *//*from  www. ja v a 2  s  .  c  o  m*/
@Override
public void parseDirectory(File configurationDirectory) throws Exception {
    this.configurationDirectory = configurationDirectory;
    if (configurationDirectory != null && configurationDirectory.isDirectory()
            && configurationDirectory.canRead()) {
        Collection<File> configFiles = FileUtils.listFiles(configurationDirectory,
                new String[] { "yml", "yaml" }, true);
        List<File> files = new ArrayList<File>(configFiles);
        Collections.sort(files, NameFileComparator.NAME_INSENSITIVE_COMPARATOR);
        Map<String, Map<String, ?>> configurationMap = new HashMap<String, Map<String, ?>>();
        Yaml yamlParser = new Yaml(getClassTags());
        for (File configFile : files) {
            FileReader reader = null;
            try {
                reader = new FileReader(configFile);
                for (Object parsed : yamlParser.loadAll(reader)) {
                    mergeConfigs(configurationMap, parsed);
                }
            } finally {
                IOUtils.closeQuietly(reader);
            }
        }
        this.configuration = configurationMap;
    } else if (configurationDirectory != null && configurationDirectory.isDirectory()) {
        logger.warn("Directory {} cannot be read.", configurationDirectory);
    } else if (configurationDirectory != null) {
        logger.warn("Directory {} is not a directory or does not exist.", configurationDirectory);
    } else {
        throw new IllegalArgumentException("The configurationDirectory must be specified.");
    }
}

From source file:com.gettingagile.tisugly.analyzer.ASMAnalyzer.java

@SuppressWarnings("unchecked")
private Collection<File> listClassesInDirectory(File dir) {
    return FileUtils.listFiles(dir, new String[] { "class" }, true);
}

From source file:com.ariht.maven.plugins.config.io.DirectoryReader.java

/**
 * Return collection of all files in directory and sub-directories, ignoring any that
 * have been specifically excluded in plugin configuration.
 *//*from   www  . jav a  2 s .com*/
@SuppressWarnings("rawtypes")
private Collection<File> getAllFiles(final File directory, final List<File> filesToIgnore) {
    if (!directory.exists()) {
        log.warn("Directory does not exist: " + directory.getPath());
        return EMPTY_FILE_LIST;
    }
    final Collection allFiles = FileUtils.listFiles(directory, TrueFileFilter.TRUE,
            DirectoryFileFilter.DIRECTORY);
    final Collection<File> files = new ArrayList<File>(allFiles.size());
    for (final Object o : allFiles) {
        if (o != null && o instanceof File) {
            final File file = (File) o;
            if (isFileToIgnore(file, filesToIgnore)) {
                log.debug("Ignoring : " + file.toString());
            } else {
                log.debug("Adding file: " + file.toString());
                files.add(file);
            }
        } else {
            log.warn("Not a file: " + ToStringBuilder.reflectionToString(o));
        }
    }
    return files;
}

From source file:info.magnolia.cms.util.ClasspathResourcesUtil.java

/**
 * Load resources from jars or directories
 *
 * @param resources found resources will be added to this collection
 * @param jarOrDir  a File, can be a jar or a directory
 * @param filter    used to filter resources
 *//* ww  w  .  j  av  a  2  s  .c om*/
private static void collectFiles(Collection resources, File jarOrDir, Filter filter) {

    if (!jarOrDir.exists()) {
        log.warn("missing file: {}", jarOrDir.getAbsolutePath());
        return;
    }

    if (jarOrDir.isDirectory()) {
        if (log.isDebugEnabled())
            log.debug("looking in dir {}", jarOrDir.getAbsolutePath());

        Collection files = FileUtils.listFiles(jarOrDir, new TrueFileFilter() {
        }, new TrueFileFilter() {
        });
        for (Iterator iter = files.iterator(); iter.hasNext();) {
            File file = (File) iter.next();
            String name = StringUtils.substringAfter(file.getPath(), jarOrDir.getPath());

            // please, be kind to Windows!!!
            name = StringUtils.replace(name, "\\", "/");
            if (!name.startsWith("/")) {
                name = "/" + name;
            }

            if (filter.accept(name)) {
                resources.add(name);
            }
        }
    } else if (jarOrDir.getName().endsWith(".jar")) {
        if (log.isDebugEnabled())
            log.debug("looking in jar {}", jarOrDir.getAbsolutePath());
        JarFile jar;
        try {
            jar = new JarFile(jarOrDir);
        } catch (IOException e) {
            log.error("IOException opening file {}, skipping", jarOrDir.getAbsolutePath());
            return;
        }
        for (Enumeration em = jar.entries(); em.hasMoreElements();) {
            JarEntry entry = (JarEntry) em.nextElement();
            if (!entry.isDirectory()) {
                if (filter.accept("/" + entry.getName())) {
                    resources.add("/" + entry.getName());
                }
            }
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("Unknown (not jar) file in classpath: {}, skipping.", jarOrDir.getName());
    }

}

From source file:com.denimgroup.threadfix.framework.impl.spring.SpringControllerMappings.java

private Collection<File> getFiles(File rootDirectory, String extension) {
    return FileUtils.listFiles(rootDirectory, new FileExtensionFileFilter(extension), TrueFileFilter.INSTANCE);
}

From source file:com.norconex.committer.AbstractFileQueueCommitterTest.java

@Test
public void testMultipleCommitThread() throws Exception {

    final AtomicInteger counter = new AtomicInteger();

    final AbstractFileQueueCommitter committer = new AbstractFileQueueCommitter() {

        @Override/*from  ww w.  j a va2 s .co m*/
        protected void commitAddition(IAddOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitDeletion(IDeleteOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitComplete() {
        }
    };

    File queue = temp.newFolder();
    committer.setQueueDir(queue.getPath());
    // Use a bigger number to make sure the files are not 
    // committed while they are added.
    committer.setQueueSize(1000);

    // Queue 50 files for additions
    for (int i = 0; i < 50; i++) {
        Properties metadata = new Properties();
        committer.add(Integer.toString(i), IOUtils.toInputStream("hello world!"), metadata);
    }
    // Queue 50 files for deletions
    for (int i = 50; i < 100; i++) {
        Properties metadata = new Properties();
        committer.remove(Integer.toString(i), metadata);
    }

    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    committer.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    pool.shutdown();
    pool.awaitTermination(10, TimeUnit.SECONDS);

    // Each file should have been processed exactly once
    assertEquals(100, counter.intValue());

    // All files should have been processed
    Collection<File> files = FileUtils.listFiles(queue, null, true);
    assertTrue(files.isEmpty());
}

From source file:bear.main.GroovyCompiler.java

public synchronized GroovyClassLoader compileScripts(List<File> sourceDirs, ClassLoader parentCL) {
    nameMap.clear();/*from w ww  . j  a  v a  2s  . com*/
    simpleNameMap.clear();

    if (gcl == null) {
        gcl = new GroovyClassLoader(parentCL);
    }

    gcl.addClasspath(buildDir.getAbsolutePath());

    for (File sourceDir : sourceDirs) {
        List<File> groovySources = new ArrayList<File>(FileUtils.listFiles(sourceDir, extensions, true));

        try {
            for (File file : groovySources) {
                GroovyCodeSource source = sourceMap.get(file);

                if (source == null) {
                    sourceMap.put(file, source = new GroovyCodeSource(file, "UTF-8"));
                }

                logger.info("compiling {}...", file);

                Class aClass = gcl.parseClass(source);

                CompiledEntry<?> e = new CompiledEntry(aClass, file, "groovy");

                simpleNameMap.put(aClass.getSimpleName(), e);
                nameMap.put(aClass.getName(), e);
            }
        } catch (IOException e) {
            throw Exceptions.runtime(e);
        }
    }

    return gcl;
}

From source file:de.peran.dependency.ChangedTestClassesHandler.java

public boolean initialyGetTraces() throws IOException, InterruptedException {
    final MavenKiekerTestExecutor generator = new MavenKiekerTestExecutor(projectFolder, resultsFolder,
            new File(projectFolder, "peran_logs"));

    if (resultsFolder.exists()) {
        FileUtils.deleteDirectory(resultsFolder);
    }/* w w  w .  ja  va 2s  .co m*/

    generator.executeTests();

    if (resultsFolder.exists()) {
        LOG.debug("Initial test execution finished, starting result collection");
        for (final File testResultFile : FileUtils.listFiles(resultsFolder, new WildcardFileFilter("*.xml"),
                TrueFileFilter.INSTANCE)) {
            final String testClassName = testResultFile.getParentFile().getName();
            final String testMethodName = testResultFile.getName().substring(0,
                    testResultFile.getName().length() - 4); // remove .xml
            final File parent = testResultFile.getParentFile();
            updateDependenciesOnce(testClassName, testMethodName, parent);
        }
        LOG.debug("Result collection finished");
        return true;
    } else {
        LOG.debug("No result data available - error occured?");
        return false;
    }
}

From source file:com.flysystem.core.adapter.local.Local.java

public List<FileMetadata> listContents(String directory, boolean recursive) {
    List<File> files = (List<File>) FileUtils.listFiles(getExistingFile(directory), null, recursive);
    return FileMetadataConverter.doConvert(files, getPathPrefix());
}

From source file:de.renew.workflow.connector.internal.cases.ScenarioCompatibilityHelper.java

public static boolean ensureBackwardsCompatibility(final ScenarioHandlingProjectNature nature) {
    // FIXME: this is dirty fix only for this release 2.3
    // should be implemented in other way, we just do not have any time now
    try {// ww  w  .j a va2  s.com
        if (nature == null
                || !nature.getProject().hasNature("org.kalypso.kalypso1d2d.pjt.Kalypso1D2DProjectNature")) //$NON-NLS-1$
            return true;

        // FIXME: the whole code here does not belong to this place -> this is a hidden dependency to 1d2d: bad!
        // TODO: instead implement an extension point mechanism
        final ProjectTemplate[] lTemplate = EclipsePlatformContributionsExtensions
                .getProjectTemplates("org.kalypso.kalypso1d2d.pjt.projectTemplate"); //$NON-NLS-1$
        try {
            // FIXME: this very probably does not work correctly or any more at all!

            /* Unpack project from template */
            final File destinationDir = nature.getProject().getLocation().toFile();
            final URL data = lTemplate[0].getData();
            final String location = data.toString();
            final String extension = FilenameUtils.getExtension(location);
            if ("zip".equalsIgnoreCase(extension)) //$NON-NLS-1$
            {
                // TODO: this completely overwrite the old project content, is this intended?
                ZipUtilities.unzip(data.openStream(), destinationDir, false);
            } else {
                final URL fileURL = FileLocator.toFileURL(data);
                final File dataDir = FileUtils.toFile(fileURL);
                if (dataDir == null) {
                    return false;
                }

                // FIXME: this only fixes the basic scenario, is this intended?

                final IOFileFilter lFileFilter = new WildcardFileFilter(new String[] { "wind.gml" }); //$NON-NLS-1$
                final IOFileFilter lDirFilter = TrueFileFilter.INSTANCE;
                final Collection<?> windFiles = FileUtils.listFiles(destinationDir, lFileFilter, lDirFilter);

                if (dataDir.isDirectory() && (windFiles == null || windFiles.size() == 0)) {
                    final WildcardFileFilter lCopyFilter = new WildcardFileFilter(
                            new String[] { "*asis", "models", "wind.gml" }); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                    FileUtils.copyDirectory(dataDir, destinationDir, lCopyFilter);
                } else {
                    return true;
                }
            }
        } catch (final Throwable t) {
            t.printStackTrace();
            return false;
        }

        nature.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (final CoreException e) {
        // FIXME: this is no error handling; the users are not informed and will stumble over following errors caued by
        // this problem

        WorkflowConnectorPlugin.getDefault().getLog().log(e.getStatus());
        e.printStackTrace();
        return false;
    }

    return true;
}