Example usage for org.apache.commons.io.filefilter FileFilterUtils prefixFileFilter

List of usage examples for org.apache.commons.io.filefilter FileFilterUtils prefixFileFilter

Introduction

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

Prototype

public static IOFileFilter prefixFileFilter(String prefix) 

Source Link

Document

Returns a filter that returns true if the filename starts with the specified text.

Usage

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

@Test
public void handlesOneFileMultipleReaders() throws InterruptedException, MalformedURLException {
    MockEndpoint first = getMockEndpoint("mock:endFirst");
    first.setExpectedMessageCount(1);/*from  ww w  .  j a va  2  s .  co  m*/
    first.expectedBodiesReceived("afile1.log");
    first.setResultWaitTime(TimeUnit.SECONDS.toMillis(15));
    first.setAssertPeriod(TimeUnit.SECONDS.toMillis(1));

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

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

    first.assertIsSatisfied();
    second.assertIsSatisfied();
    third.assertIsSatisfied();

    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.assertFalse(".camel1 exists", secondDirectory.exists());
    Assert.assertFalse(".camel2 exists", thirdDirectory.exists());

    Collection<File> firstFiles = FileUtils.listFiles(firstDirectory,
            FileFilterUtils.prefixFileFilter("afile1.log"), null);

    Assert.assertNotNull(firstFiles);

    //Directory should of only copied one file
    Assert.assertEquals(new Integer(1), new Integer(firstFiles.size()));
}

From source file:net.sf.firemox.xml.XmlConfiguration.java

/**
 * <ul>//from  ww w  . jav  a  2  s.c om
 * 2 modes:
 * <li>Update the a MDB for specified TBS against the XML files (main file,
 * cards and fragments). Arguments are : TBS_NAME</li>
 * <li>Rebuild completely the MDB for specified TBS. Arguments are : -full
 * TBS_NAME</li>
 * </ul>
 * 
 * @param args
 *          main arguments.
 */
