Example usage for java.io File exists

List of usage examples for java.io File exists

Introduction

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

Prototype

public boolean exists() 

Source Link

Document

Tests whether the file or directory denoted by this abstract pathname exists.

Usage

From source file:com.axiomine.largecollections.generator.GeneratorPrimitiveSet.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];// w ww  .  j a v a 2  s  .  c o  m
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "Set";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/PrimitiveSetTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorWritableList.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];//w w w . j  a v  a2s.c om
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "List";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/WritableListTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.axiomine.largecollections.generator.GeneratorWritableSet.java

public static void main(String[] args) throws Exception {
    //Package of the new class you are generating Ex. com.mypackage
    String MY_PACKAGE = args[0];/*from ww w.jav  a  2 s. c om*/
    //Any custom imports you need (: seperated). Use - if no custom imports are included
    //Ex. java.util.*:java.lang.Random     
    String CUSTOM_IMPORTS = args[1].equals("-") ? "" : args[1];
    //Package of your Key serializer class. Use com.axiomine.bigcollections.functions
    String T = args[2];

    String tCls = T;

    if (tCls.equals("byte[]")) {
        tCls = "BytesArray";
    }
    String CLASS_NAME = tCls + "Set";
    File root = new File("");
    File outFile = new File(root.getAbsolutePath() + "/src/main/java/" + MY_PACKAGE.replaceAll("\\.", "/") + "/"
            + CLASS_NAME + ".java");

    if (outFile.exists()) {
        System.out.println(outFile.getAbsolutePath() + " already exists. Please delete it and try again");
    }
    {
        String[] imports = null;
        String importStr = "";

        if (!StringUtils.isBlank(CUSTOM_IMPORTS)) {
            CUSTOM_IMPORTS.split(":");
            for (String s : imports) {
                importStr = "import " + s + ";\n";
            }
        }

        String program = FileUtils.readFileToString(
                new File(root.getAbsolutePath() + "/src/main/resources/WritableSetTemplate.java"));

        program = program.replaceAll("#MY_PACKAGE#", MY_PACKAGE);
        program = program.replaceAll("#CUSTOM_IMPORTS#", importStr);

        program = program.replaceAll("#CLASS_NAME#", CLASS_NAME);
        program = program.replaceAll("#T#", T);
        program = program.replaceAll("#TCLS#", tCls);

        System.out.println(outFile.getAbsolutePath());
        FileUtils.writeStringToFile(outFile, program);
    }
}

From source file:com.guye.baffle.obfuscate.Main.java

public static void main(String[] args) throws IOException, BaffleException {
    Options opt = new Options();

    opt.addOption("c", "config", true, "config file path,keep or mapping");

    opt.addOption("o", "output", true, "output mapping writer file");

    opt.addOption("v", "verbose", false, "explain what is being done.");

    opt.addOption("h", "help", false, "print help for the command.");

    opt.getOption("c").setArgName("file list");

    opt.getOption("o").setArgName("file path");

    String formatstr = "baffle [-c/--config filepaths list ][-o/--output filepath][-h/--help] ApkFile TargetApkFile";

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new PosixParser();
    CommandLine cl = null;//from   w ww  . ja va2  s .  com
    try {
        // ?Options?
        cl = parser.parse(opt, args);

    } catch (ParseException e) {
        formatter.printHelp(formatstr, opt); // ???
        return;
    }

    if (cl == null || cl.getArgs() == null || cl.getArgs().length == 0) {
        formatter.printHelp(formatstr, opt);
        return;
    }

    // ?-h--help??
    if (cl.hasOption("h")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp(formatstr, "", opt, "");
        return;
    }

    // ???DirectoryName
    String[] str = cl.getArgs();
    if (str == null || str.length != 2) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("not specify apk file or taget apk file", opt);
        return;
    }

    if (str[1].equals(str[0])) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file can not rewrite , please specify new target file", opt);
        return;
    }
    File apkFile = new File(str[0]);
    if (!apkFile.exists()) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("apk file not exists", opt);
        return;
    }

    File[] configs = null;
    if (cl.hasOption("c")) {
        String cfg = cl.getOptionValue("c");
        String[] fs = cfg.split(",");
        int len = fs.length;
        configs = new File[fs.length];
        for (int i = 0; i < len; i++) {
            configs[i] = new File(fs[i]);
            if (!configs[i].exists()) {
                HelpFormatter hf = new HelpFormatter();
                hf.printHelp("config file " + fs[i] + " not exists", opt);
                return;
            }
        }
    }

    File mappingfile = null;
    if (cl.hasOption("o")) {
        String mfile = cl.getOptionValue("o");
        mappingfile = new File(mfile);

        if (mappingfile.getParentFile() != null) {
            mappingfile.getParentFile().mkdirs();
        }

    }

    if (cl.hasOption('v')) {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.CONFIG);
    } else {
        Logger.getLogger(Obfuscater.LOG_NAME).setLevel(Level.OFF);
    }

    Logger.getLogger(Obfuscater.LOG_NAME).addHandler(new ConsoleHandler());

    Obfuscater obfuscater = new Obfuscater(configs, mappingfile, apkFile, str[1]);

    obfuscater.obfuscate();
}

