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:cop.maven.plugins.AbstractRestToRamlMojo.java

private List<File> getSourceFiles() {
    return getSourceDirectories().stream()
            .map(sourceDirectory -> FileUtils.listFiles(sourceDirectory, JAVA_FILE_FILTER,
                    DirectoryFileFilter.INSTANCE))
            .map(sourceFiles -> (List<File>) sourceFiles).flatMap(List::stream).collect(Collectors.toList());
}

From source file:io.neocdtv.simpleplayer.ui.PlaylistTransferHandler.java

@Override
public boolean importData(TransferHandler.TransferSupport info) {
    if (!info.isDrop()) {
        return false;
    }//w w  w . j  ava2 s  .  c om

    JList list = (JList) info.getComponent();
    DefaultListModel<PlaylistEntry> listModel = (DefaultListModel) list.getModel();
    JList.DropLocation dropLocation = (JList.DropLocation) info.getDropLocation();

    // Get the string that is being dropped.
    Transferable transferable = info.getTransferable();
    List<File> data;
    try {
        data = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
        for (File file : data) {
            if (file.isDirectory()) {
                final boolean recursive = true;
                final String[] fileExtensionFilter = null;
                final List<File> listFiles = Arrays.asList(FileUtils.convertFileCollectionToFileArray(
                        FileUtils.listFiles(file, fileExtensionFilter, recursive)));
                for (File o : listFiles) {
                    listModel.addElement(buildEntry(o));
                }
            } else {
                listModel.addElement(buildEntry(file));
            }
        }
    } catch (UnsupportedFlavorException | IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return false;
    }
    return true;
}

From source file:com.temenos.interaction.loader.classloader.CachingParentLastURLClassloaderFactory.java

protected synchronized URLClassLoader createClassLoader(Object currentState, FileEvent<File> param) {
    try {//from  w  ww. j a va 2s.co  m
        LOGGER.debug(
                "Classloader requested from CachingParentLastURLClassloaderFactory, based on FileEvent reflecting change in {}",
                param.getResource().getAbsolutePath());
        Set<URL> urls = new HashSet<URL>();
        File newTempDir = new File(FileUtils.getTempDirectory(), currentState.toString());
        FileUtils.forceMkdir(newTempDir);
        Collection<File> files = FileUtils.listFiles(param.getResource(), new String[] { "jar" }, true);
        for (File f : files) {
            try {
                LOGGER.trace("Adding {} to list of URLs to create classloader from", f.toURI().toURL());
                FileUtils.copyFileToDirectory(f, newTempDir);
                urls.add(new File(newTempDir, f.getName()).toURI().toURL());
            } catch (MalformedURLException ex) {
                // should not happen, we do have the file there
                // but if, what can we do - just log it
                LOGGER.warn("Trying to intilialize classloader based on URL failed!", ex);
            }
        }
        lastClassloaderTempDir = newTempDir;
        URLClassLoader classloader = new ParentLastURLClassloader(urls.toArray(new URL[] {}),
                Thread.currentThread().getContextClassLoader());

        return classloader;
    } catch (IOException ex) {
        throw new RuntimeException("Unexpected error trying to create new classloader.", ex);
    }
}

From source file:com.garethahealy.camel.file.loadbalancer.example1.routes.Read99FilesWithThreeReadersTest.java