public static void main(String... args) {
    options = new Options();
    final CmdLineParser parser = new CmdLineParser(options);
    try {
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        // Display help
        info(e.getMessage());
        parser.setUsageWidth(80);
        parser.printUsage(System.out);
        System.exit(-1);
        return;
    }

    if (options.isVersion()) {
        // Display version
        info("Version is " + IdConst.VERSION);
        System.exit(-1);
        return;
    }

    if (options.isHelp()) {
        // Display help
        parser.setUsageWidth(80);
        parser.printUsage(System.out);
        System.exit(-1);
        return;
    }

    warning = 0;
    uncompleted = 0;
    error = 0;
    long start = System.currentTimeMillis();
    XmlTools.initHashMaps();
    MToolKit.tbsName = options.getMdb();
    String xmlFile = MToolKit.getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + ".xml", false)
            .getAbsolutePath();
    try {
        if (options.isForce()) {
            final File recycledDir = MToolKit.getTbsFile("recycled");
            if (!recycledDir.exists() || !recycledDir.isDirectory()) {
                recycledDir.mkdir();
            }

            parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(),
                    new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false)));
        } else {
            // Check the up-to-date state of MDB
            final File file = MToolKit
                    .getFile(IdConst.TBS_DIR + "/" + MToolKit.tbsName + "/" + MToolKit.tbsName + ".mdb");
            final long lastModifiedMdb;
            if (file == null) {
                lastModifiedMdb = 0;
            } else {
                lastModifiedMdb = file.lastModified();
            }
            boolean update = false;
            // Check the up-to-date state of MDB against the main XML file
            if (MToolKit.getFile(xmlFile).lastModified() > lastModifiedMdb) {
                // The main XML file is newer than MDB
                System.out.println("MDB is out of date, " + xmlFile + " is newer");
                update = true;
            } else {
                final File fragmentDir = MToolKit.getTbsFile("");
                for (File frament : fragmentDir.listFiles(
                        (FilenameFilter) FileFilterUtils.andFileFilter(FileFilterUtils.suffixFileFilter("xml"),
                                FileFilterUtils.prefixFileFilter("fragment-")))) {
                    if (frament.lastModified() > lastModifiedMdb) {
                        // One card is newer than MDB
                        System.out.println(
                                "MDB is out of date, at least one fragment found : " + frament.getName());
                        update = true;
                        break;
                    }
                }
                if (!update) {
                    // Check the up-to-date state of MDB against the cards
                    final File recycledDir = MToolKit.getTbsFile("recycled");
                    if (!recycledDir.exists() || !recycledDir.isDirectory()) {
                        recycledDir.mkdir();
                    }
                    if (recycledDir.lastModified() > lastModifiedMdb) {
                        // The recycled XML file is newer than MDB
                        System.out.println("MDB is out of date, the recycled directory is new");
                        update = true;
                    } else {
                        for (File card : recycledDir.listFiles((FilenameFilter) FileFilterUtils.andFileFilter(
                                FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.notFileFilter(
                                        FileFilterUtils.suffixFileFilter(IdConst.FILE_DATABASE_SAVED))))) {
                            if (card.lastModified() > lastModifiedMdb) {
                                // One card is newer than MDB
                                System.out.println("MDB is out of date, at least one new card found : " + card);
                                update = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (!update) {
                return;
            }
            // Need to update the whole MDB
            parseRules(xmlFile, MToolKit.getTbsFile("recycled").getAbsolutePath(),
                    new FileOutputStream(MToolKit.getTbsFile(MToolKit.tbsName + ".mdb", false)));
        }
    } catch (SAXParseException e) {
        // Ignore this error
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (warning > 0) {
        System.out.println("\t" + warning + " warning" + (warning > 1 ? "s" : ""));
    }
    if (error > 0) {
        System.out.println("\t" + error + " error" + (error > 1 ? "s" : ""));
        System.out.println("Some cards have not been built correctly. Fix them.");
    } else {
        System.out.println("\tSuccessfull build");
    }
    System.out.println("\tTime : " + (System.currentTimeMillis() - start) / 1000 + " s");
}

From source file:com.data2semantics.yasgui.server.db.ConnectionFactory.java

private static void applyDeltas(Connection connect, File configDir)
        throws UnsupportedEncodingException, IOException, SQLException {
    @SuppressWarnings("unchecked")
    ArrayList<File> listFiles = new ArrayList<File>(
            FileUtils.listFiles(new File(configDir.getAbsolutePath() + "/config"),
                    FileFilterUtils.prefixFileFilter("delta_"), null));

    TreeMap<Integer, File> files = new TreeMap<Integer, File>();
    for (File file : listFiles) {
        String basename = file.getName();
        basename = basename.substring("delta_".length());
        basename = basename.substring(0, basename.length() - ".sql".length());
        int index = Integer.parseInt(basename);
        files.put(index, file);//from w  w w .j ava2s. c om
    }
    ArrayList<Integer> currentDeltas = getDeltas(connect);
    //treemap is naturally sorted, so just iterate through them
    for (Entry<Integer, File> entry : files.entrySet()) {
        if (!currentDeltas.contains(entry.getKey())) {
            ScriptRunner runner = new ScriptRunner(connect, false, true);
            FileInputStream fileStream = new FileInputStream(entry.getValue());
            runner.runScript(new BufferedReader(new InputStreamReader(fileStream, "UTF-8")));
            fileStream.close();
            setDeltaApplied(connect, entry.getKey());
        }

    }
}

From source file:architecture.ee.web.logo.DefaultLogoManager.java

private void deleteImageFileCache(LogoImage image) {
    Collection<File> files = FileUtils.listFiles(getImageCacheDir(),
            FileFilterUtils.prefixFileFilter(image.getLogoId().toString()),
            FileFilterUtils.suffixFileFilter(".logo"));
    for (File file : files) {
        log.debug(file.getPath() + ":" + file.isFile());
        try {/*from  w w w.  j  a v a  2s .c o m*/
            FileUtils.forceDelete(file);
        } catch (IOException e) {
            log.error(e);
        }
    }

}

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public Attachment saveAttachment(Attachment attachment) {

    Date now = new Date();
    Attachment attachmentToUse = attachment;
    if (attachmentToUse.getAttachmentId() > 0) {
        attachmentCache.remove(attachmentToUse.getAttachmentId());
        attachmentToUse.setModifiedDate(now);
        attachmentDao.updateAttachment(attachmentToUse);

        attachmentCache.remove(attachmentToUse.getAttachmentId());

    } else {/*from   w  ww.j  a  v a2s. c o m*/
        attachmentToUse.setCreationDate(now);
        attachmentToUse.setModifiedDate(now);
        attachmentToUse = attachmentDao.createAttachment(attachmentToUse);
    }
    try {
        if (attachmentToUse.getInputStream() != null) {
            attachmentDao.saveAttachmentData(attachmentToUse, attachmentToUse.getInputStream());
            Collection<File> files = FileUtils.listFiles(getAttachmentCacheDir(),
                    FileFilterUtils.prefixFileFilter(attachment.getAttachmentId() + ""), null);
            for (File file : files) {
                FileUtils.deleteQuietly(file);
            }
        }

        return getAttachment(attachment.getAttachmentId());
    } catch (Exception e) {
        throw new SystemException(e);
    }
}

From source file:architecture.ee.web.community.profile.DefaultProfileManager.java

private void deleteImageFileCache(ProfileImage image) {

    Collection<File> files = FileUtils.listFiles(getImageCacheDir(),
            FileFilterUtils.prefixFileFilter(image.getProfileImageId().toString()),
            FileFilterUtils.suffixFileFilter(".profile"));
    for (File file : files) {
        log.debug(file.getPath() + ":" + file.isFile());
        try {//from www.j  a  va 2s  .c o  m
            FileUtils.forceDelete(file);
        } catch (IOException e) {
            log.error(e);
        }
    }

}

From source file:architecture.ee.web.attachment.DefaultImageManager.java

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
public void saveOrUpdate(Image image) {
    try {//from w  w w. j a  v a2s  .  co m
        if (image.getImageId() <= 0) {
            imageDao.createImage(image);
            imageDao.saveImageInputStream(image, image.getInputStream());
        } else {
            Date now = new Date();
            ((ImageImpl) image).setModifiedDate(now);
            imageDao.updateImage(image);
            imageDao.saveImageInputStream(image, image.getInputStream());
        }

        Collection<File> files = FileUtils.listFiles(getImageCacheDir(),
                FileFilterUtils.prefixFileFilter(image.getImageId() + ""), null);
        for (File file : files) {
            FileUtils.forceDelete(file);
        }
        Image imageToUse = getImage(image.getImageId());
        imageCache.remove(imageToUse.getImageId());
    } catch (Exception e) {
        throw new SystemException(e);
    }
}

From source file:architecture.ee.web.attachment.DefaultImageManager.java

private void deleteImageFileCache(Image image) {
    Collection<File> files = FileUtils.listFiles(getImageCacheDir(),
            FileFilterUtils.prefixFileFilter(String.valueOf(image.getImageId())),
            FileFilterUtils.suffixFileFilter(".bin"));
    for (File file : files) {
        log.debug(file.getPath() + ":" + file.isFile());
        try {//from  w ww.j ava 2s  .c  o m
            FileUtils.forceDelete(file);
        } catch (IOException e) {
            log.error(e);
        }
    }

}

From source file:kr.co.leem.system.FileSystemUtils.java

/**
 *  .//from  w  ww. j  a  v  a 2  s .c  o  m
 *
 * @param srcDir ?  .
 * @param destDir   .
 * @param name .
 * @param fileNameSearch .
 * @param preserveFileDate   .
 * @see FileUtils#copyDirectory(File, File, FileFilter, boolean)
 * @see FileFilterUtils#nameFileFilter(long, long)
 * @see FileFilterUtils#prefixFileFilter(String)
 * @see FileFilterUtils#suffixFileFilter(String)
 * @see FileFilterUtils#or(IOFileFilter, IOFileFilter)
 */
public static void copyDirectory(final String srcDir, final String destDir, final String name,
        final searchFileName fileNameSearch, final boolean preserveFileDate) {
    processIO(new IOCallback<Object>() {
        public Object doInProcessIO() throws IOException, NullPointerException, IllegalArgumentException {
            IOFileFilter fileFilter;
            switch (fileNameSearch) {
            case FULL_MATCH:
                fileFilter = FileFilterUtils.nameFileFilter(name);
                break;
            case PREFIX:
                fileFilter = FileFilterUtils.prefixFileFilter(name);
                break;
            case SUFFIX:
                fileFilter = FileFilterUtils.suffixFileFilter(name);
                break;
            default:
                fileFilter = FileFilterUtils.nameFileFilter(name);
                break;
            }

            IOFileFilter fileNameFiles = FileFilterUtils.or(DirectoryFileFilter.DIRECTORY, fileFilter);
            FileUtils.copyDirectory(new File(srcDir), new File(destDir), fileNameFiles, preserveFileDate);
            return null;
        }
    });
}

From source file:com.isomorphic.maven.mojo.AbstractPackagerMojo.java

/**
 * Download the specified distributions, if necessary, extract resources from them, and use the results to create Maven artifacts as appropriate:
 * <p/>/*from   w  w  w .  j a v a2  s.c o  m*/
 * Try to install all of the main artifacts - e.g., those found in lib/*.jar and assembly/*.zip <br/>
 * Try to match main artifacts to 'subartifacts' by name and attach them (with classifiers as necessary)
 * 
 * @param downloads The list of licenses top be included in the distribution.  Multiple licenses are only allowed to support the inclusion of optional modules.
 * @param basedir The directory into which results should be written
 * @return A collection of Maven artifacts resulting from the download and preparation of a supported Isomorphic SDK.
 * @throws MojoExecutionException When any fatal error occurs.
 */
private Set<Module> collect(List<License> downloads, File basedir) throws MojoExecutionException {

    //allow execution to proceed without login credentials - it may be that they're not required
    Server server = settings.getServer(serverId);
    String username = null;
    String password = null;
    if (server != null) {
        username = server.getUsername();
        password = server.getPassword();
    } else {
        LOGGER.warn("No server configured with id '{}'.  Will be unable to authenticate.", serverId);
    }

    UsernamePasswordCredentials credentials = null;
    if (username != null) {
        credentials = new UsernamePasswordCredentials(username, password);
    }

    File downloadTo = new File(basedir, "zip");
    downloadTo.mkdirs();

    Downloads downloadManager = new Downloads(credentials);
    downloadManager.setToFolder(downloadTo);
    downloadManager.setProxyConfiguration(settings.getActiveProxy());
    downloadManager.setOverwriteExistingFiles(overwrite);

    File[] existing = downloadTo.listFiles();
    List<Distribution> distributions = new ArrayList<Distribution>();
    try {
        if (!skipDownload) {
            distributions.addAll(
                    downloadManager.fetch(product, buildNumber, buildDate, downloads.toArray(new License[0])));
        } else if (existing != null) {
            LOGGER.info("Creating local distribution from '{}'", downloadTo.getAbsolutePath());
            Distribution distribution = Distribution.get(product, license, buildNumber, buildDate);
            distribution.getFiles().addAll(Arrays.asList(existing));
            distributions.add(distribution);
        }

        if (!skipExtraction) {
            LOGGER.info("Unpacking downloaded file/s to '{}'", basedir);
            for (Distribution distribution : distributions) {
                distribution.unpack(basedir);
            }
        }

        //it doesn't strictly read this way, but we're looking for lib/*.jar, pom/*.xml, assembly/*.zip
        //TODO it'd be better if this didn't have to know where the files were located after unpacking
        Collection<File> files = FileUtils.listFiles(basedir,
                FileFilterUtils.or(FileFilterUtils.suffixFileFilter("jar"),
                        FileFilterUtils.suffixFileFilter("xml"), FileFilterUtils.suffixFileFilter("zip")),
                FileFilterUtils.or(FileFilterUtils.nameFileFilter("lib"), FileFilterUtils.nameFileFilter("pom"),
                        FileFilterUtils.nameFileFilter("assembly")));

        if (files.isEmpty()) {
            throw new MojoExecutionException(String.format(
                    "There don't appear to be any files to work with at '%s'.  Check earlier log entries for clues.",
                    basedir.getAbsolutePath()));
        }

        Set<Module> result = new TreeSet<Module>();
        for (File file : files) {
            try {

                String base = FilenameUtils.getBaseName(file.getName().replaceAll("_", "-"));

                //poms don't need anything else
                if ("xml".equals(FilenameUtils.getExtension(file.getName()))) {
                    result.add(new Module(getModelFromFile(file)));
                    continue;
                }

                //for each jar/zip, find the matching pom
                IOFileFilter filter = new WildcardFileFilter(base + ".pom");
                Collection<File> poms = FileUtils.listFiles(basedir, filter, TrueFileFilter.INSTANCE);
                if (poms.size() != 1) {
                    LOGGER.warn(
                            "Expected to find exactly 1 POM matching artifact with name '{}', but found {}.  Skpping installation.",
                            base, poms.size());
                    continue;
                }

                Model model = getModelFromFile(poms.iterator().next());
                Module module = new Module(model, file);

                /*
                 * Find the right javadoc bundle, matched on prefix.  e.g., 
                 *       smartgwt-eval -> smartgwt-javadoc
                 *       isomorphic-core-rpc -> isomorphic-javadoc
                 * and add it to the main artifact with the javadoc classifier.  This seems appropriate as long as
                 *       a) there is no per-jar javadoc
                 *       b) naming conventions are adhered to (or can be corrected by plugin at extraction)
                 */
                int index = base.indexOf("-");
                String prefix = base.substring(0, index);

                Collection<File> doc = FileUtils.listFiles(new File(basedir, "doc"),
                        FileFilterUtils.prefixFileFilter(prefix), FileFilterUtils.nameFileFilter("lib"));

                if (doc.size() != 1) {
                    LOGGER.debug("Found {} javadoc attachments with prefix '{}'.  Skipping attachment.",
                            doc.size(), prefix);
                } else {
                    module.attach(doc.iterator().next(), "javadoc");
                }

                result.add(module);
            } catch (ModelBuildingException e) {
                throw new MojoExecutionException("Error building model from POM", e);
            }
        }
        return result;
    } catch (IOException e) {
        throw new MojoExecutionException("Failure during assembly collection", e);
    }
}