From source file:gemlite.core.commands.WServer.java

public static void main(String[] args2) throws Exception {
    String[] defaultArgs = new String[] { "D:/work/data/Gemlite-demo/target/Gemlite-demo-0.0.1-SNAPSHOT.war",
            "8082", "/" };
    defaultArgs = args2 == null || args2.length == 0 ? defaultArgs : args2;
    ServerConfigHelper.initConfig();//from   w  w  w  . ja v  a 2 s  .co  m
    ServerConfigHelper.initLog4j("classpath:log4j2-server.xml");
    ServerConfigHelper.setProperty("bind-address", ServerConfigHelper.getConfig(ITEMS.BINDIP));
    int port = 8080;
    String contextPath = "/";
    String warPath = "";
    if (defaultArgs.length < 1) {
        LogUtil.getCoreLog().error(
                "Start error,plelase Start Ws server like this : java gemlite.core.command.WServer /home/ws.war");
        return;
    }

    warPath = defaultArgs[0];
    File file = new File(warPath);
    if (!file.exists()) {
        LogUtil.getCoreLog().error("Error input:" + defaultArgs[0] + " war path is not existing!");
        return;
    }
    if (!file.isFile()) {
        LogUtil.getCoreLog().error("Error input:" + defaultArgs[0] + " war path is not a valid file!");
        return;
    }

    if (defaultArgs.length > 1) {
        port = NumberUtils.toInt(defaultArgs[1]);
        if (port <= 0 || port >= 65535) {
            LogUtil.getCoreLog().error(
                    "Port Error:" + defaultArgs[1] + ",not a valid port , make sure port>0 and port<65535");
            return;
        }
    }

    if (defaultArgs.length > 2) {
        contextPath += StringUtils.replace(defaultArgs[2], "/", "");
    }

    try {
        // jetty_home
        String jetty_home = ServerConfigHelper.getConfig(ITEMS.GS_WORK) + File.separator + "jetty_home";
        jetty_home += File.separator + StringUtils.replace(contextPath, "/", "") + port;
        File jfile = new File(jetty_home);
        jfile.mkdirs();
        System.setProperty("jetty.home", jetty_home);
        String jetty_logs = jetty_home + File.separator + "logs" + File.separator;
        File logsFile = new File(jetty_logs);
        logsFile.mkdirs();
        System.setProperty("jetty.logs", jetty_logs);

        Server server = new Server();
        HttpConfiguration config = new HttpConfiguration();
        ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(config));
        connector.setReuseAddress(true);
        connector.setIdleTimeout(30000);
        connector.setPort(port);
        server.addConnector(connector);

        WebAppContext webapp = new WebAppContext();
        webapp.setContextPath(contextPath);
        webapp.setWar(warPath);
        String tmpStr = jetty_home + File.separator + "webapps" + File.separator;
        File tmpDir = new File(tmpStr);
        tmpDir.mkdirs();
        webapp.setTempDirectory(tmpDir);

        // ???
        // webapp.setExtraClasspath(extrapath);
        webapp.setParentLoaderPriority(true);

        // ?Log
        RequestLogHandler requestLogHandler = new RequestLogHandler();
        NCSARequestLog requestLog = new NCSARequestLog(
                jetty_logs + File.separator + "jetty-yyyy_mm_dd.request.log");
        requestLog.setRetainDays(30);
        requestLog.setAppend(true);
        requestLog.setExtended(false);
        requestLog.setLogTimeZone(TimeZone.getDefault().getID());
        requestLogHandler.setRequestLog(requestLog);
        webapp.setHandler(requestLogHandler);

        ContextHandler ch = webapp.getServletContext().getContextHandler();
        ch.setLogger(new Slf4jLog("gemlite.coreLog"));
        server.setHandler(webapp);
        server.start();

        System.out.println("-----------------------------------------------------");
        LogUtil.getCoreLog().info("Ws Server started,You can visite -> http://"
                + ServerConfigHelper.getConfig(ITEMS.BINDIP) + ":" + port + contextPath);

        server.join();

    } catch (Exception e) {
        LogUtil.getCoreLog().error("Ws Server error:", e);
    }
}