@Test
public void readThreeFilesWithThreeReaders() throws InterruptedException, MalformedURLException {
    Map<String, String> answer = getRouteToEndpointPriority();

    //Used for debugging purposes, in-case we need to know which endpoint has what priority
    LOG.info("EndpointSetup: " + answer.toString());

    MockEndpoint first = getMockEndpoint("mock:endFirst");
    first.setExpectedMessageCount(33);/*from w w w . ja v a2  s .c  o  m*/
    first.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    first.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

    MockEndpoint second = getMockEndpoint("mock:endSecond");
    second.setExpectedMessageCount(33);
    second.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    second.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

    MockEndpoint third = getMockEndpoint("mock:endThird");
    third.setExpectedMessageCount(33);
    third.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    third.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

    //Wait for the files to be processed
    sleep(30);

    File firstDirectory = FileUtils.toFile(new URL("file:" + rootDirectory + "/.camel0"));
    File secondDirectory = FileUtils.toFile(new URL("file:" + rootDirectory + "/.camel1"));
    File thirdDirectory = FileUtils.toFile(new URL("file:" + rootDirectory + "/.camel2"));

    Assert.assertTrue(".camel0 doesnt exist", firstDirectory.exists());
    Assert.assertTrue(".camel1 doesnt exist", secondDirectory.exists());
    Assert.assertTrue(".camel2 doesnt exist", thirdDirectory.exists());

    Collection<File> firstFiles = FileUtils.listFiles(firstDirectory, FileFilterUtils.fileFileFilter(), null);
    Collection<File> secondFiles = FileUtils.listFiles(secondDirectory, FileFilterUtils.fileFileFilter(), null);
    Collection<File> thirdFiles = FileUtils.listFiles(thirdDirectory, FileFilterUtils.fileFileFilter(), null);

    Assert.assertNotNull(firstFiles);
    Assert.assertNotNull(secondFiles);
    Assert.assertNotNull(thirdFiles);

    //Check the files are unique, and we haven't copied the same file twice
    int firstSize = firstFiles.size();
    int secondSize = secondFiles.size();
    int thirdSize = thirdFiles.size();

    firstFiles.removeAll(secondFiles);
    firstFiles.removeAll(thirdFiles);

    secondFiles.removeAll(firstFiles);
    secondFiles.removeAll(thirdFiles);

    thirdFiles.removeAll(firstFiles);
    thirdFiles.removeAll(secondFiles);

    //If these numbers don't match, we duplicated a file
    Assert.assertEquals("duplicate copy in .camel0", new Integer(firstSize), new Integer(firstFiles.size()));
    Assert.assertEquals("duplicate copy in .camel1", new Integer(secondSize), new Integer(secondFiles.size()));
    Assert.assertEquals("duplicate copy in .camel2", new Integer(thirdSize), new Integer(thirdFiles.size()));

    //Check the expected copied amount is correct
    Assert.assertEquals(new Integer(33), new Integer(firstFiles.size()));
    Assert.assertEquals(new Integer(33), new Integer(secondFiles.size()));
    Assert.assertEquals(new Integer(33), new Integer(thirdFiles.size()));
    Assert.assertEquals(new Integer(99),
            new Integer(firstFiles.size() + secondFiles.size() + thirdFiles.size()));

    //Assert the endpoints last, as there seems to be a strange bug where they fail but the files have been processed,
    //so that would suggest the MockEndpoints are reporting a false-positive
    first.assertIsSatisfied();
    second.assertIsSatisfied();
    third.assertIsSatisfied();
}

From source file:com.amalto.core.query.SystemStorageTest.java

private static Collection<String> getConfigFiles() throws Exception {
    URL data = InitDBUtil.class.getResource("data"); //$NON-NLS-1$
    List<String> result = new ArrayList<String>();
    if ("jar".equals(data.getProtocol())) { //$NON-NLS-1$
        JarURLConnection connection = (JarURLConnection) data.openConnection();
        JarEntry entry = connection.getJarEntry();
        JarFile file = connection.getJarFile();
        Enumeration<JarEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            JarEntry e = entries.nextElement();
            if (e.getName().startsWith(entry.getName()) && !e.isDirectory()) {
                result.add(IOUtils.toString(file.getInputStream(e)));
            }//from  w ww  .j  ava  2 s . c o m
        }
    } else {
        Collection<File> files = FileUtils.listFiles(new File(data.toURI()), new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                return true;
            }

            @Override
            public boolean accept(File file, String s) {
                return true;
            }
        }, new IOFileFilter() {

            @Override
            public boolean accept(File file) {
                return !".svn".equals(file.getName()); //$NON-NLS-1$
            }

            @Override
            public boolean accept(File file, String s) {
                return !".svn".equals(file.getName()); //$NON-NLS-1$
            }
        });
        for (File f : files) {
            result.add(IOUtils.toString(new FileInputStream(f)));
        }
    }
    return result;
}

