Example usage for org.apache.commons.cli CommandLine hasOption

List of usage examples for org.apache.commons.cli CommandLine hasOption

Introduction

In this page you can find the example usage for org.apache.commons.cli CommandLine hasOption.

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.mvdb.etl.actions.InitCustomerData.java

public static void main(String[] args) {
    ActionUtils.assertEnvironmentSetupOk();
    ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing.");
    ActionUtils.assertFileExists("~/.mvdb/status.InitDB.complete", "200initdb.sh not executed yet. Exiting");
    ActionUtils.assertFileDoesNotExist("~/.mvdb/status.InitCustomerData.complete",
            "InitCustomerData already done. Start with 100init.sh if required. Exiting");
    ActionUtils.setUpInitFileProperty();
    ActionUtils.createMarkerFile("~/.mvdb/status.InitCustomerData.start");

    Date startDate = null;/*  www  .j a  v a  2 s .  co m*/
    Date endDate = null;
    String customerName = null;
    int batchCountF = 0;
    int batchSizeF = 0;
    final CommandLineParser cmdLinePosixParser = new PosixParser();
    final Options posixOptions = constructPosixOptions();
    CommandLine commandLine;
    try {
        commandLine = cmdLinePosixParser.parse(posixOptions, args);
        if (commandLine.hasOption("customer")) {
            customerName = commandLine.getOptionValue("customer");
        }
        if (commandLine.hasOption("batchSize")) {
            String batchSizeStr = commandLine.getOptionValue("batchSize");
            batchSizeF = Integer.parseInt(batchSizeStr);
        }
        if (commandLine.hasOption("batchCount")) {
            String batchCountStr = commandLine.getOptionValue("batchCount");
            batchCountF = Integer.parseInt(batchCountStr);
        }
        if (commandLine.hasOption("startDate")) {
            String startDateStr = commandLine.getOptionValue("startDate");
            startDate = ActionUtils.getDate(startDateStr);
        }
        if (commandLine.hasOption("endDate")) {
            String endDateStr = commandLine.getOptionValue("endDate");
            endDate = ActionUtils.getDate(endDateStr);
        }
    } catch (ParseException parseException) // checked exception
    {
        System.err.println(
                "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage());
    }

    if (startDate == null) {
        System.err.println(
                "startDate has not been specified with the correct format YYYYMMddHHmmss.  Aborting...");
        System.exit(1);
    }

    if (endDate == null) {
        System.err
                .println("endDate has not been specified with the correct format YYYYMMddHHmmss.  Aborting...");
        System.exit(1);
    }

    if (endDate.after(startDate) == false) {
        System.err.println("endDate must be after startDate.  Aborting...");
        System.exit(1);
    }

    // if you have time,
    // it's better to create an unit test rather than testing like this :)

    ApplicationContext context = Top.getContext();

    final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO");
    final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO");

    initData(orderDAO, batchCountF, batchSizeF, startDate, endDate);
    initConfiguration(configurationDAO, customerName, endDate);

    int total = orderDAO.findTotalOrders();
    System.out.println("Total : " + total);

    long max = orderDAO.findMaxId();
    System.out.println("maxid : " + max);

    ActionUtils.createMarkerFile("~/.mvdb/status.InitCustomerData.complete");

}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("u", null, true, "Solr URI");
    options.addOption("q", null, true, "Query");
    options.addOption("n", null, true, "Max # of results");
    options.addOption("o", null, true, "An optional TREC-style output file");
    options.addOption("w", null, false, "Do a warm-up query call, before each query");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter trecOutFile = null;

    try {/* w  ww . ja  v a  2 s.  c  o  m*/
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null, solrURI = null;

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        if (cmd.hasOption("q")) {
            queryFile = cmd.getOptionValue("q");
        } else {
            Usage("Specify Query file");
        }

        int numRet = 100;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        if (cmd.hasOption("o")) {
            trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o"))));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConst.ID_FIELD);
        fieldList.add(UtilConst.SCORE_FIELD);

        double totalTime = 0;
        double retQty = 0;

        ArrayList<Double> queryTimes = new ArrayList<Double>();

        boolean bDoWarmUp = cmd.hasOption("w");

        if (bDoWarmUp) {
            System.out.println("Using a warmup step!");
        }

        int queryQty = 0;
        for (String t : FileUtils.readLines(new File(queryFile))) {
            t = t.trim();
            if (t.isEmpty())
                continue;
            int ind = t.indexOf('|');
            if (ind < 0)
                throw new Exception("Wrong format, line: '" + t + "'");
            String qID = t.substring(0, ind);
            String q = t.substring(ind + 1);

            SolrDocumentList res = null;

            if (bDoWarmUp) {
                res = solr.runQuery(q, fieldList, numRet);
            }

            Long tm1 = System.currentTimeMillis();
            res = solr.runQuery(q, fieldList, numRet);
            Long tm2 = System.currentTimeMillis();
            retQty += res.getNumFound();
            System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms");
            double delta = (tm2 - tm1);
            totalTime += delta;
            queryTimes.add(delta);
            ++queryQty;

            if (trecOutFile != null) {

                ArrayList<SolrRes> resArr = new ArrayList<SolrRes>();
                for (SolrDocument doc : res) {
                    String id = (String) doc.getFieldValue(UtilConst.ID_FIELD);
                    float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD);
                    resArr.add(new SolrRes(id, "", score));
                }
                SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]);
                Arrays.sort(results);

                SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length);
            }
        }
        double devTime = 0, meanTime = totalTime / queryQty;
        for (int i = 0; i < queryQty; ++i) {
            double d = queryTimes.get(i) - meanTime;
            devTime += d * d;
        }
        devTime = Math.sqrt(devTime / (queryQty - 1));
        System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime));
        System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty));

        solr.close();
        trecOutFile.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:androidimporter.AndroidImporter.java

