Example usage for java.io FilenameFilter FilenameFilter

List of usage examples for java.io FilenameFilter FilenameFilter

Introduction

In this page you can find the example usage for java.io FilenameFilter FilenameFilter.

Prototype

FilenameFilter

Source Link

Usage

From source file:net.jetrix.filter.DownstackPuzzleGenerator.java

/**
 * Find all levels in the puzzle directory.
 *//*  w  w  w.  ja  v  a 2  s.c  o  m*/
protected File[] getLevels() {
    File directory = new File(path);
    File[] files = directory.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".field");
        }
    });

    // sort the list of files

    Arrays.sort(files, new FilenameComparator());

    return files;
}

From source file:com.mc.printer.model.panel.client.paper.ReadSavedTask.java

public HashMap<String, List<SaveOject>> getLocalData() {
    String saveDir = Constants.SYSTEM_SAVE_PATH_DEFAULT;
    String path = System.getProperty(Constants.SYSTEM_SAVE_PATH_OPTION);
    if (path != null) {
        saveDir = path + File.separator;
    }//from www .j a v a 2  s.  co  m
    logger.debug("find path:" + saveDir);
    File file = new File(saveDir);
    if (file.exists()) {
        File[] files = file.listFiles(new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(Constants.SYSTEM_SAVE_SPLIT);
            }
        });

        for (File f : files) { //
            String fileName = f.getName();
            if (fileName.equalsIgnoreCase(formValueKey)) { //???
                String[] formandvalues = fileName.split("\\" + Constants.SYSTEM_SAVE_SPLIT);
                if (formandvalues.length > 1) { //1?form+ ?
                    logger.debug("collect data:" + fileName);
                    try {
                        SaveBean saveBean = new SaveBean();
                        XMLHelper<SaveBean> helper = new XMLHelper<SaveBean>(saveDir + fileName, saveBean);
                        saveBean = helper.read();
                        List<SaveOject> saveobjs = saveBean.getSaveObject();
                        if (saveobjs != null) {
                            logger.debug("get saved data,total:" + saveobjs.size());
                        }
                        HashMap<String, List<SaveOject>> map = new HashMap();
                        map.put("key", saveobjs);
                        return map;
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                    }

                }

            }

        }

    } else {
        logger.debug("no exist:" + saveDir);
    }
    return null;
}

From source file:gov.wa.wsdot.cms.utils.Migration.java

/**
 * Match all files in directory which are not xml files.
 *//*from  w  w w  .j  a  v  a  2  s  . c om*/
public static void matchResources(String archiveFolder) {
    File files[] = (new File(archiveFolder)).listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File archiveFolder, String name) {
            return name.matches(".*(?<!\\.xml)$");
        }
    });

    for (File file : files) {
        System.out.println("Found: " + file);
    }
}

From source file:com.hs.mail.imap.schedule.MessageCompressor.java

private void compressDirectory(File directory) {
    File[] files = directory.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.endsWith(DOT_GZIP_EXTENSION);
        }/* w  ww . j ava  2 s.co m*/
    });
    for (int i = 0; i < files.length; i++) {
        compressFile(files[i]);
    }
    FileUtils.createNewFile(new File(directory, COMPRESSED));
}

From source file:com.kegare.caveworld.world.WorldProviderDeepCaveworld.java