From source file:architecture.ee.jdbc.sqlquery.scanner.DirectoryScanner.java

protected void buildFromDirectory(File file) throws BuilderException {
    for (File f : FileUtils.listFiles(file,
            FileFilterUtils.suffixFileFilter(sqlQueryFactory.getConfiguration().getSuffix()),
            FileFilterUtils.trueFileFilter())) {
        if (!sqlQueryFactory.getConfiguration().isResourceLoaded(f.toURI().toString())) {
            log.debug("building " + f.toURI().toString());
            try {
                XmlSqlSetBuilder builder = new XmlSqlSetBuilder(new FileInputStream(f),
                        sqlQueryFactory.getConfiguration(), f.toURI().toString(), null);
                builder.parse();/*from w  w w .  j  a v a 2  s . com*/
            } catch (IOException e) {
                throw new BuilderException("build faild", e);
            }
        }
    }
}

From source file:de.uzk.hki.da.pkg.MetsConsistencyChecker.java

/**
 * Checks the package consistency based on actual files
 * present in package the on the file system.
 * /*  w w w  .j  ava  2s . com*/
 * For every file in the packagePath, a checksum will be computed.
 * Also a corresponding mets:FLocat element will be extracted and
 * the expected checksum will be compared to the computed one.
 *
 * @return true if a corresponding FLocat element could be found for every
 * file and the checksums matched, otherwise false
 * @throws Exception the exception
 */
public boolean checkPackageBasedOnFiles() throws Exception {

    boolean result = true;

    Namespace metsNS = Namespace.getNamespace("mets", "http://www.loc.gov/METS/");
    Namespace xlinkNS = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink");
    String metsPath = packagePath + "/export_mets.xml";

    SAXBuilder builder = new SAXBuilder(false);
    Document doc = builder.build(new File(metsPath));

    ExecutorService executor = Executors.newFixedThreadPool(8);
    List<FileChecksumVerifierThread> threads = new ArrayList<FileChecksumVerifierThread>();

    String absPackagePath = new File(packagePath).getAbsolutePath();

    for (File f : (List<File>) FileUtils.listFiles(new File(packagePath), null, true)) {

        // skip the METS file itself
        if ("export_mets.xml".equals(f.getName())) {
            continue;
        }

        String relPath = f.getAbsolutePath().substring(absPackagePath.length() + 1);

        logger.debug("Verifying file: {}", relPath);

        String xpathExpr = "//mets:file/mets:FLocat[@xlink:href='" + relPath + "']";
        XPath xpath = XPath.newInstance(xpathExpr);
        xpath.addNamespace(metsNS);
        xpath.addNamespace(xlinkNS);
        Element elemFLocat = (Element) xpath.selectSingleNode(doc);

        // check if METS contains FLocat element for file
        if (elemFLocat == null) {
            result = false;
            String msg = "Could not find FLocat element in METS metadata: " + relPath;
            logger.error(msg);
            messages.add(msg);
            continue;
        }

        Element elemFile = elemFLocat.getParentElement();

        String checksum = elemFile.getAttributeValue("CHECKSUM");
        String checksumType = elemFile.getAttributeValue("CHECKSUMTYPE");

        // check if required attributes are set
        if (checksum == null) {
            logger.warn(
                    "METS File Element in {} does not contain attribute CHECKSUM. File consistency can not be verified.",
                    metsPath);
            continue;
        }
        if (checksumType == null) {
            logger.warn(
                    "METS File Element in {} does not contain attribute CHECKSUM TYPE. File consistency can not be verified.",
                    metsPath);
            continue;
        }

        logger.debug("Checking with algorithm: {}", checksumType);

        // calculate and verify checksum
        checksumType = checksumType.replaceAll("-", "");
        try {
            MessageDigest algorithm = MessageDigest.getInstance(checksumType);
            threads.add(new FileChecksumVerifierThread(checksum, f, algorithm));
        } catch (NoSuchAlgorithmException e) {
            logger.warn(
                    "METS File Element in {} contains unknown CHECKSUM TYPE: {}. File consistency can not be verified.",
                    metsPath, checksumType);
            continue;
        }

    }

    List<Future<ChecksumResult>> futures = executor.invokeAll(threads);

    for (Future<ChecksumResult> future : futures) {
        ChecksumResult cResult = future.get();
        if (!cResult.isSuccess()) {
            result = false;
            logger.error(cResult.getMessage());
            messages.add(cResult.getMessage());
        }
    }

    return result;

}