public static void main(String[] args) throws ParseException {
    //"/usr/local/apache-ant/bin/ant"
    String antPath = System.getProperty("ANT_PATH", System.getenv("ANT_PATH"));
    if (antPath == null || !new File(antPath).exists()) {
        throw new RuntimeException("Cannot find ant at " + antPath
                + ".  Please specify location to ant via the ANT_PATH environment variable or java system property.");
    }/*from  www.  ja v  a  2s. c o m*/

    Options opts = new Options()
            .addOption("i", "android-resource-dir", true, "Android project res directory path")
            .addOption("o", "cn1-project-dir", true, "Path to the CN1 output project directory.")
            .addOption("r", "cn1-resource-file", false,
                    "Path to CN1 output .res file.  Defaults to theme.res in project dir")
            .addOption("p", "package", true, "Java package to place GUI forms in.")
            .addOption("h", "help", false, "Usage instructions");

    CommandLineParser parser = new DefaultParser();

    CommandLine line = parser.parse(opts, args);

    if (line.hasOption("help")) {
        showHelp(opts);
        System.exit(0);
    }
    args = line.getArgs();

    if (args.length < 1) {
        System.out.println("No command provided.");
        showHelp(opts);
        System.exit(0);
    }

    switch (args[0]) {
    case "import-project": {

        if (!line.hasOption("android-resource-dir") || !line.hasOption("cn1-project-dir")
                || !line.hasOption("package")) {
            System.out.println("Please provide android-resource-dir, package, and cn1-project-dir options");
            showHelp(opts);
            System.exit(1);
        }
        File resDir = findResDir(new File(line.getOptionValue("android-resource-dir")));
        if (resDir == null || !resDir.isDirectory()) {
            System.out.println("Failed to find android resource directory from provided value");
            showHelp(opts);
            System.exit(1);
        }

        File projDir = new File(line.getOptionValue("cn1-project-dir"));
        File resFile = new File(projDir, "src" + File.separator + "theme.res");
        if (line.hasOption("cn1-resource-file")) {
            resFile = new File(line.getOptionValue("cn1-resource-file"));
        }

        JavaSEPort.setShowEDTViolationStacks(false);
        JavaSEPort.setShowEDTWarnings(false);
        JFrame frm = new JFrame("Placeholder");
        frm.setVisible(false);
        Display.init(frm.getContentPane());
        JavaSEPort.setBaseResourceDir(resFile.getParentFile());
        try {
            System.out.println("About to import project at " + resDir.getAbsolutePath());
            System.out.println("Codename One Output Project: " + projDir.getAbsolutePath());
            System.out.println("Resource file: " + resFile.getAbsolutePath());
            System.out.println("Java Package: " + line.getOptionValue("package"));
            AndroidProjectImporter.importProject(resDir, projDir, resFile, line.getOptionValue("package"));
            Runtime.getRuntime().exec(new String[] { antPath, "init" }, new String[] {},
                    resFile.getParentFile().getParentFile());
            //runAnt(new File(resFile.getParentFile().getParentFile(), "build.xml"), "init");
            System.exit(0);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            System.exit(0);
        }
        break;
    }

    default:
        System.out.println("Unknown command " + args[0]);
        showHelp(opts);
        break;

    }

}

