Example usage for org.apache.commons.io.filefilter SuffixFileFilter SuffixFileFilter

List of usage examples for org.apache.commons.io.filefilter SuffixFileFilter SuffixFileFilter

Introduction

In this page you can find the example usage for org.apache.commons.io.filefilter SuffixFileFilter SuffixFileFilter.

Prototype

public SuffixFileFilter(List suffixes) 

Source Link

Document

Constructs a new Suffix file filter for a list of suffixes.

Usage

From source file:org.silverpeas.core.process.io.file.TestFileHandler.java

@Test
public void testListFilesFromSessionAndRealPathWithFilters() throws Exception {
    buildCommonPathStructure();/*from  w w  w  . j  a  v a  2 s . co  m*/
    Collection<File> files = fileHandler.listFiles(BASE_PATH_TEST, realRootPath, TrueFileFilter.INSTANCE,
            TrueFileFilter.INSTANCE);
    assertThat(files.size(), is(13));
    assertThat(listFiles(sessionHandledPath, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).size(), is(7));
    assertThat(listFiles(realRootPath, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).size(), is(14));

    // Non recursive
    files = fileHandler.listFiles(BASE_PATH_TEST, realRootPath, TrueFileFilter.INSTANCE,
            FalseFileFilter.INSTANCE);
    assertThat(files.size(), is(3));
    assertThat(listFiles(sessionHandledPath, TrueFileFilter.INSTANCE, FalseFileFilter.INSTANCE).size(), is(2));
    assertThat(listFiles(realRootPath, TrueFileFilter.INSTANCE, FalseFileFilter.INSTANCE).size(), is(2));

    // Extension
    files = fileHandler.listFiles(BASE_PATH_TEST, realRootPath,
            new SuffixFileFilter(new String[] { ".test", ".xml", ".txt" }), TrueFileFilter.INSTANCE);
    assertThat(files.size(), is(3));
    assertThat(listFiles(sessionHandledPath, new SuffixFileFilter(new String[] { "test", ".xml", "txt" }),
            TrueFileFilter.INSTANCE).size(), is(1));
    assertThat(listFiles(realRootPath, new SuffixFileFilter(new String[] { "test", "xml", "txt" }),
            TrueFileFilter.INSTANCE).size(), is(3));
}

From source file:org.silverpeas.core.process.io.file.TestHandledFile.java