From source file:edu.kit.dama.util.release.GenerateSourceRelease.java

public static void checkLicenseHeaders(File destination) throws IOException {
    //check license headers
    Collection<File> files = FileUtils.listFiles(destination, new String[] { "java", "xml" }, true);
    for (File f : files) {
        boolean haveLicense = false;
        try (BufferedReader bf = new BufferedReader(new FileReader(f))) {
            String line;/*from  w w w. j a  v  a2s  . com*/
            while ((line = bf.readLine()) != null) {
                if (line.contains("Licensed under the Apache License")) {
                    haveLicense = true;
                    break;
                }
            }
        }
        if (!haveLicense) {
            System.out.println("File  " + f + " seems to have no/an invalid license header.");
        }
    }
}

From source file:dpfmanager.shell.interfaces.gui.component.show.ShowController.java

public void showComboTextArea(String folderPath, String extension) {
    int count = 0;

    // Clear comboBox
    getView().clearComboBox();/* w  ww  .ja va 2  s. co  m*/

    // Check if summary
    File summary = new File(folderPath);
    if (summary.isFile()) {
        getView().setCurrentReportParams(summary.getParent(), extension);
        getView().addComboChild(summary.getName().replace("." + extension, ""), true);
        count++;
    }

    // Add all individuals
    File folder = new File(folderPath);
    if (folder.isFile()) {
        folder = folder.getParentFile();
    }
    getView().setCurrentReportParams(folder.getPath(), extension);

    IOFileFilter filter = customFilter(extension);
    IOFileFilter filterDir = customFilterDir(folder.getPath());
    Collection<File> childs = FileUtils.listFiles(folder, filter, filterDir);
    for (File child : childs) {
        String onlyName = child.getName().replace("." + extension, "");
        if (count == 0) {
            getView().addComboChild(onlyName, true);
        } else {
            getView().addComboChild(onlyName, false);
        }
        count++;
    }

    // Show nodes
    getView().showTextArea();
    if (count > 1) {
        getView().showComboBox();
    }
}

From source file:key.secretkey.utils.PasswordStorage.java

public static Repository initialize(Context context) {
    File dir = getRepositoryDirectory(context);
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());

    if (dir == null) {
        return null;
    }/*w w  w . j  ava  2  s .c  om*/

    // uninitialize the repo if the dir does not exist or is absolutely empty
    if (!dir.exists() || !dir.isDirectory() || FileUtils.listFiles(dir, null, false).isEmpty()) {
        settings.edit().putBoolean("repository_initialized", false).apply();
    }

    if (!PasswordStorage.getPasswords(dir).isEmpty()) {
        settings.edit().putBoolean("repository_initialized", true).apply();
    }

    // create the repository static variable in PasswordStorage
    return PasswordStorage.getRepository(new File(dir.getAbsolutePath() + "/.git"));
}