From source file:de.huberlin.german.korpling.laudatioteitool.App.java

public static void main(String[] args) {
    Options opts = new Options()
            .addOption(new Option("merge", true,
                    messages.getString("MERGE CONTENT FROM INPUT DIRECTORY INTO ONE TEI HEADER")))
            .addOption(new Option("split", true,
                    messages.getString("SPLIT ONE TEI HEADER INTO SEVERAL HEADER FILES")))
            .addOption(new Option("validate", true, messages.getString("VALIDATE DIRECTORY OR FILE")))
            .addOption(new Option("config", true, messages.getString("CONFIG FILE LOCATION")))
            .addOption(new Option("schemecorpus", true, messages.getString("CORPUS SCHEME LOCATION")))
            .addOption(new Option("schemedoc", true, messages.getString("DOCUMENT SCHEME LOCATION")))
            .addOption(new Option("schemeprep", true, messages.getString("PREPARATION SCHEME LOCATION")))
            .addOption(new Option("help", false, messages.getString("SHOW THIS HELP")));

    HelpFormatter fmt = new HelpFormatter();
    String usage = "java -jar teitool.jar [options] [output directory/file]";
    String header = messages.getString("HELP HEADER");
    String footer = messages.getString("HELP FOOTER");

    try {/*  w w w .  ja  va2 s. c om*/
        CommandLineParser cliParser = new PosixParser();

        CommandLine cmd = cliParser.parse(opts, args);

        Properties props = new Properties();
        if (cmd.hasOption("config")) {
            props = readConfig(cmd.getOptionValue("config"));
        } // end if "config" given
        fillPropertiesFromCommandLine(props, cmd);

        if (cmd.hasOption("help")) {
            fmt.printHelp(usage, header, opts, footer);
        } else if (cmd.hasOption("validate")) {
            validate(cmd.getOptionValue("validate"), props.getProperty("schemecorpus"),
                    props.getProperty("schemedoc"), props.getProperty("schemeprep"));
        } else if (cmd.hasOption("merge")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT FILE AS ARGUMENT"));
                System.exit(-1);
            }
            MergeTEI merge = new MergeTEI(new File(cmd.getOptionValue("merge")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            merge.merge();

            System.exit(0);
        } else if (cmd.hasOption("split")) {
            if (cmd.getArgs().length != 1) {
                System.out.println(messages.getString("YOU NEED TO GIVE AT AN OUTPUT DIRECTORY AS ARGUMENT"));
                System.exit(-1);
            }
            SplitTEI split = new SplitTEI(new File(cmd.getOptionValue("split")), new File(cmd.getArgs()[0]),
                    props.getProperty("schemecorpus"), props.getProperty("schemedoc"),
                    props.getProperty("schemeprep"));
            split.split();
            System.exit(0);
        } else {
            fmt.printHelp(usage, header, opts, footer);
        }

    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        fmt.printHelp(usage, header, opts, footer);
    } catch (LaudatioException ex) {
        System.err.println(ex.getMessage());
    } catch (UnsupportedOperationException ex) {
        System.err.println(ex.getMessage());
    }

    System.exit(1);

}

From source file:com.quanticate.opensource.pdftkbox.PDFtkBox.java

public static void main(String[] args) throws Exception {
    // For printing help
    Options optsHelp = new Options();
    optsHelp.addOption(Option.builder("help").required().desc("print this message").build());

    // Normal-style import/export
    Options optsNormal = new Options();
    OptionGroup normal = new OptionGroup();
    Option optExport = Option.builder("export").required().hasArg().desc("export bookmarks from pdf")
            .argName("source-pdf").build();
    normal.addOption(optExport);/*  w  w  w .jav  a  2 s .  com*/
    Option optImport = Option.builder("import").required().hasArg().desc("import bookmarks into pdf")
            .argName("source-pdf").build();
    normal.addOption(optImport);
    optsNormal.addOptionGroup(normal);
    Option optBookmarks = Option.builder("bookmarks").hasArg().desc("bookmarks definition file")
            .argName("bookmarks").build();
    optsNormal.addOption(optBookmarks);
    Option optOutput = Option.builder("output").hasArg().desc("output to new pdf").argName("pdf").build();
    optsNormal.addOption(optOutput);

    // PDFtk style options
    Options optsPDFtk = new Options();
    OptionGroup pdftk = new OptionGroup();
    Option optDumpData = Option.builder("dump_data").required().desc("dump bookmarks from pdf").build();
    pdftk.addOption(optDumpData);
    Option optUpdateInfo = Option.builder("update_info").required().hasArg().desc("update bookmarks in pdf")
            .argName("bookmarks").build();
    pdftk.addOption(optUpdateInfo);
    optsPDFtk.addOptionGroup(pdftk);
    optsPDFtk.addOption(optOutput);

    // What are we doing?
    CommandLineParser parser = new DefaultParser();

    // Did they want help?
    try {
        parser.parse(optsHelp, args);

        // If we get here, they asked for help
        doPrintHelp(optsHelp, optsNormal, optsPDFtk);
        return;
    } catch (ParseException pe) {
    }

    // Normal-style import/export?
    try {
        CommandLine line = parser.parse(optsNormal, args);

        // Export
        if (line.hasOption(optExport.getOpt())) {
            doExport(line.getOptionValue(optExport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getArgs());
            return;
        }
        // Import with explicit output filename
        if (line.hasOption(optImport.getOpt()) && line.hasOption(optOutput.getOpt())) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()),
                    line.getOptionValue(optOutput.getOpt()), null);
            return;
        }
        // Import with implicit output filename
        if (line.hasOption(optImport.getOpt()) && line.getArgs().length > 0) {
            doImport(line.getOptionValue(optImport.getOpt()), line.getOptionValue(optBookmarks.getOpt()), null,
                    line.getArgs());
            return;
        }
    } catch (ParseException pe) {
    }

    // PDFtk-style
    if (args.length > 1) {
        // Nobble things for PDFtk-style options and Commons CLI
        for (int i = 1; i < args.length; i++) {
            for (Option opt : optsPDFtk.getOptions()) {
                if (args[i].equals(opt.getOpt())) {
                    args[i] = "-" + args[i];
                }
            }
        }
        try {
            // Input file comes first, then arguments
            String input = args[0];
            String[] pargs = new String[args.length - 1];
            System.arraycopy(args, 1, pargs, 0, pargs.length);

            // Parse what's left and check
            CommandLine line = parser.parse(optsPDFtk, pargs);

            if (line.hasOption(optDumpData.getOpt())) {
                doExport(input, line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
            if (line.hasOption(optUpdateInfo.getOpt())) {
                doImport(input, line.getOptionValue(optUpdateInfo.getOpt()),
                        line.getOptionValue(optOutput.getOpt()), line.getArgs());
                return;
            }
        } catch (ParseException pe) {
        }
    }

    // If in doubt, print help
    doPrintHelp(optsHelp, optsNormal, optsPDFtk);
}

From source file:eu.scape_project.tb.lsdr.hocrparser.HocrParser.java

/**
 * The main entry point.//from   w  w w.  j av  a2  s  .  c o  m
 */
public static void main(String[] args) throws ParseException {
    Configuration conf = new Configuration();

    //conf.setBoolean("mapreduce.client.genericoptionsparser.used", true);
    GenericOptionsParser gop = new GenericOptionsParser(conf, args);
    HocrParserCliConfig pc = new HocrParserCliConfig();
    CommandLineParser cmdParser = new PosixParser();
    CommandLine cmd = cmdParser.parse(HocrParserOptions.OPTIONS, gop.getRemainingArgs());
    if ((args.length == 0) || (cmd.hasOption(HocrParserOptions.HELP_OPT))) {
        HocrParserOptions.exit("Usage", 0);
    } else {
        HocrParserOptions.initOptions(cmd, pc);
    }
    String dir = pc.getDirStr();

    String name = pc.getHadoopJobName();
    if (name == null || name.equals("")) {
        name = "hocr_parser";
    }

    try {
        Job job = new Job(conf, name);
        job.setJarByClass(HocrParser.class);

        job.setMapperClass(HocrParserMapper.class);
        //job.setCombinerClass(HocrParserReducer.class);
        job.setReducerClass(HocrParserReducer.class);

        job.setInputFormatClass(SequenceFileInputFormat.class);

        job.setOutputFormatClass(TextOutputFormat.class);
        //SequenceFileOutputFormat.setOutputCompressionType(job, SequenceFile.CompressionType.NONE);

        //conf.setMapOutputKeyClass(Text.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        SequenceFileInputFormat.addInputPath(job, new Path(dir));
        String outpath = "output/" + System.currentTimeMillis() + "hop";
        FileOutputFormat.setOutputPath(job, new Path(outpath));
        job.waitForCompletion(true);
        System.out.print(outpath);
        System.exit(0);
    } catch (Exception e) {
        logger.error("IOException occurred", e);
    }
}

From source file:co.cask.cdap.data.tools.CoprocessorBuildTool.java

public static void main(final String[] args) throws ParseException {

    Options options = new Options().addOption(new Option("h", "help", false, "Print this usage message."))
            .addOption(new Option("f", "force", false, "Overwrites any coprocessors that already exist."));

    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String[] commandArgs = commandLine.getArgs();

    // if help is an option, or if there isn't a single 'ensure' command, print usage and exit.
    if (commandLine.hasOption("h") || commandArgs.length != 1 || !"check".equalsIgnoreCase(commandArgs[0])) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp(CoprocessorBuildTool.class.getName() + " check",
                "Checks that HBase coprocessors required by CDAP are loaded onto HDFS. "
                        + "If not, the coprocessors are built and placed on HDFS.",
                options, "");
        System.exit(0);//from   www. j ava 2  s.  c  o m
    }

    boolean overwrite = commandLine.hasOption("f");

    CConfiguration cConf = CConfiguration.create();
    Configuration hConf = HBaseConfiguration.create();

    Injector injector = Guice.createInjector(new ConfigModule(cConf, hConf),
            // for LocationFactory
            new PrivateModule() {
                @Override
                protected void configure() {
                    bind(FileContext.class).toProvider(FileContextProvider.class).in(Scopes.SINGLETON);
                    expose(LocationFactory.class);
                }

                @Provides
                @Singleton
                private LocationFactory providesLocationFactory(Configuration hConf, CConfiguration cConf,
                        FileContext fc) {
                    final String namespace = cConf.get(Constants.CFG_HDFS_NAMESPACE);
                    return new FileContextLocationFactory(hConf, fc, namespace);
                }
            });

    try {
        SecurityUtil.loginForMasterService(cConf);
    } catch (Exception e) {
        LOG.error("Failed to login as CDAP user", e);
        System.exit(1);
    }

    LocationFactory locationFactory = injector.getInstance(LocationFactory.class);
    HBaseTableUtil tableUtil = new HBaseTableUtilFactory(cConf).get();
    CoprocessorManager coprocessorManager = new CoprocessorManager(cConf, locationFactory, tableUtil);

    try {
        Location location = coprocessorManager.ensureCoprocessorExists(overwrite);
        LOG.info("coprocessor exists at {}.", location);
    } catch (IOException e) {
        LOG.error("Unable to build and upload coprocessor jars.", e);
        System.exit(1);
    }
}