From source file:DruidResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
        post.addHeader("content-type", "application/json");
        CloseableHttpResponse res;//from   ww w.j a va2  s.c o m

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{" + "\"queryType\":\"timeseries\","
                + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"],"
                + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BYTE_BUFFER);
                valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) {
                length = reader.read(CHAR_BUFFER);
                post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length)));
            }

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            for (int j = 0; j < TEST_ROUND; j++) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                if (STORE_RESULT && j == 0) {
                    try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
                            BufferedWriter writer = new BufferedWriter(
                                    new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) {
                        while ((length = in.read(BYTE_BUFFER)) > 0) {
                            writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8"));
                        }
                    }
                }
                res.close();
                time[j] = (int) (endTime - startTime);
                totalTime += time[j];
                System.out.print(time[j] + "ms ");
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:com.act.lcms.db.io.LoadConstructAnalysisTableIntoDB.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption(Option.builder("i").argName("path").desc("The TSV file to read").hasArg().required()
            .longOpt("input-file").build());

    // DB connection options.
    opts.addOption(Option.builder().argName("database url")
            .desc("The url to use when connecting to the LCMS db").hasArg().longOpt("db-url").build());
    opts.addOption(Option.builder("u").argName("database user").desc("The LCMS DB user").hasArg()
            .longOpt("db-user").build());
    opts.addOption(Option.builder("p").argName("database password").desc("The LCMS DB password").hasArg()
            .longOpt("db-pass").build());
    opts.addOption(Option.builder("H").argName("database host")
            .desc(String.format("The LCMS DB host (default = %s)", DB.DEFAULT_HOST)).hasArg().longOpt("db-host")
            .build());//  ww w .  ja v  a  2 s  .  c  o  m
    opts.addOption(Option.builder("P").argName("database port")
            .desc(String.format("The LCMS DB port (default = %d)", DB.DEFAULT_PORT)).hasArg().longOpt("db-port")
            .build());
    opts.addOption(Option.builder("N").argName("database name")
            .desc(String.format("The LCMS DB name (default = %s)", DB.DEFAULT_DB_NAME)).hasArg()
            .longOpt("db-name").build());

    // Everybody needs a little help from their friends.
    opts.addOption(
            Option.builder("h").argName("help").desc("Prints this help message").longOpt("help").build());

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true);
        return;
    }

    File inputFile = new File(cl.getOptionValue("input-file"));
    if (!inputFile.exists()) {
        System.err.format("Unable to find input file at %s\n", cl.getOptionValue("input-file"));
        new HelpFormatter().printHelp(LoadConstructAnalysisTableIntoDB.class.getCanonicalName(), opts, true);
        System.exit(1);
    }

    DB db;

    if (cl.hasOption("db-url")) {
        db = new DB().connectToDB(cl.getOptionValue("db-url"));
    } else {
        Integer port = null;
        if (cl.getOptionValue("P") != null) {
            port = Integer.parseInt(cl.getOptionValue("P"));
        }
        db = new DB().connectToDB(cl.getOptionValue("H"), port, cl.getOptionValue("N"), cl.getOptionValue("u"),
                cl.getOptionValue("p"));
    }

    try {
        db.getConn().setAutoCommit(false);

        ConstructAnalysisFileParser parser = new ConstructAnalysisFileParser();
        parser.parse(inputFile);

        List<Pair<Integer, DB.OPERATION_PERFORMED>> results = ChemicalAssociatedWithPathway
                .insertOrUpdateChemicalsAssociatedWithPathwayFromParser(db, parser);
        if (results != null) {
            for (Pair<Integer, DB.OPERATION_PERFORMED> r : results) {
                System.out.format("%d: %s\n", r.getLeft(), r.getRight());
            }
        }
        // If we didn't encounter an exception, commit the transaction.
        db.getConn().commit();
    } catch (Exception e) {
        System.err.format("Caught exception when trying to load plate composition, rolling back. %s\n",
                e.getMessage());
        db.getConn().rollback();
        throw (e);
    } finally {
        db.getConn().close();
    }

}