@Test
public void testListFilesWithFilters() throws Exception {
    buildCommonPathStructure();/*from ww w. j a  v a 2  s. co  m*/
    final HandledFile test = getHandledFile(realRootPath);
    Collection<HandledFile> files = test.listFiles(TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
    assertThat(files.size(), is(13));
    assertThat(listFiles(sessionHandledPath, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).size(), is(7));
    assertThat(listFiles(realRootPath, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE).size(), is(14));

    // Non recursive
    files = test.listFiles(TrueFileFilter.INSTANCE, FalseFileFilter.INSTANCE);
    assertThat(files.size(), is(3));
    assertThat(listFiles(sessionHandledPath, TrueFileFilter.INSTANCE, FalseFileFilter.INSTANCE).size(), is(2));
    assertThat(listFiles(realRootPath, TrueFileFilter.INSTANCE, FalseFileFilter.INSTANCE).size(), is(2));

    // Extension
    files = test.listFiles(new SuffixFileFilter(new String[] { ".test", ".xml", ".txt" }),
            TrueFileFilter.INSTANCE);
    assertThat(files.size(), is(3));
    assertThat(listFiles(sessionHandledPath, new SuffixFileFilter(new String[] { "test", ".xml", "txt" }),
            TrueFileFilter.INSTANCE).size(), is(1));
    assertThat(listFiles(realRootPath, new SuffixFileFilter(new String[] { "test", "xml", "txt" }),
            TrueFileFilter.INSTANCE).size(), is(3));
}

From source file:org.sipfoundry.sipxconfig.admin.localization.LocalizationContextImpl.java

public String[] getInstalledRegions() {
    String[] regions = getListOfDirectories(m_regionDir, REGION_PREFIX);
    List<String> result = new ArrayList<String>(regions.length);
    for (String region : regions) {
        File regionDir = new File(m_regionDir, region);
        String[] files = regionDir.list(new SuffixFileFilter(DIALPLAN_TEMPLATE));
        if (files != null && files.length > 0) {
            result.add(region);/*from  w  ww.ja  va 2 s.co m*/
        }
    }
    return result.toArray(new String[result.size()]);
}

From source file:org.sonar.plugins.web.api.ProjectFileManager.java

private IOFileFilter getFileSuffixFilter() {
    IOFileFilter suffixFilter = FileFilterUtils.trueFileFilter();

    List<String> suffixes = Arrays.asList(getFileSuffixes());
    if (!suffixes.isEmpty()) {
        suffixFilter = new SuffixFileFilter(suffixes);
    }/*from   www.  ja va  2s .c  o m*/

    return suffixFilter;
}

From source file:org.tellervo.desktop.bulkdataentry.command.PopulateFromODKCommand.java

public void execute(MVCEvent argEvent) {

    try {//ww  w  . jav  a2s.  com
        MVC.splitOff(); // so other mvc events can execute
    } catch (IllegalThreadException e) {
        // this means that the thread that called splitOff() was not an MVC thread, and the next event's won't be blocked anyways.
        e.printStackTrace();
    } catch (IncorrectThreadException e) {
        // this means that this MVC thread is not the main thread, it was already splitOff() previously
        e.printStackTrace();
    }

    PopulateFromODKFileEvent event = (PopulateFromODKFileEvent) argEvent;
    ArrayList<ODKParser> filesProcessed = new ArrayList<ODKParser>();
    ArrayList<ODKParser> filesFailed = new ArrayList<ODKParser>();
    Path instanceFolder = null;

    // Launch the ODK wizard to collect parameters from user
    ODKImportWizard wizard = new ODKImportWizard(BulkImportModel.getInstance().getMainView());

    if (wizard.wasCancelled())
        return;

    if (wizard.isRemoteAccessSelected()) {
        // Doing remote server download of ODK files
        try {

            // Request a zip file of ODK files from the server ensuring the temp file is deleted on exit
            URI uri;
            uri = new URI(
                    App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid url!") + "/" + "odk/fetchInstances.php");
            String file = getRemoteODKFiles(uri);

            if (file == null) {
                // Download was cancelled
                return;
            }

            new File(file).deleteOnExit();

            // Unzip to a temporary folder, again ensuring it is deleted on exit 
            instanceFolder = Files.createTempDirectory("odk-unzip");
            instanceFolder.toFile().deleteOnExit();

            log.debug("Attempting to open zip file: '" + file + "'");

            ZipFile zipFile = new ZipFile(file);
            try {
                Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = entries.nextElement();
                    File entryDestination = new File(instanceFolder.toFile(), entry.getName());
                    entryDestination.deleteOnExit();
                    if (entry.isDirectory()) {
                        entryDestination.mkdirs();
                    } else {
                        entryDestination.getParentFile().mkdirs();
                        InputStream in = zipFile.getInputStream(entry);
                        OutputStream out = new FileOutputStream(entryDestination);
                        IOUtils.copy(in, out);
                        IOUtils.closeQuietly(in);
                        out.close();
                    }
                }
            } finally {
                zipFile.close();
            }
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // Accessing ODK files from local folder
        instanceFolder = new File(wizard.getODKInstancesFolder()).toPath();
    }

    // Check the instance folder specified exists
    File folder = instanceFolder.toFile();
    if (!folder.exists()) {

        log.error("Instances folder does not exist");
        return;
    }

    // Compile a hash set of all media files in the instance folder and subfolders
    File file = null;
    File[] mediaFileArr = null;
    if (wizard.isIncludeMediaFilesSelected()) {
        HashSet<File> mediaFiles = new HashSet<File>();

        // Array of file extensions to consider as media files
        String[] mediaExtensions = { "jpg", "mpg", "snd", "mp4", "m4a" };
        for (String ext : mediaExtensions) {
            SuffixFileFilter filter = new SuffixFileFilter("." + ext);
            Iterator<File> it = FileUtils.iterateFiles(folder, filter, TrueFileFilter.INSTANCE);
            while (it.hasNext()) {
                file = it.next();
                mediaFiles.add(file);
            }
        }

        // Copy files to consolidate to a new folder 
        mediaFileArr = mediaFiles.toArray(new File[mediaFiles.size()]);
        String copyToFolder = wizard.getCopyToLocation();
        for (int i = 0; i < mediaFileArr.length; i++) {
            file = mediaFileArr[i];

            File target = new File(copyToFolder + file.getName());
            try {
                FileUtils.copyFile(file, target, true);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            mediaFileArr[i] = target;
        }
    }

    SampleModel smodel = event.sampleModel;
    ElementModel emodel = event.elementModel;
    ObjectModel model = event.objectModel;

    try {
        if (smodel.getTableModel().getRowCount() == 1 && smodel.getTableModel().getAllSingleRowModels().get(0)
                .getProperty(SingleSampleModel.TITLE) == null) {
            // Empty table first
            smodel.getTableModel().getAllSingleRowModels().clear();
        }
    } catch (Exception ex) {
        log.debug("Error deleting empty rows");
    }

    try {
        if (emodel.getTableModel().getRowCount() == 1 && emodel.getTableModel().getAllSingleRowModels().get(0)
                .getProperty(SingleElementModel.TITLE) == null) {
            // Empty table first
            emodel.getTableModel().getAllSingleRowModels().clear();
        }
    } catch (Exception ex) {
        log.debug("Error deleting empty rows");
    }

    try {
        if (model.getTableModel().getRowCount() == 1 && model.getTableModel().getAllSingleRowModels().get(0)
                .getProperty(SingleObjectModel.OBJECT_CODE) == null) {
            // Empty table first
            model.getTableModel().getAllSingleRowModels().clear();
        }
    } catch (Exception ex) {
        log.debug("Error deleting empty rows");
    }

    SuffixFileFilter fileFilter = new SuffixFileFilter(".xml");
    Iterator<File> iterator = FileUtils.iterateFiles(folder, fileFilter, TrueFileFilter.INSTANCE);
    while (iterator.hasNext()) {
        file = iterator.next();
        filesFound++;

        try {

            ODKParser parser = new ODKParser(file);
            filesProcessed.add(parser);

            if (!parser.isValidODKFile()) {
                filesFailed.add(parser);
                continue;
            } else if (parser.getFileType() == null) {
                filesFailed.add(parser);
                continue;
            } else if (parser.getFileType() == ODKFileType.OBJECTS) {
                addObjectToTableFromParser(parser, model, wizard, mediaFileArr);
            } else if (parser.getFileType() == ODKFileType.ELEMENTS_AND_SAMPLES) {
                addElementFromParser(parser, emodel, wizard, mediaFileArr);
                addSampleFromParser(parser, smodel, wizard, mediaFileArr);
            } else {
                filesFailed.add(parser);
                continue;
            }

        } catch (FileNotFoundException e) {
            otherErrors += "<p color=\"red\">Error loading file:</p>\n"
                    + ODKParser.formatFileNameForReport(file);
            otherErrors += "<br/>  - File not found<br/><br/>";
        } catch (IOException e) {
            otherErrors += "<p color=\"red\">Error loading file:</p>\n"
                    + ODKParser.formatFileNameForReport(file);
            otherErrors += "<br/>  - IOException - " + e.getLocalizedMessage() + "<br/><br/>";
        } catch (Exception e) {
            otherErrors += "<p color=\"red\">Error parsing file:</p>\n"
                    + ODKParser.formatFileNameForReport(file);
            otherErrors += "<br/>  - Exception - " + e.getLocalizedMessage() + "<br/><br/>";
        }

    }

    // Create a CSV file of metadata if the user requested it
    if (wizard.isCreateCSVFileSelected()) {
        try {
            createCSVFile(filesProcessed, wizard.getCSVFilename());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // Compile logs to display to user
    StringBuilder log = new StringBuilder();
    log.append("<html>\n");
    for (ODKParser parser : filesFailed) {
        log.append("<p color=\"red\">Error loading file:</p>\n"
                + ODKParser.formatFileNameForReport(parser.getFile()));
        log.append("<br/>  - " + parser.getParseErrorMessage() + "<br/><br/>");
    }
    for (ODKParser parser : filesProcessed) {
        if (filesFailed.contains(parser))
            continue;
        if (parser.getParseErrorMessage() == "")
            continue;

        log.append("<p color=\"orange\">Warning loading file:</p>\n"
                + ODKParser.formatFileNameForReport(parser.getFile()));
        log.append("<br/>  - " + parser.getParseErrorMessage() + "<br/><br/>");
    }
    log.append(otherErrors);
    log.append("</html>");
    ODKParserLogViewer logDialog = new ODKParserLogViewer(BulkImportModel.getInstance().getMainView());
    logDialog.setLog(log.toString());
    logDialog.setFileCount(filesFound, filesLoadedSuccessfully);

    // Display log if there were any errors or if no files were found
    if (filesFound > filesLoadedSuccessfully) {
        logDialog.setVisible(true);
    } else if (filesFound == 0 && wizard.isRemoteAccessSelected()) {
        Alert.error(BulkImportModel.getInstance().getMainView(), "Not found",
                "No ODK data files were found on the server.  Please ensure you've used the 'send finalized form' option in ODK Collect and try again");
        return;
    } else if (filesFound == 0) {
        Alert.error(BulkImportModel.getInstance().getMainView(), "Not found",
                "No ODK data files were found in the specified folder.  Please check and try again.");
        return;
    } else if (wizard.isIncludeMediaFilesSelected()) {
        Alert.message(BulkImportModel.getInstance().getMainView(), "Download Complete",
                "The ODK download is complete.  As requested, your media files have been temporarily copied to the local folder '"
                        + wizard.getCopyToLocation()
                        + "'.  Please remember to move them to their final location");
    }

}

From source file:org.tolven.developmentmgr.DevelopmentMgr.java

protected void deployPluginJARs() throws IOException {
    File devLibDir = getDevLib();
    if (!devLibDir.exists()) {
        devLibDir.mkdirs();//from   w w w .ja v  a2s  .co  m
    }
    File tmpDevLibDir = new File(getPluginTmpDir(), "tmpDevLib");
    if (tmpDevLibDir.exists()) {
        FileUtils.deleteDirectory(tmpDevLibDir);
    }
    tmpDevLibDir.mkdirs();
    Set<File> newSourceJars = new HashSet<File>();
    for (final PluginDescriptor pluginDescriptor : getManager().getRegistry().getPluginDescriptors()) {
        ExtensionPoint devLibExtensionPoint = pluginDescriptor.getExtensionPoint(EXTENSIONPOINT_DEVLIB);
        if (devLibExtensionPoint != null) {
            Set<File> sourceJars = new HashSet<File>();
            for (ParameterDefinition parameterDefinition : devLibExtensionPoint.getParameterDefinitions()) {
                if ("jarDir".equals(parameterDefinition.getId())) {
                    String defaultJARDirValue = parameterDefinition.getDefaultValue();
                    File jarDir = getFilePath(pluginDescriptor, defaultJARDirValue);
                    if (!jarDir.exists()) {
                        throw new RuntimeException(pluginDescriptor.getUniqueId()
                                + " does not contain the directory called: " + defaultJARDirValue);
                    }
                    for (String sourceJarname : jarDir.list(new SuffixFileFilter("jar"))) {
                        File sourceJar = new File(jarDir.getPath(), sourceJarname);
                        sourceJars.add(sourceJar);
                    }
                } else {
                    String defaultJARValue = parameterDefinition.getDefaultValue();
                    File sourceJar = getFilePath(pluginDescriptor, defaultJARValue);
                    if (!sourceJar.exists()) {
                        throw new RuntimeException("Could not locate: " + sourceJar.getPath() + " for plugin: "
                                + pluginDescriptor.getId());
                    }
                    sourceJars.add(sourceJar);
                }
            }
            for (File sourceJar : sourceJars) {
                String extendedSourceJarname = getExtendedJarname(sourceJar.getName(), pluginDescriptor);
                File extendSourceJar = new File(tmpDevLibDir, extendedSourceJarname);
                FileUtils.copyFile(sourceJar, extendSourceJar);
                newSourceJars.add(extendSourceJar);
            }
        }
    }
    if (devLibDir.exists()) {
        FileUtils.deleteDirectory(devLibDir);
    }
    for (File newSourceJar : newSourceJars) {
        logger.debug("Add to development library " + newSourceJar.getPath());
        FileUtils.moveFileToDirectory(newSourceJar, devLibDir, true);
    }
}

From source file:org.tolven.tools.TolvenInstaller.java

private static void updateScripts(File binDirectory, File templateBinDir, File selectedConfigDir)
        throws IOException {
    String extension = null;//from   w w  w .jav  a  2s  . co m
    if (System.getProperty("os.name").toLowerCase().indexOf("windows") == -1) {
        extension = ".sh";
    } else {
        extension = ".bat";
    }
    Collection<File> scripts = FileUtils.listFiles(templateBinDir, new SuffixFileFilter(extension), null);
    for (File script : scripts) {
        File dest = new File(binDirectory, script.getName());
        if (dest.exists()) {
            dest.delete();
        }
        System.out.println("move: " + script.getPath() + " to: " + binDirectory.getPath());
        FileUtils.moveFileToDirectory(script, binDirectory, false);
        if (script.getName().equals("tpfenv" + extension)) {
            List<String> lines = FileUtils.readLines(dest);
            List<String> sub_lines = new ArrayList<String>();
            boolean tpfenvRequiresUpdate = false;
            for (String line : lines) {
                String replacedLine = line.replace("$TOLVEN_CONFIG", selectedConfigDir.getPath());
                if (!replacedLine.equals(line)) {
                    tpfenvRequiresUpdate = true;
                }
                sub_lines.add(replacedLine);
            }
            if (tpfenvRequiresUpdate) {
                System.out.println("updated: " + dest.getPath());
                FileUtils.writeLines(dest, sub_lines);
            }
        }
    }
}

From source file:org.toobsframework.mojo.XsdRelease.java

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException {
    int count = 0;
    int of = 0;// w  w  w . j  a  va  2  s .c  o  m

    try {
        if (verbose) {
            getLog().info("release-xsd will attempt copy versions of xsds from directory " + source.getPath()
                    + " to directory " + target.getPath() + " with version " + version);
        }

        if (!source.exists()) {
            throw new MojoExecutionException(
                    "Cannot copy xsds from " + source.getPath() + " since the directory does not exists");
        }
        if (!source.isDirectory()) {
            throw new MojoExecutionException(
                    "Cannot copy xsds from " + source.getPath() + " since it is not a directory");
        }

        if (verbose) {
            getLog().info(source.getPath() + " directory was located");
        }

        if (!target.exists()) {
            if (!target.mkdirs()) {
                throw new MojoExecutionException("Cannot create the targetdirectory " + target.getPath());
            }
            if (verbose) {
                getLog().info(target.getPath() + " directory was created");
            }
        } else if (!target.isDirectory()) {
            throw new MojoExecutionException(
                    "Cannot copy xsds from " + target.getPath() + " since it is not a directory");
        } else {
            if (verbose) {
                getLog().info(target.getPath() + " directory was located");
            }
        }

        File[] sourceFiles = source.listFiles((FileFilter) new SuffixFileFilter(".xsd"));
        for (File inputFile : sourceFiles) {
            of++;

            String fileName = replace(inputFile.getName(), ".xsd", "-" + version + ".xsd");
            File outputFile = new File(target, fileName);

            if (outputFile.exists() && FileUtils.isFileNewer(outputFile, inputFile)) {
                if (verbose) {
                    getLog().info("File " + inputFile.getPath() + " is newer than " + outputFile.getPath()
                            + ".  Skipped.");
                }
                continue;
            }

            if (verbose) {
                getLog().info("copying file " + inputFile.getPath() + " to " + outputFile.getPath());
            }

            InputStream inputStream = new FileInputStream(inputFile);
            List<String> inputLines;
            try {
                inputLines = IOUtils.readLines(inputStream);
            } finally {
                inputStream.close();
            }

            List<String> outputLines = new ArrayList<String>(inputLines.size());
            for (String inputLine : inputLines) {
                String line = fixupLine(inputLine);
                outputLines.add(line);
                /*getLog().info(">>" + line);*/
            }

            OutputStream outputStream = new FileOutputStream(outputFile, false);
            try {
                IOUtils.writeLines(outputLines, "\n", outputStream);
            } finally {
                outputStream.close();
            }
            count++;
        }

        if (count == 0) {
            getLog().info("No xsds released - " + of + " are up to date");
        } else {
            getLog().info(count + " xsd(s) out of " + of + " were sucessfully updated");
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Error occurred when trying to release xsds: " + e.getMessage(), e);
    }
}

From source file:org.uimafit.examples.LicenseTest.java

private void test(File directory) throws IOException {
    List<String> filesMissingLicense = new ArrayList<String>();

    Iterator<?> files = org.apache.commons.io.FileUtils.iterateFiles(directory, new SuffixFileFilter(".java"),
            TrueFileFilter.INSTANCE);//from  w ww .  j  a v  a  2 s  . c  om

    while (files.hasNext()) {
        File file = (File) files.next();
        if (file.getParentFile().getName().equals("type") || file.getName().equals("Files.java")) {
            continue;
        }

        String fileText = FileUtils.file2String(file);

        //
        //         boolean hasCopyright = fileText.indexOf("Copyright") != -1;
        boolean hasLicense = (fileText.indexOf("Licensed under the Apache License, Version 2.0") != -1)
                || (fileText.indexOf("Licensed to the Apache Software Foundation") != -1);
        boolean hasAuthor = fileText.indexOf("@author") != -1;
        boolean isPackageDoc = "package-info.java".equals(file.getName());
        if ( /*!hasCopyright ||*/ !hasLicense || (!isPackageDoc && !hasAuthor)) {
            filesMissingLicense.add(file.getPath());
        }
    }

    if (filesMissingLicense.size() > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append(filesMissingLicense.size());
        sb.append(" source file missing license or author attribution:\n");
        Collections.sort(filesMissingLicense);
        for (String path : filesMissingLicense) {
            sb.append(path).append('\n');
        }
        Assert.fail(sb.toString());
    }
}

From source file:org.uimafit.LicenseTest.java

private void test(File directory) throws IOException {
    List<String> filesMissingLicense = new ArrayList<String>();

    Iterator<?> files = org.apache.commons.io.FileUtils.iterateFiles(directory, new SuffixFileFilter(".java"),
            TrueFileFilter.INSTANCE);// ww w . j a v a 2s  .  c  om

    while (files.hasNext()) {
        File file = (File) files.next();
        if (file.getParentFile().getName().equals("type") || file.getName().equals("Files.java")) {
            continue;
        }

        String fileText = FileUtils.file2String(file);

        boolean hasCopyright = fileText.indexOf("Copyright") != -1;
        boolean hasLicense = fileText.indexOf("Licensed under the Apache License, Version 2.0") != -1;
        boolean hasAuthor = fileText.indexOf("@author") != -1;
        boolean isPackageDoc = "package-info.java".equals(file.getName());
        if (!hasCopyright || !hasLicense || (!isPackageDoc && !hasAuthor)) {
            filesMissingLicense.add(file.getPath());
        }
    }

    if (filesMissingLicense.size() > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append(filesMissingLicense.size());
        sb.append(" source file missing license or author attribution:\n");
        Collections.sort(filesMissingLicense);
        for (String path : filesMissingLicense) {
            sb.append(path).append('\n');
        }
        Assert.fail(sb.toString());
    }
}