From source file:MainServer.java

public static void main(String[] args) {
    int port = 1234;
    String filepath = "";
    String complete_path = "";
    String connection_type = "";
    String ip_address = "";
    int port_out = 0;
    int delay = 20; //20 by default

    //parse commands using getOpt (cli)
    //add Options
    Options options = new Options();

    options.addOption("p", true, "port_to_listen_on");
    options.addOption("d", true, "directory");
    options.addOption("T", false, "TCP mode");
    options.addOption("U", false, "UDP mode");
    options.addOption("s", true, "iPAddress");
    options.addOption("P", true, "port_to_connect_to");
    options.addOption("D", true, "delay");

    CommandLineParser clp = new DefaultParser();
    try {/* w w w .  jav a2 s  . c o m*/
        CommandLine cl = clp.parse(options, args);

        //options for the server
        if (cl.hasOption("p")) {
            port = Integer.parseInt(cl.getOptionValue("p"));
        } else {
            System.err.println("No valid port selected.");
            return;
        }

        if (cl.hasOption("d")) {
            filepath = cl.getOptionValue("d");
            //if there a '/' in front, remove it to make it a valid directory
            if (filepath.substring(0, 1).equalsIgnoreCase("/")) {
                filepath = filepath.substring(1);
            }
        } else {
            System.err.println("No valid directory given.");
            return;
        }

        if (cl.hasOption("D")) {
            delay = Integer.parseInt(cl.getOptionValue("D"));
        }

        //options for the client
        if (cl.hasOption("T")) {
            connection_type = "T";
        } else if (cl.hasOption("U")) {
            connection_type = "U";
        }

        if (cl.hasOption("s")) {
            ip_address = cl.getOptionValue("s");
        }

        if (cl.hasOption("P")) {
            port_out = Integer.parseInt(cl.getOptionValue("P"));
        }

    } catch (ParseException e) {
        //TODO: handle exception
    }

    //create directory (if it doesn't already exist)
    try {
        Files.createDirectories(Paths.get(filepath));
    } catch (Exception e) {
        //TODO: handle exception
        System.err.println("Couldn't create directory");
        System.err.println(filepath);
    }

    //read in required files (create them if they dont already exist)
    try {
        Files.createFile(Paths.get(filepath + "/gossip.txt"));
        Files.createFile(Paths.get(filepath + "/peers.txt"));
    } catch (Exception e) {
        //TODO: handle exception
    }
    WriteToFiles.readFiles(filepath);

    //start the servers
    TCPServerSock tcpServer = new TCPServerSock(port, filepath, delay);
    UDPServer udpServer = new UDPServer(port, filepath);

    Thread tcpThread = new Thread(tcpServer);
    Thread udpThread = new Thread(udpServer);

    tcpThread.start();
    udpThread.start();

    //start the client
    if (!connection_type.equals("") && port_out != 0 && !ip_address.equals("")) {
        Client client = new Client(ip_address, port_out, connection_type);
        Thread clientThread = new Thread(client);
        clientThread.start();
    }

    //Start thread to forget peers
    ForgetPeer forgetPeer = new ForgetPeer(filepath + "/peers.txt", delay);
    Thread forgetPeerThread = new Thread(forgetPeer);
    forgetPeerThread.start();
}