From source file:com.twentyn.patentTextProcessor.WordCountProcessor.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();// w w w .j a  v  a2 s . c o  m
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to score").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("WordCountProcessor", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    WordCountProcessor wcp = new WordCountProcessor();
    PatentCorpusReader corpusReader = new PatentCorpusReader(wcp, splitFileOrDir);
    corpusReader.readPatentCorpus();
}

From source file:org.mzd.shap.spring.cli.ConfigSetup.java

public static void main(String[] args) {
    // check args
    if (args.length != 1) {
        exitOnError(1, null);/*  w  w  w  .  j a v  a 2 s.  c  om*/
    }

    // check file existance
    File analyzerXML = new File(args[0]);
    if (!analyzerXML.exists()) {
        exitOnError(1, "'" + analyzerXML.getPath() + "' did not exist\n");
    }

    // prompt user whether existing data should be purged
    boolean isPurged = false;
    String ormContext = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    try {
        System.out.println("\nDo you wish to purge the database before running setup?");
        System.out.println("WARNING: all existing data in SHAP will be lost!");
        System.out.println("Really purge? yes/[NO]");
        String ans = br.readLine();
        if (ans.toLowerCase().equals("yes")) {
            System.out.println("Purging enabled");
            ormContext = "orm-purge-context.xml";
            isPurged = true;
        } else {
            System.out.println("Purging disabled");
            ormContext = "orm-context.xml";
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }

    // run tool
    try {
        // Using a generic application context since we're referencing
        // both classpath and filesystem resources.
        GenericApplicationContext ctx = new GenericApplicationContext();
        XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
        xmlReader.loadBeanDefinitions(new ClassPathResource("datasource-context.xml"),
                new ClassPathResource(ormContext), new FileSystemResource(analyzerXML));
        ctx.refresh();

        /*
         * Create an base admin user.
         */
        if (isPurged) {
            //only attempted if we've wiped the old database.
            RoleDao roleDao = (RoleDao) ctx.getBean("roleDao");
            Role adminRole = roleDao.saveOrUpdate(new Role("admin", "ROLE_ADMIN"));
            Role userRole = roleDao.saveOrUpdate(new Role("user", "ROLE_USER"));
            UserDao userDao = (UserDao) ctx.getBean("userDao");
            userDao.saveOrUpdate(new User("admin", "admin", "shap01", adminRole, userRole));
        }

        /*
         * Create some predefined analyzers. Users should have modified
         * the configuration file to suit their environment.
         */
        AnnotatorDao annotatorDao = (AnnotatorDao) ctx.getBean("annotatorDao");
        DetectorDao detectorDao = (DetectorDao) ctx.getBean("detectorDao");

        ConfigSetup config = (ConfigSetup) ctx.getBean("configuration");

        for (Annotator an : config.getAnnotators()) {
            System.out.println("Adding annotator: " + an.getName());
            annotatorDao.saveOrUpdate(an);
        }

        for (Detector dt : config.getDetectors()) {
            System.out.println("Adding detector: " + dt.getName());
            detectorDao.saveOrUpdate(dt);
        }

        System.exit(0);
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        System.exit(1);
    }
}

From source file:cc.twittertools.util.VerifySubcollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(/* ww w  .java2  s.  co m*/
            OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractSubcollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    LongOpenHashSet tweetids = new LongOpenHashSet();
    File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION));
    if (!tweetidsFile.exists()) {
        System.err.println("Error: " + tweetidsFile + " does not exist!");
        System.exit(-1);
    }
    LOG.info("Reading tweetids from " + tweetidsFile);

    FileInputStream fin = new FileInputStream(tweetidsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));

    String s;
    while ((s = br.readLine()) != null) {
        tweetids.add(Long.parseLong(s));
    }
    br.close();
    fin.close();
    LOG.info("Read " + tweetids.size() + " tweetids.");

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    LongOpenHashSet seen = new LongOpenHashSet();
    TreeMap<Long, String> tweets = Maps.newTreeMap();

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    int cnt = 0;
    while ((status = stream.next()) != null) {
        if (!tweetids.contains(status.getId())) {
            LOG.error("tweetid " + status.getId() + " doesn't belong in collection");
            continue;
        }
        if (seen.contains(status.getId())) {
            LOG.error("tweetid " + status.getId() + " already seen!");
            continue;
        }

        tweets.put(status.getId(), status.getJsonObject().toString());
        seen.add(status.getId());
        cnt++;
    }
    LOG.info("total of " + cnt + " tweets in subcollection.");

    for (Map.Entry<Long, String> entry : tweets.entrySet()) {
        out.println(entry.getValue());
    }

    stream.close();
    out.close();
}