Example usage for org.apache.commons.io.filefilter TrueFileFilter INSTANCE

List of usage examples for org.apache.commons.io.filefilter TrueFileFilter INSTANCE

Introduction

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

Prototype

IOFileFilter INSTANCE

To view the source code for org.apache.commons.io.filefilter TrueFileFilter INSTANCE.

Click Source Link

Document

Singleton instance of true filter.

Usage

From source file:io.snappydata.hydra.cluster.SnappyTest.java

protected static String getUserAppJarLocation(final String jarName, String jarPath) {
    String userAppJarPath = null;
    File baseDir = new File(jarPath);
    try {/*from   w  ww .jav a2  s. c o m*/
        IOFileFilter filter = new WildcardFileFilter(jarName);
        List<File> files = (List<File>) FileUtils.listFiles(baseDir, filter, TrueFileFilter.INSTANCE);
        Log.getLogWriter().info("Jar file found: " + Arrays.asList(files));
        for (File file1 : files) {
            if (!file1.getAbsolutePath().contains("/work/")
                    || !file1.getAbsolutePath().contains("/scala-2.10/"))
                userAppJarPath = file1.getAbsolutePath();
        }
    } catch (Exception e) {
        Log.getLogWriter().info("Unable to find " + jarName + " jar at " + jarPath + " location.");
    }
    return userAppJarPath;
}

From source file:de.teamgrit.grit.report.TexGenerator.java

/**
 * Writes the source code into the .tex file.
 * //from  w w  w  .  j  av a 2s .c om
 * @param file
 *            File the source code gets written into.
 * @param submission
 *            SubmissionObj the needed information gets taken from.
 * @throws IOException
 *             If something goes wrong when writing.
 */
private static void writeSourceCode(File file, Submission submission) throws IOException {
    FileWriterWithEncoding writer = new FileWriterWithEncoding(file, "UTF-8", true);

    writer.append("\\paragraph{Code}~\\\\\n");

    for (File f : FileUtils.listFiles(submission.getSourceCodeLocation().toFile(),
            FileFilterUtils.fileFileFilter(), TrueFileFilter.INSTANCE)) {

        // determines programming language of the file and adjusts the
        // lstlisting according to it
        String language = "no valid file";
        String fileExtension = FilenameUtils.getExtension(f.toString());

        if (fileExtension.matches("[Jj][Aa][Vv][Aa]")) {
            language = "Java";
        } else if (fileExtension.matches("([Ll])?[Hh][Ss]")) {
            language = "Haskell";
        } else if (fileExtension.matches("[Cc]|[Hh]")) {
            language = "C";
        } else if (fileExtension.matches("[Cc][Pp][Pp]")) {
            language = "C++";
        } else {
            // file is not a valid source file
            continue;
        }

        writer.append("\\lstinputlisting[language=" + language);

        writer.append(", breaklines=true]{" + FilenameUtils.separatorsToUnix((f.getAbsolutePath())) + "}\n");

    }
    writer.close();
}

From source file:com.btoddb.fastpersitentqueue.JournalMgrIT.java

@Test
public void testShutdownHasRemainingData() throws IOException {
    mgr.setMaxJournalFileSize(51);//from w  ww.jav a  2 s. co m
    mgr.init();

    FpqEntry entry1 = mgr.append(new FpqEntry(idGen.incrementAndGet(), new byte[] { 0, 1, 2, 3 }));
    FpqEntry entry2 = mgr.append(new FpqEntry(idGen.incrementAndGet(), new byte[] { 0, 1, 2, 3 }));
    FpqEntry entry3 = mgr.append(new FpqEntry(idGen.incrementAndGet(), new byte[] { 0, 1, 2, 3 }));
    assertThat(mgr.getJournalIdMap().entrySet(), hasSize(2));

    mgr.reportTake(entry1);
    mgr.reportTake(entry2);
    mgr.shutdown();

    Collection<File> remainingFiles = FileUtils.listFiles(theDir, TrueFileFilter.INSTANCE,
            TrueFileFilter.INSTANCE);
    assertThat(remainingFiles, hasSize(1));
    assertThat(remainingFiles,
            contains(mgr.getJournalIdMap().get(entry3.getJournalId()).getFile().getFile().getAbsoluteFile()));
    assertThat(mgr.getJournalIdMap(), not(hasKey(entry1.getJournalId())));
    assertThat(mgr.getJournalIdMap(), not(hasKey(entry2.getJournalId())));
    assertThat(mgr.getJournalIdMap(), hasKey(entry3.getJournalId()));
}