public static void regenerate(final boolean backup) {
    final File dir = getDimDir();
    final String name = dir.getName().substring(4);
    final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
    Set<EntityPlayerMP> target = Sets.newHashSet();

    for (Object obj : server.getConfigurationManager().playerEntityList.toArray()) {
        if (obj != null && ((EntityPlayerMP) obj).dimension == CaveworldAPI.getDeepDimension()) {
            target.add(CaveUtils.respawnPlayer((EntityPlayerMP) obj, 0));
        }/*from ww w . j  a  v a2  s .  c om*/
    }

    boolean result = new ForkJoinPool().invoke(new RecursiveTask<Boolean>() {
        @Override
        protected Boolean compute() {
            IChatComponent component;

            try {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerating", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                if (server.isSinglePlayer()) {
                    Caveworld.network.sendToAll(new RegenerateMessage(backup));
                }

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(0));

                CaveBlocks.caveworld_portal.portalDisabled = true;

                int dim = CaveworldAPI.getDeepDimension();
                WorldServer world = DimensionManager.getWorld(dim);

                if (world != null) {
                    world.saveAllChunks(true, null);
                    world.flush();

                    MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(world));

                    DimensionManager.setWorld(dim, null);
                }

                if (dir != null) {
                    if (backup) {
                        File parent = dir.getParentFile();
                        final Pattern pattern = Pattern.compile("^" + dir.getName() + "_bak-..*\\.zip$");
                        File[] files = parent.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String name) {
                                return pattern.matcher(name).matches();
                            }
                        });

                        if (files != null && files.length >= 5) {
                            Arrays.sort(files, new Comparator<File>() {
                                @Override
                                public int compare(File o1, File o2) {
                                    int i = CaveUtils.compareWithNull(o1, o2);

                                    if (i == 0 && o1 != null && o2 != null) {
                                        try {
                                            i = Files.getLastModifiedTime(o1.toPath())
                                                    .compareTo(Files.getLastModifiedTime(o2.toPath()));
                                        } catch (IOException e) {
                                        }
                                    }

                                    return i;
                                }
                            });

                            FileUtils.forceDelete(files[0]);
                        }

                        Calendar calendar = Calendar.getInstance();
                        String year = Integer.toString(calendar.get(Calendar.YEAR));
                        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
                        String day = String.format("%02d", calendar.get(Calendar.DATE));
                        String hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
                        String minute = String.format("%02d", calendar.get(Calendar.MINUTE));
                        String second = String.format("%02d", calendar.get(Calendar.SECOND));
                        File bak = new File(parent,
                                dir.getName() + "_bak-" + Joiner.on("").join(year, month, day) + "-"
                                        + Joiner.on("").join(hour, minute, second) + ".zip");

                        if (bak.exists()) {
                            FileUtils.deleteQuietly(bak);
                        }

                        component = new ChatComponentText(StatCollector
                                .translateToLocalFormatted("caveworld.regenerate.backingup", name));
                        component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                        server.getConfigurationManager().sendChatMsg(component);

                        Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(1));

                        if (CaveUtils.archiveDirZip(dir, bak)) {
                            ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_FILE,
                                    FilenameUtils.normalize(bak.getParentFile().getPath()));

                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backedup", name));
                            component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true)
                                    .setChatClickEvent(click);
                            server.getConfigurationManager().sendChatMsg(component);
                        } else {
                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backup.failed", name));
                            component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                            server.getConfigurationManager().sendChatMsg(component);
                        }
                    }

                    FileUtils.deleteDirectory(dir);
                }

                if (DimensionManager.shouldLoadSpawn(dim)) {
                    DimensionManager.initDimension(dim);

                    world = DimensionManager.getWorld(dim);

                    if (world != null) {
                        world.saveAllChunks(true, null);
                        world.flush();
                    }
                }

                CaveBlocks.caveworld_portal.portalDisabled = false;

                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerated", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(2));

                return true;
            } catch (Exception e) {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.failed", name));
                component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(3));

                CaveLog.log(Level.ERROR, e, component.getUnformattedText());
            }

            return false;
        }
    });

    if (result && (Config.hardcore || Config.caveborn)) {
        for (EntityPlayerMP player : target) {
            if (!CaveworldAPI.isEntityInCaveworld(player)) {
                CaveUtils.forceTeleport(player, CaveworldAPI.getDeepDimension());
            }
        }
    }
}

From source file:eu.edisonproject.classification.tfidf.mapreduce.TFIDFDriverImpl.java

/**
 *
 * @param inputPath/*  www  .  j a  va 2s .  c om*/
 */
