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

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

Introduction

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

Prototype

public WildcardFileFilter(List wildcards) 

Source Link

Document

Construct a new case-sensitive wildcard filter for a list of wildcards.

Usage

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rpict to run the simulation/*from ww  w.  j a v  a2s .com*/
 * @param config Radiance Configuration
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param args
 * @param model
 * @param in
 * @param out
 * @param err
 * @param png Switch for converting scene to jpg or not
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runRpict(RadianceConfig config, String WorkDir, String args, String model, String in,
        String out, String err, boolean png, ProcessWrapper process) {

    int ExitValue = -99;

    // Call rpict
    StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir());
    buf.append(File.separator).append("rpict");

    List<String> command = new ArrayList<>();
    command.add(buf.toString());
    String[] arglist = args.split("\\s+");
    command.addAll(Arrays.asList(arglist));
    command.add(model);
    try {
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir());
        builder.redirectError(new File(WorkDir + File.separator + err));
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing Rpict", ex);
    }

    if (png) {
        // Sweep everything with the same extension as out. This is for handling
        // -o option in rpict
        String ext = FilenameUtils.getExtension(out);
        File[] files = new File(WorkDir).listFiles((FileFilter) new WildcardFileFilter("*." + ext));
        for (File file : files) {
            String outname = file.getName();

            // Filter scene
            try {
                buf = new StringBuilder(config.getResolvedRadianceBinDir());
                buf.append(File.separator).append("pfilt");

                command = new ArrayList<>();
                command.add(buf.toString());
                // String [] arglist = "-1 -e -3".split("\\s+");
                // command.addAll(Arrays.asList(arglist));
                command.add(outname);
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.directory(new File(WorkDir));
                builder.environment().put("RAYPATH",
                        "." + File.pathSeparator + config.getResolvedRadianceLibDir());
                builder.redirectError(new File(WorkDir + File.separator + err));
                builder.redirectOutput(new File(WorkDir + File.separator + outname + ".flt"));
                Process proc = builder.start();
                ExitValue = proc.waitFor();
            } catch (IOException | InterruptedException ex) {
                logger.error("Error occoured when executing pfilt", ex);
            }

            // Convert to bmp
            try {
                buf = new StringBuilder(config.getResolvedRadianceBinDir());
                buf.append(File.separator).append("ra_bmp");

                command = new ArrayList<>();
                command.add(buf.toString());
                //String [] arglist = "-g 1.0".split("\\s+");
                //command.addAll(Arrays.asList(arglist));
                command.add(outname + ".flt");
                command.add(outname + ".bmp");
                ProcessBuilder builder = new ProcessBuilder(command);
                builder.directory(new File(WorkDir));
                builder.environment().put("RAYPATH",
                        "." + File.pathSeparator + config.getResolvedRadianceLibDir());
                builder.redirectError(
                        ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err)));
                Process proc = builder.start();
                ExitValue = proc.waitFor();
            } catch (IOException | InterruptedException ex) {
                logger.error("Error occoured when executing ra_bmp", ex);
            }

            // Convert to png
            BufferedImage input_image = null;
            try {
                input_image = ImageIO.read(new File(WorkDir + File.separator + outname + ".bmp")); //read bmp into input_image object
                File outputfile = new File(WorkDir + File.separator + outname + ".png"); //create new outputfile object
                ImageIO.write(input_image, "png", outputfile); //write PNG output to file 
            } catch (Exception ex) {
                logger.error("Error converting bmp to png.", ex);
            }

            // Remove flt and bmp
            new File(WorkDir + File.separator + outname + ".flt").delete();
            new File(WorkDir + File.separator + outname + ".bmp").delete();
        }
    }
    // Return Radiance exit value
    return ExitValue;
}

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 {//  w ww  .jav  a  2  s  . c  om
        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:com.mindquarry.desktop.workspace.SVNTestBase.java

/**
 * Finds all files with a given pattern that can include wildcards. Will
 * recurse into subdirectories. Similar to 'find DIR -name "PATTERN"' on a
 * unix command line.// w  ww.ja  v a 2  s. c  o m
 * 
 * Example: findFiles(dir, "*.java")
 * 
 * @param dir the directory to search for (including all subdirectories)
 * @param pattern a pattern that can contain "?" (single-char-wildcard) and
 *                "*" (multi-char-wildcard) as wildcards
 * @return an Iterator containing File objects for all found files
 */
@SuppressWarnings("unchecked")
public Iterator findFiles(File dir, String pattern) {
    return FileUtils.iterateFiles(dir, new WildcardFileFilter(pattern), TrueFileFilter.INSTANCE);
}

From source file:com.fiveamsolutions.nci.commons.mojo.copywebfiles.CopyWebFilesMojo.java

/**
 * @return//from   w  w w  .  j  a  va  2 s  .  com
 * @throws MojoExecutionException
 */
private Collection<File> getLatestDeploymentDirectories() throws MojoExecutionException {
    Set<File> matchSet = new HashSet<File>();
    File latestDeployDirectory = deployDirectory;
    if (StringUtils.isNotEmpty(deployDirectoryPattern)) {
        IOFileFilter fileFilter = new WildcardFileFilter(deployDirectoryPattern);
        fileFilter = FileFilterUtils.andFileFilter(DirectoryFileFilter.DIRECTORY, fileFilter);
        File[] matches = deployDirectory.listFiles((FileFilter) fileFilter);
        if (ArrayUtils.isEmpty(matches)) {
            throw new MojoExecutionException("No directories found that match the given pattern");
        }
        latestDeployDirectory = matches[0];
        for (File match : matches) {
            if (match.lastModified() > latestDeployDirectory.lastModified()) {
                latestDeployDirectory = match;
            }
            if (copyToAllMatches) {
                matchSet.add(match);
            }
        }
    }
    matchSet.add(latestDeployDirectory);
    return appendSubDirectory(matchSet);
}

From source file:info.fetter.logstashforwarder.FileWatcher.java

private void addWildCardFiles(String filesToWatch, Event fields, int deadTime) throws Exception {
    logger.info("Watching wildcard files : " + filesToWatch);
    String directory = FilenameUtils.getFullPath(filesToWatch);
    String wildcard = FilenameUtils.getName(filesToWatch);
    logger.trace("Directory : " + new File(directory).getCanonicalPath() + ", wildcard : " + wildcard);
    IOFileFilter fileFilter = FileFilterUtils.and(FileFilterUtils.fileFileFilter(),
            new WildcardFileFilter(wildcard), new LastModifiedFileFilter(deadTime));
    initializeWatchMap(new File(directory), fileFilter, fields);
}

From source file:de.dkfz.roddy.core.Analysis.java

/**
 * Creates a single execution context (similar to context(pidfilters...)) but does not execute it.
 * This method is mainly for ui based / asynchnronous execution context generation.
 * A separate thread is created which executes the context.
 *
 * @param pidFilter//  w  w  w .j  a va2 s.c  o  m
 * @param executionContextLevel
 * @return
 */
public ExecutionContext runDeferredContext(String pidFilter,
        final ExecutionContextLevel executionContextLevel) {
    long creationCheckPoint = System.nanoTime();
    for (DataSet ds : getRuntimeService().getListOfPossibleDataSets(this)) {
        if (!new WildcardFileFilter(pidFilter).accept(ds.getInputFolderForAnalysis(this)))
            continue;
        final ExecutionContext context = new ExecutionContext(
                FileSystemAccessProvider.getInstance().callWhoAmI(), this, ds, executionContextLevel,
                ds.getOutputFolderForAnalysis(this), ds.getInputFolderForAnalysis(this), null,
                creationCheckPoint);
        runDeferredContext(context);
        return context;
    }
    return null;
}

From source file:com.totsp.mavenplugin.gwt.scripting.ScriptWriterUnix16.java

/**
 * Write test scripts./*ww w  . j av  a  2  s .  c o  m*/
 */
public void writeTestScripts(AbstractGWTMojo mojo) throws MojoExecutionException {
    // get extras
    String extra = (mojo.getExtraJvmArgs() != null) ? mojo.getExtraJvmArgs() : "";

    if (AbstractGWTMojo.OS_NAME.startsWith("mac") && (extra.indexOf("-XstartOnFirstThread") == -1)) {
        extra = "-XstartOnFirstThread " + extra;
    }

    String testExtra = (mojo.getExtraTestArgs() != null) ? mojo.getExtraTestArgs() : "";

    // make sure output dir is present
    File outputDir = new File(mojo.getBuildDir(), "gwtTest");
    outputDir.mkdirs();
    outputDir.mkdir();

    // for each test compile source root, build a test script
    List<String> testCompileRoots = mojo.getProject().getTestCompileSourceRoots();

    for (String currRoot : testCompileRoots) {
        // TODO better file filter here
        Collection<File> coll = FileUtils.listFiles(new File(currRoot),
                new WildcardFileFilter(mojo.getTestFilter()), HiddenFileFilter.VISIBLE);

        for (File currFile : coll) {
            String testName = currFile.toString();
            mojo.getLog().debug(("gwtTest test match found (after filter applied) - " + testName));

            // parse off the extension
            if (testName.lastIndexOf('.') > testName.lastIndexOf(File.separatorChar)) {
                testName = testName.substring(0, testName.lastIndexOf('.'));
            }

            if (testName.startsWith(currRoot)) {
                testName = testName.substring(currRoot.length());
            }

            if (testName.startsWith(File.separator)) {
                testName = testName.substring(1);
            }

            testName = StringUtils.replace(testName, File.separatorChar, '.');
            mojo.getLog().debug("testName after parsing - " + testName);

            // start script inside gwtTest output dir, and name it with test class name
            File file = new File(mojo.getBuildDir() + File.separator + "gwtTest",
                    "gwtTest-" + testName + ".sh");
            PrintWriter writer = this.getPrintWriterWithClasspath(mojo, file, DependencyScope.TEST);

            // build Java command
            writer.print("\"" + mojo.getJavaCommand() + "\" ");

            if (extra.length() > 0) {
                writer.print(" " + extra + " ");
            }

            if (testExtra.length() > 0) {
                writer.print(" " + testExtra + " ");
            }

            writer.print(" -cp \"$CP\" ");
            writer.print("junit.textui.TestRunner ");
            writer.print(testName);

            // write script out
            writer.flush();
            writer.close();
            this.chmodUnixFile(file);
        }
    }
}

From source file:jeplus.EPlusWinTools.java

/**
 * Clean up working directory after simulation, based on the options to keep
 * working files and the list of files to delete.
 * @param workdir The working directory to be cleared
 * @param keepeplus Flag for keeping all EnergyPlus output files
 * @param keepjeplus Flag for keeping all intermediate jEPlus files
 * @param keepdir Flag for keeping the working directory
 * @param filesToDelete A [,;: ] separated list of file names to be deleted from the directory
 * @return Clean up successful or not. False is return if error occurs when deleting any file 
 *//*from w w  w.  j a  v a  2s. co m*/
public static boolean cleanupWorkDir(String workdir, boolean keepeplus, boolean keepjeplus, boolean keepdir,
        String filesToDelete) {
    boolean success = true;

    // Create the directory
    File dir = new File(workdir);
    if (dir.exists()) {
        if (!keepdir) {
            File[] files = dir.listFiles();
            for (File file : files) {
                file.delete();
            }
            success = dir.delete();
        } else {
            if (!keepjeplus) {
                File[] files = dir.listFiles(EPlusConfig.getIOFileFilter(EPlusConfig.JEPLUS_INTERM));
                for (File file : files) {
                    success &= file.delete();
                }
            }
            if (!keepeplus) {
                File[] files = dir.listFiles(EPlusConfig.getIOFileFilter(EPlusConfig.EPOUTPUT));
                for (File file : files) {
                    success &= file.delete();
                }
            }
        }
        if (filesToDelete != null) {
            String[] patterns = filesToDelete.split("\\s*[,;: ]\\s*");
            OrFileFilter filter = new OrFileFilter();
            for (String pattern : patterns) {
                filter.addFileFilter(new WildcardFileFilter(pattern));
            }
            File[] files = dir.listFiles((FileFilter) filter);
            for (File file : files) {
                success &= file.delete();
            }
        }
    }
    return success;
}

From source file:com.splout.db.engine.MySQLOutputFormat.java

@Override
public void close() throws IOException, InterruptedException {
    try {/* www .  jav  a2 s  .  com*/
        for (Map.Entry<Integer, Connection> entry : connCache.entrySet()) {
            LOG.info("Closing SQL connection [" + entry.getKey() + "]");
            //
            Connection conn = entry.getValue();
            Statement st = conn.createStatement();
            st.execute("COMMIT");
            if (getPostSQL() != null) {
                LOG.info("Executing end SQL statements.");
                for (String sql : getPostSQL()) {
                    LOG.info("Executing: " + sql);
                    st.execute(sql);
                }
            }
            st.close();
            conn.close();
            // close MySQL before copying files (so mysql.sock disappears!)
            EmbeddedMySQL msql = mySQLs.get(entry.getKey());

            msql.stop();
            File resident = msql.getConfig().getResidentFolder();
            File zipDest = new File(resident.getParentFile(), entry.getKey() + ".db");

            // Create a "partition.db" zip with the needed files.
            CompressorUtil.createZip(resident, zipDest,
                    new WildcardFileFilter(
                            new String[] { "ib*", "*.frm", "*.MYD", "*.MYI", "db.opt", "*.ibd" }),
                    FileFilterUtils.or(FileFilterUtils.nameFileFilter("data"),
                            FileFilterUtils.nameFileFilter("splout")));
            // Delete all files except the generated zip "partition.db"
            FileUtils.deleteDirectory(new File(resident, "bin"));
            FileUtils.deleteDirectory(new File(resident, "data"));
            FileUtils.deleteDirectory(new File(resident, "share"));
        }
    } catch (Exception e) {
        throw new IOException(e);
    } finally { // in any case, destroy the HeartBeater
        for (Map.Entry<Integer, EmbeddedMySQL> entry : mySQLs.entrySet()) {
            entry.getValue().stop();
        }
    }
}

From source file:hoot.services.controllers.ingest.BasemapResource.java

protected void _deleteBaseMap(String bmName) throws Exception {
    //List<String> delList = new ArrayList<String>();
    String controlFolder = _ingestStagingPath + "/BASEMAP/";
    String tileDirectoryPath = _tileServerPath + "/BASEMAP/" + bmName;

    File tileDir = new File(tileDirectoryPath);
    if (tileDir.exists()) {
        FileUtils.forceDelete(tileDir);/*from w w w  .  ja  v a 2 s .co m*/
    }

    File dir = new File(controlFolder);
    FileFilter fileFilter = new WildcardFileFilter(bmName + ".*");
    File[] files = dir.listFiles(fileFilter);
    for (int i = 0; i < files.length; i++) {
        File curFile = files[i];
        FileUtils.forceDelete(curFile);
        //delList.add(curFile.getPath());
    }

}