From source file:de.uzk.hki.da.cb.UnpackNoBagitAction.java

/**
 * @return/*from  www .  ja  v a2 s.co m*/
 */
private Map<String, List<File>> generateDocumentsToFilesMap() {

    Map<String, List<File>> documentsToFiles = new HashMap<String, List<File>>();

    Collection<File> files = FileUtils.listFiles(wa.dataPath().toFile(), TrueFileFilter.INSTANCE,
            TrueFileFilter.INSTANCE);
    for (File file : files) {
        String document = file.getAbsolutePath().replace(wa.dataPath().toFile().getAbsolutePath(), "");
        document = document.substring(1);
        document = FilenameUtils.removeExtension(document);

        if (!documentsToFiles.keySet().contains(document)) {

            List<File> filesList = new ArrayList<File>();
            filesList.add(file);
            documentsToFiles.put(document, filesList);
        } else {
            documentsToFiles.get(document).add(file);
        }
    }
    return documentsToFiles;
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.environmentchecker.XSDFriendlyValidatorBasedChecker.java

/**
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.environmentchecker.EnvironmentChecker#checkEnvironment(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext)
 *///from   w w  w .ja  va 2s  .  c  om
@Override
public void checkEnvironment(ConfigurationAnalysisContext context)
        throws EnvironmentException, EnvironmentCheckingException {
    List<XMLNotValidAgainstXSDException> negativeValidationResults = new ArrayList<>();
    for (ExtractedConfiguration<?> extractedConfiguration : context.getExtractedConfigurations()) {
        //If a filtering target is specified, we ignore all the extracted configurations which do not come from it.
        if (target != null && !extractedConfiguration.getTarget().equals(target)) {
            continue;
        }
        Object extractedConfigurationData = extractedConfiguration.getConfigurationData();
        // We check whether this list is a List<File>. It is not so
        // simple, as Java looses information about parametrized types
        // at runtime.
        if (!(extractedConfigurationData instanceof List)) {
            continue;// It is not a list
        }
        List<?> extractedList = (List<?>) extractedConfigurationData;
        if (extractedList.size() == 0 || !(extractedList.get(0) instanceof File)) {
            continue;// This is not the kind of list we were looking
                     // for.
        }
        @SuppressWarnings("unchecked")
        List<File> extractedFilesList = (List<File>) extractedList;
        Properties configurationAnalyzerSettings = context.getConfigurationAnalyzerSettings();
        for (File extractedFile : extractedFilesList) {
            if (XML_FILE_FILTER.accept(extractedFile)) {
                File base = extractedFile.getParentFile();
                //Now, we look for the for the schemas related to the file and get input streams to them
                ValidationResults validationResults = processSingleFile(extractedFile, base,
                        configurationAnalyzerSettings);
                if (validationResults != null && validationResults.getValidationErrorMessages().size() > 0) {
                    XMLNotValidAgainstXSDException xsdException = new XMLNotValidAgainstXSDException(
                            validationResults);
                    negativeValidationResults.add(xsdException);
                }
            } else if (extractedFile.isDirectory()) {
                //The extracted file is a directory, so we traverse it to look for XML files.
                File base = extractedFile.getParentFile();
                Collection<File> filesToLookAt = FileUtils.listFiles(extractedFile,
                        (IOFileFilter) XML_FILE_FILTER, TrueFileFilter.INSTANCE);
                for (File file : filesToLookAt) {
                    //Now, we look for the for the schemas related to the file and get input streams to them
                    ValidationResults validationResults = processSingleFile(file, base,
                            configurationAnalyzerSettings);
                    if (validationResults != null
                            && validationResults.getValidationErrorMessages().size() > 0) {
                        XMLNotValidAgainstXSDException xsdException = new XMLNotValidAgainstXSDException(
                                validationResults);
                        negativeValidationResults.add(xsdException);
                    }
                }
            }
        }
    }
    if (negativeValidationResults.size() > 0) {
        throw new IncorrectXMLFilesException(negativeValidationResults);
    }
}

From source file:com.silverpeas.admin.components.Instanciateur.java

static String getDescriptorFullPath(String componentName) throws IOException {
    IOFileFilter filter = new NameFileFilter(componentName + ".xml");
    List<File> list = new ArrayList<File>(
            FileUtils.listFiles(new File(xmlPackage), filter, TrueFileFilter.INSTANCE));
    if (!list.isEmpty()) {
        return list.get(0).getCanonicalPath();
    }//w w  w .j  a va 2  s.  co  m
    return new File(xmlPackage, componentName + ".xml").getCanonicalPath();
}

From source file:io.github.jeremgamer.editor.panels.Buttons.java

protected void updateList() {
    data.clear();//from  ww w  .java  2  s.c om
    File dir = new File("projects/" + Editor.getProjectName() + "/buttons");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    for (File file : FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) {
        if (file.getName().endsWith(".rbd"))
            data.addElement(file.getName().replace(".rbd", ""));
    }
    buttonList.setModel(data);
}

From source file:ai.h2o.servicebuilder.MakeWarServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Long startTime = System.currentTimeMillis();
    File tmpDir = null;//from   w w w .  j a  v  a  2 s .c  om
    try {
        //create temp directory
        tmpDir = createTempDirectory("makeWar");
        logger.info("tmpDir {}", tmpDir);

        //  create output directories
        File webInfDir = new File(tmpDir.getPath(), "WEB-INF");
        if (!webInfDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF)");
        File outDir = new File(webInfDir.getPath(), "classes");
        if (!outDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/classes)");
        File libDir = new File(webInfDir.getPath(), "lib");
        if (!libDir.mkdir())
            throw new Exception("Can't create output directory (WEB-INF/lib)");

        // get input files
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        String pojofile = null;
        String jarfile = null;
        String prejarfile = null;
        String deepwaterjarfile = null;
        String rawfile = null;
        String predictorClassName = null;
        String transformerClassName = null;
        ArrayList<String> pojos = new ArrayList<String>();
        ArrayList<String> rawfiles = new ArrayList<String>();
        for (FileItem i : items) {
            String field = i.getFieldName();
            String filename = i.getName();
            if (filename != null && filename.length() > 0) { // file fields
                if (field.equals("pojo")) {
                    pojofile = filename;
                    pojos.add(pojofile);
                    predictorClassName = filename.replace(".java", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added pojo model {}", filename);
                }
                if (field.equals("jar")) {
                    jarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("deepwater")) {
                    deepwaterjarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("prejar")) {
                    prejarfile = "WEB-INF" + File.separator + "lib" + File.separator + filename;
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(libDir, filename));
                }
                if (field.equals("mojo")) { // a raw model zip file, a mojo file
                    rawfile = filename;
                    rawfiles.add(rawfile);
                    predictorClassName = filename.replace(".zip", "");
                    FileUtils.copyInputStreamToFile(i.getInputStream(), new File(tmpDir, filename));
                    logger.info("added mojo model {}", filename);
                }
            } else { // form text field
                if (field.equals("preclass")) {
                    transformerClassName = i.getString();
                }
            }
        }
        logger.debug("genmodeljar {}  deepwaterjar {}  pojo {}  raw {}", jarfile, deepwaterjarfile, pojofile,
                rawfile);
        if ((pojofile == null || jarfile == null) && (rawfile == null || jarfile == null))
            throw new Exception("need either pojo and genmodel jar, or raw file and genmodel jar ");

        logger.info("prejar {}  preclass {}", prejarfile, transformerClassName);
        if (prejarfile != null && transformerClassName == null
                || prejarfile == null && transformerClassName != null)
            throw new Exception("need both prejar and preclass");

        if (pojofile != null) {
            // Compile the pojo
            String jarfiles = jarfile;
            if (deepwaterjarfile != null)
                jarfiles += ":" + deepwaterjarfile;
            runCmd(tmpDir,
                    Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source", JAVA_TARGET_VERSION,
                            "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp", jarfiles, "-d", outDir.getPath(),
                            pojofile),
                    "Compilation of pojo failed");
            logger.info("compiled pojo {}", pojofile);
        }

        if (servletPath == null)
            throw new Exception("servletPath is null");

        FileUtils.copyDirectoryToDirectory(new File(servletPath, "extra"), tmpDir);
        String extraPath = "extra" + File.separator;
        String webInfPath = extraPath + File.separator + "WEB-INF" + File.separator;
        String srcPath = extraPath + "src" + File.separator;

        if (transformerClassName == null)
            copyExtraFile(servletPath, extraPath, tmpDir, "index.html", "index.html");
        else
            copyExtraFile(servletPath, extraPath, tmpDir, "jarindex.html", "index.html");
        copyExtraFile(servletPath, extraPath, tmpDir, "jquery.js", "jquery.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "predict.js", "predict.js");
        copyExtraFile(servletPath, extraPath, tmpDir, "custom.css", "custom.css");
        copyExtraFile(servletPath, webInfPath, webInfDir, "web-predict.xml", "web.xml");
        FileUtils.copyDirectoryToDirectory(new File(servletPath, webInfPath + "lib"), webInfDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "bootstrap"), tmpDir);
        FileUtils.copyDirectoryToDirectory(new File(servletPath, extraPath + "fonts"), tmpDir);

        // change the class name in the predictor template file to the predictor we have
        String replaceTransform;
        if (transformerClassName == null)
            replaceTransform = "null";
        else
            replaceTransform = "new " + transformerClassName + "()";

        String modelCode = null;
        if (!pojos.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), pojos);
            modelCode = "null";
        } else if (!rawfiles.isEmpty()) {
            FileUtils.writeLines(new File(tmpDir, "modelnames.txt"), rawfiles);
            modelCode = "MojoModel.load(fileName)";
        }
        InstantiateJavaTemplateFile(tmpDir, modelCode, predictorClassName, replaceTransform, null,
                srcPath + "ServletUtil-TEMPLATE.java", "ServletUtil.java");

        copyExtraFile(servletPath, srcPath, tmpDir, "PredictServlet.java", "PredictServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PredictBinaryServlet.java", "PredictBinaryServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "InfoServlet.java", "InfoServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "StatsServlet.java", "StatsServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "PingServlet.java", "PingServlet.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Transform.java", "Transform.java");
        copyExtraFile(servletPath, srcPath, tmpDir, "Logging.java", "Logging.java");

        // compile extra
        List<String> cmd = Arrays.asList("javac", "-target", JAVA_TARGET_VERSION, "-source",
                JAVA_TARGET_VERSION, "-J-Xmx" + MEMORY_FOR_JAVA_PROCESSES, "-cp",
                "WEB-INF/lib/*:WEB-INF/classes:extra/WEB-INF/lib/*", "-d", outDir.getPath(),
                "PredictServlet.java", "PredictBinaryServlet.java", "InfoServlet.java", "StatsServlet.java",
                "ServletUtil.java", "PingServlet.java", "Transform.java", "Logging.java");
        runCmd(tmpDir, cmd, "Compilation of extra failed");

        // create the war jar file
        Collection<File> filesc = FileUtils.listFilesAndDirs(webInfDir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.add(new File(tmpDir, "index.html"));
        filesc.add(new File(tmpDir, "jquery.js"));
        filesc.add(new File(tmpDir, "predict.js"));
        filesc.add(new File(tmpDir, "custom.css"));
        filesc.add(new File(tmpDir, "modelnames.txt"));
        for (String m : pojos) {
            filesc.add(new File(tmpDir, m));
        }
        for (String m : rawfiles) {
            filesc.add(new File(tmpDir, m));
        }
        Collection<File> dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "bootstrap"),
                TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);
        dirc = FileUtils.listFilesAndDirs(new File(tmpDir, "fonts"), TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        filesc.addAll(dirc);

        File[] files = filesc.toArray(new File[] {});
        if (files.length == 0)
            throw new Exception("Can't list compiler output files (out)");

        byte[] resjar = createJarArchiveByteArray(files, tmpDir.getPath() + File.separator);
        if (resjar == null)
            throw new Exception("Can't create war of compiler output");
        logger.info("war created from {} files, size {}", files.length, resjar.length);

        // send jar back
        ServletOutputStream sout = response.getOutputStream();
        response.setContentType("application/octet-stream");
        String outputFilename = predictorClassName.length() > 0 ? predictorClassName : "h2o-predictor";
        response.setHeader("Content-disposition", "attachment; filename=" + outputFilename + ".war");
        response.setContentLength(resjar.length);
        sout.write(resjar);
        sout.close();
        response.setStatus(HttpServletResponse.SC_OK);

        Long elapsedMs = System.currentTimeMillis() - startTime;
        logger.info("Done war creation in {} ms", elapsedMs);
    } catch (Exception e) {
        logger.error("doPost failed ", e);
        // send the error message back
        String message = e.getMessage();
        if (message == null)
            message = "no message";
        logger.error(message);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.getWriter().write(message);
        response.getWriter().write(Arrays.toString(e.getStackTrace()));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } finally {
        // if the temp directory is still there we delete it
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                logger.error("Can't delete tmp directory");
            }
        }
    }

}