public void executeTFIDF(String inputPath) {
    try {
        File items = new File(INPUT_ITEMSET);
        if (!items.exists()) {
            throw new IOException(items.getAbsoluteFile() + " not found");
        }

        String OUTPUT_PATH1 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-1-word-freq";

        if (items.length() < 200000000) {
            String AVRO_FILE = System.currentTimeMillis() + "_" + UUID.randomUUID() + "-TFIDFDriverImpl-avro";
            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "Starting text2Avro");
            text2Avro(inputPath, AVRO_FILE);

            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO,
                    "Starting WordFrequencyInDocDriver: {0},{1},{2},{3},{4}",
                    new Object[] { AVRO_FILE, OUTPUT_PATH1, INPUT_ITEMSET, NUM_OF_LINES, STOPWORDS_PATH });
            String[] args1 = { AVRO_FILE, OUTPUT_PATH1, INPUT_ITEMSET, STOPWORDS_PATH };
            ToolRunner.run(new WordFrequencyInDocDriver(), args1);
        } else {
            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "Starting TermWordFrequency");
            String[] args1 = { INPUT_ITEMSET, OUTPUT_PATH1, inputPath, STOPWORDS_PATH, NUM_OF_LINES };
            ToolRunner.run(new TermWordFrequency(), args1);
        }
        String OUTPUT_PATH2 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-2-word-counts";
        ;
        String[] args2 = { OUTPUT_PATH1, OUTPUT_PATH2 };
        ToolRunner.run(new WordCountsForDocsDriver(), args2);

        File docs = new File(inputPath);
        File[] files = docs.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".txt");
            }
        });
        Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "docs:{0}", docs.getAbsolutePath());
        int numberOfDocuments = files.length;
        String OUTPUT_PATH3 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-3-tf-idf";
        String[] args3 = { OUTPUT_PATH2, OUTPUT_PATH3, String.valueOf(numberOfDocuments) };
        ToolRunner.run(new WordsInCorpusTFIDFDriver(), args3);

        StringBuilder fileNames = new StringBuilder();
        String prefix = "";
        for (File name : files) {
            if (name.isFile() && FilenameUtils.getExtension(name.getName()).endsWith("txt")) {
                fileNames.append(prefix);
                prefix = ",";
                fileNames.append(FilenameUtils.removeExtension(name.getName()).replaceAll("_", ""));
            }
        }
        String OUTPUT_PATH4 = System.currentTimeMillis() + "_" + UUID.randomUUID()
                + "-TFIDFDriverImpl-4-distances";
        String[] args4 = { OUTPUT_PATH3, OUTPUT_PATH4, COMPETENCES_PATH, fileNames.toString() };
        Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "args4:{0}", Arrays.toString(args4));
        ToolRunner.run(new CompetencesDistanceDriver(), args4);

        Configuration conf = new Configuration();
        FileSystem fs = FileSystem.get(conf);
        Path hdfsRes = new Path(OUTPUT_PATH4);
        FileStatus[] results = fs.listStatus(hdfsRes);
        for (FileStatus s : results) {
            Path dest = new Path(OUT + "/" + s.getPath().getName());
            Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.INFO, "Copy: {0} to: {1}",
                    new Object[] { s.getPath(), dest });
            fs.copyToLocalFile(s.getPath(), dest);
        }
        fs.delete(hdfsRes, true);

    } catch (Exception ex) {
        Logger.getLogger(TFIDFDriverImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:fr.dudie.acrachilisync.utils.IssueDescriptionReaderTest.java

/**
 * Generates the test dataset.//from   ww w . java2 s .  co m
 * <p>
 * List all files under classpath:/files/description_[ko]{2}_.*.txt.
 * 
 * @return the test dataset
 * @throws URISyntaxException
 *             urisyntexception
 */
@Parameters
public static List<Object[]> data() throws URISyntaxException {

    final File files = new File(MD5UtilsTest.class.getResource("/files").toURI());
    final Pattern p = Pattern.compile("descriptionreader_[ko]{2}_.*\\.txt", Pattern.CASE_INSENSITIVE);
    final FilenameFilter filter = new FilenameFilter() {

        @Override
        public boolean accept(final File dir, final String name) {

            final Matcher m = p.matcher(name);
            return m.matches();
        }
    };

    final List<Object[]> data = new ArrayList<Object[]>();
    for (final File f : files.listFiles(filter)) {
        data.add(new Object[] { f, !f.getName().startsWith("descriptionreader_ok") });
    }
    return data;
}

From source file:de.undercouch.citeproc.TestSuiteRunner.java

/**
 * Runs tests/*from w w  w  .  j  a  va 2 s.  c om*/
 * @param f either a compiled test file (.json) to run or a directory
 * containing compiled test files
 * @param runnerType the type of the script runner that will be used
 * to execute all JavaScript code
 * @throws IOException if a file could not be loaded
 */
public void runTests(File f, RunnerType runnerType) throws IOException {
    ScriptRunnerFactory.setRunnerType(runnerType);
    {
        ScriptRunner sr = ScriptRunnerFactory.createRunner();
        System.out.println("Using script runner: " + sr.getName() + " " + sr.getVersion());
    }

    //find test files
    File[] testFiles;
    if (f.isDirectory()) {
        testFiles = f.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".json");
            }
        });
    } else {
        testFiles = new File[] { f };
    }

    AnsiConsole.systemInstall();
    try {
        long start = System.currentTimeMillis();
        int count = testFiles.length;
        int success = 0;

        ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

        //submit a job for each test file
        List<Future<Boolean>> fus = new ArrayList<Future<Boolean>>();
        for (File fi : testFiles) {
            fus.add(executor.submit(new TestCallable(fi)));
        }

        //receive results
        try {
            for (Future<Boolean> fu : fus) {
                if (fu.get()) {
                    ++success;
                }
            }
        } catch (Exception e) {
            //should never happen
            throw new RuntimeException(e);
        }

        executor.shutdown();

        //output total time
        long end = System.currentTimeMillis();
        double time = (end - start) / 1000.0;
        System.out.println("Successfully executed " + success + " of " + count + " tests.");
        System.out.println(String.format(Locale.ENGLISH, "Total time: %.3f secs", time));
    } finally {
        AnsiConsole.systemUninstall();
    }
}