From source file:de.tudarmstadt.ukp.teaching.uima.nounDecompounding.web1t.LuceneIndexer.java

/**
 * Execute the indexer. Following parameter are allowed:
 * // w w  w  . j  av a2  s . c o m
 *   * --web1t The folder with all extracted n-gram files
 *   * --outputPath The lucene index folder
 *   * --index (optional) Number of how many indexes should be created. Default: 1
 * 
 * @param args
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("web1t")
            .withDescription("Folder with the web1t extracted documents").hasArg().isRequired().create());
    options.addOption(OptionBuilder.withLongOpt("outputPath")
            .withDescription("File, where the index should be created").hasArg().isRequired().create());
    options.addOption(OptionBuilder.withLongOpt("index")
            .withDescription("(optional) Number of how many indexes should be created. Default: 1").hasArg()
            .create());
    options.addOption(OptionBuilder.withLongOpt("igerman98").withDescription(
            "(optional) If this argument is set, only words of the german dictionary will be added to the index")
            .create());

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        int i = 1;
        if (cmd.hasOption("index")) {
            i = Integer.valueOf(cmd.getOptionValue("index"));
        }

        LuceneIndexer indexer = new LuceneIndexer(new File(cmd.getOptionValue("web1t")),
                new File(cmd.getOptionValue("outputPath")), i);

        if (cmd.hasOption("igerman98")) {
            indexer.setDictionary(new IGerman98Dictionary(new File("src/main/resources/de_DE.dic"),
                    new File("src/main/resources/de_DE.aff")));
        }

        indexer.index();
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LuceneIndexer", options);
    }
}

From source file:com.netflix.suro.SuroServer.java

public static void main(String[] args) throws IOException {
    final AtomicReference<Injector> injector = new AtomicReference<Injector>();

    try {//w  w  w.ja  v a 2  s .  c  o  m
        // Parse the command line
        Options options = createOptions();
        final CommandLine line = new BasicParser().parse(options, args);

        // Load the properties file
        final Properties properties = new Properties();
        if (line.hasOption('p')) {
            properties.load(new FileInputStream(line.getOptionValue('p')));
        }

        // Bind all command line options to the properties with prefix "SuroServer."
        for (Option opt : line.getOptions()) {
            String name = opt.getOpt();
            String value = line.getOptionValue(name);
            String propName = PROP_PREFIX + opt.getArgName();
            if (propName.equals(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY)) {
                properties.setProperty(DynamicPropertyRoutingMapConfigurator.ROUTING_MAP_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertySinkConfigurator.SINK_PROPERTY)) {
                properties.setProperty(DynamicPropertySinkConfigurator.SINK_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else if (propName.equals(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY)) {
                properties.setProperty(DynamicPropertyInputConfigurator.INPUT_CONFIG_PROPERTY,
                        FileUtils.readFileToString(new File(value)));
            } else {
                properties.setProperty(propName, value);
            }
        }

        create(injector, properties);
        injector.get().getInstance(LifecycleManager.class).start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
                } catch (IOException e) {
                    // do nothing because Closeables.close will swallow IOException
                }
            }
        });

        waitForShutdown(getControlPort(properties));
    } catch (Throwable e) {
        System.err.println("SuroServer startup failed: " + e.getMessage());
        System.exit(-1);
    } finally {
        Closeables.close(injector.get().getInstance(LifecycleManager.class), true);
    }
}