From source file:com.liferay.util.FileUtil.java

public static String[] listFiles(File dir, Boolean includeSubDirs) throws IOException {
    FileFilter fileFilter = new FileFilter() {
        public boolean accept(File file) {
            return file.isDirectory();
        }//  w  w  w .j a  v a2s  .c  o  m
    };
    File[] subFolders = dir.listFiles(fileFilter);

    List<String> files = new ArrayList<String>();

    List<File> fileArray = new ArrayList<File>(
            FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, includeSubDirs ? TrueFileFilter.INSTANCE : null));

    for (File file : fileArray) {
        if (file.isFile()) {
            if (includeSubDirs && containsParentFolder(file, subFolders)) {
                files.add(file.getParentFile().getName() + File.separator + file.getName());
            } else {
                files.add(file.getName());
            }
        }
    }

    return (String[]) files.toArray(new String[0]);
}

From source file:io.github.jeremgamer.editor.panels.Panels.java

protected void updateList() {
    data.clear();//  w w w.  ja va  2  s . c o  m
    File dir = new File("projects/" + Editor.getProjectName() + "/panels");
    if (!dir.exists()) {
        dir.mkdirs();
    }
    for (File file : FileUtils.listFiles(dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) {
        if (file.getName().endsWith(".rbd")) {
            data.addElement(file.getName().replace(".rbd", ""));
            mainPanel.addItem(file.getName().replace(".rbd", ""));
        }
    }
    panelList.setModel(data);
    try {
        gs.load(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
        mainPanel.setSelectedItem(gs.getString("mainPanel"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}