From source file:functionaltests.scilab.AbstractScilabTest.java

protected void init() throws Exception {

    sci_tb_home = new File(System.getProperty("pa.scilab.home")).getCanonicalFile();

    test_home = resourceToFile("PrepareTest.sci").getParentFile();

    credFile = new File(test_home, "demo.cred");

    localhost = InetAddress.getLocalHost().getHostName();

    schedURI = new URI(SchedulerTHelper.getLocalUrl());

    // delete all db files
    File[] dbJobFiles = new File(TMPDIR).listFiles(new FilenameFilter() {
        @Override//w ww  . ja v a 2s  .  c  o m
        public boolean accept(File dir, String name) {
            if (name.startsWith(AOScilabEnvironment.MIDDLEMAN_JOBS_FILE_NAME)) {
                return true;
            } else if (name.startsWith(ScilabTaskRepository.SCILAB_EMBEDDED_JOBS_FILE_NAME)) {
                return true;
                // TODO : change below the value to JobDB.DEFAULT_STATUS_FILENAME
            } else if (name.startsWith("SmartProxy")) {
                return true;
            }
            return false;
        }
    });

    for (File f : dbJobFiles) {
        try {
            System.out.println("Deleting " + f);
            f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:forge.deck.io.DeckGroupSerializer.java

@Override
protected FilenameFilter getFileFilter() {
    return new FilenameFilter() {

        @Override/*from   www .  j ava 2 s. co m*/
        public boolean accept(final File dir, final String name) {
            final File testSubject = new File(dir, name);
            final boolean isVisibleFolder = testSubject.isDirectory() && !testSubject.isHidden();
            final boolean hasGoodName = StringUtils.isNotEmpty(name) && !name.startsWith(".");
            final File fileHumanDeck = new File(testSubject, DeckGroupSerializer.humanDeckFile);
            return isVisibleFolder && hasGoodName && fileHumanDeck.exists();
        }
    };
}