Example usage for org.apache.commons.cli HelpFormatter printHelp

List of usage examples for org.apache.commons.cli HelpFormatter printHelp

Introduction

In this page you can find the example usage for org.apache.commons.cli HelpFormatter printHelp.

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:net.orzo.App.java

/**
 *
 *///from  w  w  w .ja  v  a2  s .co  m
public static void main(final String[] args) {
    final App app = new App();
    Logger log = null;
    CommandLine cmd;

    try {
        cmd = app.init(args);

        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    "orzo [options] user_script [user_arg1 [user_arg2 [...]]]\n(to generate a template: orzo -t [file path])",
                    app.cliOptions);

        } else if (cmd.hasOption("v")) {
            System.out.printf("Orzo.js version %s\n", app.props.get("orzo.version"));

        } else if (cmd.hasOption("t")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");

            File tplFile = new File(cmd.getOptionValue("t"));
            FileWriter tplWriter = new FileWriter(tplFile);
            tplWriter.write(templateSrc);
            tplWriter.close();

            File dtsFile = new File(
                    String.format("%s/orzojs.d.ts", new File(tplFile.getAbsolutePath()).getParent()));
            FileWriter dtsWriter = new FileWriter(dtsFile);
            String dtsSrc = new ResourceLoader().getResourceAsString("net/orzo/orzojs.d.ts");
            dtsWriter.write(dtsSrc);
            dtsWriter.close();

        } else if (cmd.hasOption("T")) {
            String templateSrc = new ResourceLoader().getResourceAsString("net/orzo/template1.js");
            System.out.println(templateSrc);

        } else {

            // Logger initialization
            if (cmd.hasOption("g")) {
                System.setProperty("logback.configurationFile", cmd.getOptionValue("g"));

            } else {
                System.setProperty("logback.configurationFile", "./logback.xml");
            }
            log = LoggerFactory.getLogger(App.class);
            if (cmd.hasOption("s")) { // Orzo.js as a REST and AMQP service
                FullServiceConfig conf = new Gson().fromJson(new FileReader(cmd.getOptionValue("s")),
                        FullServiceConfig.class);
                Injector injector = Guice.createInjector(new CoreModule(conf), new RestServletModule());
                HttpServer httpServer = new HttpServer(conf, new JerseyGuiceServletConfig(injector));
                app.services.add(httpServer);

                if (conf.getAmqpResponseConfig() != null) {
                    // response AMQP service must be initialized before receiving one
                    app.services.add(injector.getInstance(AmqpResponseConnection.class));
                }

                if (conf.getAmqpConfig() != null) {
                    app.services.add(injector.getInstance(AmqpConnection.class));
                    app.services.add(injector.getInstance(AmqpService.class));
                }

                if (conf.getRedisConf() != null) {
                    app.services.add(injector.getInstance(RedisStorage.class));
                }

                Runtime.getRuntime().addShutdownHook(new ShutdownHook(app));
                app.startServices();

            } else if (cmd.hasOption("d")) { // Demo mode
                final String scriptId = "demo";
                final SourceCode demoScript = SourceCode.fromResource(DEMO_SCRIPT);
                System.err.printf("Running demo script %s.", demoScript.getName());
                CmdConfig conf = new CmdConfig(scriptId, demoScript, null, cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                tm.startTaskSync(tm.registerTask(scriptId, new String[0]));

            } else if (cmd.getArgs().length > 0) { // Command line mode
                File userScriptFile = new File(cmd.getArgs()[0]);
                String optionalModulesPath = null;
                String[] inputValues;
                SourceCode userScript;

                // custom CommonJS modules path
                if (cmd.hasOption("m")) {
                    optionalModulesPath = cmd.getOptionValue("m");
                }

                if (cmd.getArgs().length > 0) {
                    inputValues = Arrays.copyOfRange(cmd.getArgs(), 1, cmd.getArgs().length);
                } else {
                    inputValues = new String[0];
                }

                userScript = SourceCode.fromFile(userScriptFile);
                CmdConfig conf = new CmdConfig(userScript.getName(), userScript, optionalModulesPath,
                        cmd.getOptionValue("p", null));
                TaskManager tm = new TaskManager(conf);
                String taskId = tm.registerTask(userScript.getName(), inputValues);
                tm.startTaskSync(taskId);
                if (tm.getTask(taskId).getStatus() == TaskStatus.ERROR) {
                    tm.getTask(taskId).getFirstError().getErrors().stream().forEach(System.err::println);
                }

            } else {
                System.err.println("Invalid parameters. Try -h for more information.");
                System.exit(1);
            }
        }

    } catch (Exception ex) {
        System.err.printf("Orzo.js crashed with error: %s\nSee the log for details.\n", ex.getMessage());
        if (log != null) {
            log.error(ex.getMessage(), ex);

        } else {
            ex.printStackTrace();
        }
    }
}

From source file:com.mozilla.fhr.consumer.FHRConsumer.java

public static void main(String[] args) {
    Options options = FHRConsumer.getOptions();
    CommandLineParser parser = new GnuParser();
    ShutdownHook sh = ShutdownHook.getInstance();
    try {/*w  ww  .  ja va  2 s .c o m*/
        // Parse command line options
        CommandLine cmd = parser.parse(options, args);

        final FHRConsumer consumer = (FHRConsumer) FHRConsumer.fromOptions(cmd);
        sh.addFirst(consumer);

        // Set the sink for consumer storage
        SinkConfiguration sinkConfig = new SinkConfiguration();
        if (cmd.hasOption("numthreads")) {
            sinkConfig.setInt("hbasesink.hbase.numthreads", Integer.parseInt(cmd.getOptionValue("numthreads")));
        }
        if (cmd.hasOption("batchsize")) {
            sinkConfig.setInt("hbasesink.hbase.batchsize", Integer.parseInt(cmd.getOptionValue("batchsize")));
        }

        sinkConfig.setString("hbasesink.hbase.tablename", cmd.getOptionValue("table"));
        sinkConfig.setString("hbasesink.hbase.column.family", cmd.getOptionValue("family", "data"));
        sinkConfig.setString("hbasesink.hbase.column.qualifier", cmd.getOptionValue("qualifier", "json"));
        sinkConfig.setBoolean("hbasesink.hbase.rowkey.prefixdate",
                Boolean.parseBoolean(cmd.getOptionValue("prefixdate", "false")));
        KeyValueSinkFactory sinkFactory = KeyValueSinkFactory.getInstance(HBaseSink.class, sinkConfig);
        sh.addLast(sinkFactory);
        consumer.setSinkFactory(sinkFactory);

        // Initialize metrics collection, reporting, etc.
        final MetricsManager manager = MetricsManager.getDefaultMetricsManager();

        // Begin polling
        consumer.poll();
    } catch (ParseException e) {
        LOG.error("Error parsing command line options", e);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(FHRConsumer.class.getName(), options);
    }
}

From source file:fr.tpt.s3.mcdag.scheduling.Main.java

public static void main(String[] args) throws IOException, InterruptedException {

    /* Command line options */
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML Models");
    input.setRequired(true);//from  w ww  .java  2s.c om
    input.setArgs(Option.UNLIMITED_VALUES); // Sets maximum number of threads to be launched
    options.addOption(input);

    Option outSched = new Option("os", "out-scheduler", false, "Write the scheduling tables into a file.");
    outSched.setRequired(false);
    options.addOption(outSched);

    Option outPrism = new Option("op", "out-prism", false, "Write PRISM model into a file.");
    outPrism.setRequired(false);
    options.addOption(outPrism);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debugOpt = new Option("d", "debug", false, "Enabling debug.");
    debugOpt.setRequired(false);
    options.addOption(debugOpt);

    Option preemptOpt = new Option("p", "preempt", false, "Count for preemptions.");
    preemptOpt.setRequired(false);
    options.addOption(preemptOpt);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("MC-DAG framework", options);

        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    boolean bOutSched = cmd.hasOption("out-scheduler");
    boolean bOutPrism = cmd.hasOption("out-prism");
    boolean debug = cmd.hasOption("debug");
    boolean preempt = cmd.hasOption("preempt");
    boolean levels = cmd.hasOption("n-levels");
    int nbFiles = inputFilePath.length;

    int nbJobs = 1;
    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    if (debug)
        System.out.println("[DEBUG] Launching " + inputFilePath.length + " thread(s).");

    int i_files = 0;
    ExecutorService executor = Executors.newFixedThreadPool(nbJobs);

    /* Launch threads to solve allocation */
    while (i_files != nbFiles) {
        SchedulingThread ft = new SchedulingThread(inputFilePath[i_files], bOutSched, bOutPrism, debug,
                preempt);

        ft.setLevels(levels);
        executor.execute(ft);
        i_files++;
    }

    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    System.out.println("[FRAMEWORK Main] DONE");
}

From source file:javadepchecker.Main.java

/**
 * @param args the command line arguments
 */// w  ww. j a v  a  2s .c om
public static void main(String[] args) throws IOException {
    int exit = 0;
    try {
        CommandLineParser parser = new PosixParser();
        Options options = new Options();
        options.addOption("h", "help", false, "print help");
        options.addOption("i", "image", true, "image directory");
        options.addOption("v", "verbose", false, "print verbose output");
        CommandLine line = parser.parse(options, args);
        String[] files = line.getArgs();
        if (line.hasOption("h") || files.length == 0) {
            HelpFormatter h = new HelpFormatter();
            h.printHelp("java-dep-check [-i <image>] <package.env>+", options);
        } else {
            image = line.getOptionValue("i", "");

            for (String arg : files) {
                if (line.hasOption('v')) {
                    System.out.println("Checking " + arg);
                }
                if (!checkPkg(new File(arg))) {
                    exit = 1;
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(exit);
}

From source file:name.wagners.bpp.Bpp.java

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

    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("generations")
            .withDescription("Number of generations [default: 50]").create("g"));

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("mutrate")
            .withDescription("Mutation rate [default: 1]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("mutprop")
            .withDescription("Mutation propability [default: 0.5]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("populationsize")
            .withDescription("Size of population [default: 20]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a|b").withLongOpt("recombalg")
            .withDescription("Recombination algorithm [default: a]").create());

    // options.addOption(OptionBuilder
    // .hasArg()/* ww  w .  j  a  v a 2  s.  c om*/
    // .withArgName("int")
    // .withLongOpt("recombrate")
    // .withDescription("Recombination rate [default: 1]")
    // .create());

    options.addOption(OptionBuilder.hasArg().withArgName("double").withLongOpt("recombprop")
            .withDescription("Recombination propability [default: 0.8]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("a").withLongOpt("selalg")
            .withDescription("Selection algorithm [default: a]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("int").withLongOpt("selectionpressure")
            .withDescription("Selection pressure [default: 4]").create());

    options.addOption(OptionBuilder.hasArg().withArgName("bool").withLongOpt("elitism")
            .withDescription("Enable Elitism [default: 1]").create("e"));

    options.addOption(OptionBuilder.hasArg().withArgName("filename")
            // .isRequired()
            .withLongOpt("datafile").withDescription("Problem data file [default: \"binpack.txt\"]")
            .create("f"));

    options.addOptionGroup(new OptionGroup()
            .addOption(OptionBuilder.withLongOpt("verbose").withDescription("be extra verbose").create("v"))
            .addOption(OptionBuilder.withLongOpt("quiet").withDescription("be extra quiet").create("q")));

    options.addOption(OptionBuilder.withLongOpt("version")
            .withDescription("print the version information and exit").create("V"));

    options.addOption(OptionBuilder.withLongOpt("help").withDescription("print this message").create("h"));

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        // validate that block-size has been set
        if (line.hasOption("help")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Bpp", options);

            System.exit(0);
        }

        if (line.hasOption("version")) {
            log.info("Bpp 0.1 (c) 2007 by Daniel Wagner");
        }

        if (line.hasOption("datafile")) {
            fname = line.getOptionValue("datafile");
        }

        if (line.hasOption("elitism")) {
            elitism = Boolean.parseBoolean(line.getOptionValue("elitism"));
        }

        if (line.hasOption("generations")) {
            gen = Integer.parseInt(line.getOptionValue("generations"));
        }

        if (line.hasOption("mutprop")) {
            mp = Double.parseDouble(line.getOptionValue("mutprop"));
        }

        if (line.hasOption("mutrate")) {
            mr = Integer.parseInt(line.getOptionValue("mutrate"));
        }

        if (line.hasOption("populationsize")) {
            ps = Integer.parseInt(line.getOptionValue("populationsize"));
        }

        if (line.hasOption("recombalg")) {
            sel = line.getOptionValue("recombalg").charAt(0);
        }

        if (line.hasOption("recombprop")) {
            rp = Double.parseDouble(line.getOptionValue("recombprop"));
        }

        if (line.hasOption("selalg")) {
            selalg = line.getOptionValue("selalg").charAt(0);
        }

        if (line.hasOption("selectionpressure")) {
            sp = Integer.parseInt(line.getOptionValue("selectionpressure"));
        }

    } catch (ParseException exp) {
        log.info("Unexpected exception:" + exp.getMessage(), exp);

        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Bpp", options);

        System.exit(1);
    }

    // Ausgabe der eingestellten Optionen

    log.info("Configuration");
    log.info("  Datafile:                  " + fname);
    log.info("  Generations:               " + gen);
    log.info("  Population size:           " + ps);
    log.info("  Elitism:                   " + elitism);
    log.info("  Mutation propapility:      " + mp);
    log.info("  Mutation rate:             " + mr);
    log.info("  Recombination algorithm    " + (char) sel);
    log.info("  Recombination propapility: " + rp);
    log.info("  Selection pressure:        " + sp);

    // Daten laden
    instance = new Instance();
    instance.load(fname);

    Evolutionizer e = new Evolutionizer(instance);

    e.run();
}

From source file:ca.ualberta.exemplar.core.Exemplar.java

public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser cli = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "shows this message");
    options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)");
    options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)");

    CommandLine line = null;//from  ww  w .  j a  va2s . c o m

    try {
        line = cli.parse(options, rawArgs);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "malt");

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar", options);
        System.exit(0);
    }

    if (args.length != 2) {
        System.out.println("error: exemplar requires an input file and output file.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar <input> <output>", options);
        System.exit(0);
    }

    File input = new File(args[0]);
    File output = new File(args[1]);

    String benchmarkType = line.getOptionValue("benchmark", "");
    if (!benchmarkType.isEmpty()) {
        if (benchmarkType.equals("binary")) {
            BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName);
            evaluation.runAndTime();
            System.exit(0);
        } else {
            if (benchmarkType.equals("nary")) {
                BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName);
                evaluation.runAndTime();
                System.exit(0);
            } else {
                System.out.println("error: benchmark option has to be either 'binary' or 'nary'.");
                System.exit(0);
            }
        }
    }

    Parser parser = null;
    if (parserName.equals("stanford")) {
        parser = new ParserStanford();
    } else {
        if (parserName.equals("malt")) {
            parser = new ParserMalt();
        } else {
            System.out.println(parserName + " is not a valid parser.");
            System.exit(0);
        }
    }

    System.out.println("Starting EXEMPLAR...");

    RelationExtraction exemplar = null;
    try {
        exemplar = new RelationExtraction(parser);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
    PlainTextReader reader = null;
    reader = new PlainTextReader(inputQueue, input);

    Thread readerThread = new Thread(reader);
    readerThread.start();

    PrintStream statementsOut = null;

    try {
        statementsOut = new PrintStream(output, "UTF-8");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.exit(0);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        System.exit(0);
    }

    statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence");

    while (true) {
        String doc = null;
        try {
            doc = inputQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (doc.isEmpty()) {
            break;
        }

        List<RelationInstance> instances = exemplar.extractRelations(doc);

        for (RelationInstance instance : instances) {

            // Output SUBJ arguments in a separate field, for clarity
            boolean first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("SUBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }

            // Output the original relation
            statementsOut.print("\t" + instance.getOriginalRelation() + "\t");

            // Output the DOBJ arguments, followed by POBJ
            first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("DOBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.startsWith("POBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            statementsOut.print("\t" + instance.getNormalizedRelation());
            statementsOut.print("\t" + instance.getSentence());
            statementsOut.println();
        }
    }

    System.out.println("Done!");
    statementsOut.close();

}

From source file:de.prozesskraft.pkraft.Wrap.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    //      try//from   w w  w.  java2  s .co m
    //      {
    //         if (args.length != 3)
    //         {
    //            System.out.println("Please specify processdefinition file (xml) and an outputfilename");
    //         }
    //         
    //      }
    //      catch (ArrayIndexOutOfBoundsException e)
    //      {
    //         System.out.println("***ArrayIndexOutOfBoundsException: Please specify processdefinition.xml, openoffice_template.od*, newfile_for_processdefinitions.odt\n" + e.toString());
    //      }

    /*----------------------------
      get options from ini-file
    ----------------------------*/
    File inifile = new java.io.File(
            WhereAmI.getInstallDirectoryAbsolutePath(Wrap.class) + "/" + "../etc/pkraft-wrap.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option ooutput = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory; default: .] file for generated wrapper process.")
            //            .isRequired()
            .create("output");

    Option odefinition = OptionBuilder.withArgName("FILE").hasArg()
            .withDescription("[mandatory] process definition file.")
            //            .isRequired()
            .create("definition");

    /*----------------------------
      create options object
    ----------------------------*/
    Options options = new Options();

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(ooutput);
    options.addOption(odefinition);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        commandline = parser.parse(options, args);

    } catch (Exception exp) {
        // oops, something went wrong
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        exiter();
    }

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("wrap", options);
        System.exit(0);
    }

    else if (commandline.hasOption("v")) {
        System.out.println("web:     www.prozesskraft.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }

    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    if (!(commandline.hasOption("definition"))) {
        System.err.println("option -definition is mandatory.");
        exiter();
    }

    if (!(commandline.hasOption("output"))) {
        System.err.println("option -output is mandatory.");
        exiter();
    }

    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/
    Process p1 = new Process();
    java.io.File output = new java.io.File(commandline.getOptionValue("output"));

    if (output.exists()) {
        System.err.println("warn: already exists: " + output.getCanonicalPath());
        exiter();
    }

    p1.setInfilexml(commandline.getOptionValue("definition"));
    System.err.println("info: reading process definition " + commandline.getOptionValue("definition"));

    // dummy process
    Process p2 = null;

    try {
        p2 = p1.readXml();
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.err.println("error");
        exiter();
    }

    // den wrapper process generieren
    Process p3 = p2.getProcessAsWrapper();
    p3.setOutfilexml(output.getAbsolutePath());

    // den neuen wrap-process rausschreiben
    p3.writeXml();
}

From source file:net.mybox.mybox.ServerAdmin.java

/**
 * Handle command line args//  w  ww.j a  va 2s . c om
 * @param args
 */
public static void main(String[] args) {

    Options options = new Options();
    options.addOption("c", "config", true, "configuration file");
    //    options.addOption("d", "database", true, "accounts database file");
    options.addOption("a", "apphome", true, "application home directory");
    options.addOption("h", "help", false, "show help screen");
    options.addOption("V", "version", false, "print the Mybox version");

    CommandLineParser line = new GnuParser();
    CommandLine cmd = null;

    try {
        cmd = line.parse(options, args);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ServerAdmin.class.getName(), options);
        return;
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Client.class.getName(), options);
        return;
    }

    if (cmd.hasOption("V")) {
        Client.printMessage("version " + Common.appVersion);
        return;
    }

    if (cmd.hasOption("a")) {
        String appHomeDir = cmd.getOptionValue("a");
        try {
            Common.updatePaths(appHomeDir);
        } catch (FileNotFoundException e) {
            Client.printErrorExit(e.getMessage());
        }

        Server.updatePaths();
    }

    String configFile = Server.defaultConfigFile;
    //    String accountsDBfile = Server.defaultAccountsDbFile;

    if (cmd.hasOption("c")) {
        configFile = cmd.getOptionValue("c");
    }

    File fileCheck = new File(configFile);
    if (!fileCheck.isFile())
        Server.printErrorExit("Config not found: " + configFile + "\nPlease run ServerSetup");

    //    if (cmd.hasOption("d")){
    //      accountsDBfile = cmd.getOptionValue("d");
    //    }
    //
    //    fileCheck = new File(accountsDBfile);
    //    if (!fileCheck.isFile())
    //      Server.printErrorExit("Error account database not found: " + accountsDBfile);

    ServerAdmin server = new ServerAdmin(configFile);

}

From source file:com.artistech.tuio.dispatch.TuioPublish.java

public static void main(String[] args) throws InterruptedException {
    //read off the TUIO port from the command line
    int tuio_port = 3333;
    int zeromq_port = 5565;
    TuioSink.SerializeType serialize_method = TuioSink.SerializeType.PROTOBUF;

    Options options = new Options();
    options.addOption("t", "tuio-port", true, "TUIO Port to listen on. (Default = 3333)");
    options.addOption("z", "zeromq-port", true, "ZeroMQ Port to publish on. (Default = 5565)");
    options.addOption("s", "serialize-method", true,
            "Serialization Method (JSON, OBJECT, Default = PROTOBUF).");
    options.addOption("h", "help", false, "Show this message.");
    HelpFormatter formatter = new HelpFormatter();

    try {//from   w  ww. j  a  v  a2 s  .  c o m
        CommandLineParser parser = new org.apache.commons.cli.BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            formatter.printHelp("tuio-zeromq-publish", options);
            return;
        } else {
            if (cmd.hasOption("t") || cmd.hasOption("tuio-port")) {
                tuio_port = Integer.parseInt(cmd.getOptionValue("t"));
            }
            if (cmd.hasOption("z") || cmd.hasOption("zeromq-port")) {
                zeromq_port = Integer.parseInt(cmd.getOptionValue("z"));
            }
            if (cmd.hasOption("s") || cmd.hasOption("serialize-method")) {
                serialize_method = (TuioSink.SerializeType) Enum.valueOf(TuioSink.SerializeType.class,
                        cmd.getOptionValue("s"));
            }
        }
    } catch (ParseException | IllegalArgumentException ex) {
        System.err.println("Error Processing Command Options:");
        formatter.printHelp("tuio-zeromq-publish", options);
        return;
    }

    //start up the zmq publisher
    ZMQ.Context context = ZMQ.context(1);
    // We send updates via this socket
    try (ZMQ.Socket publisher = context.socket(ZMQ.PUB)) {
        // We send updates via this socket
        publisher.bind("tcp://*:" + Integer.toString(zeromq_port));

        //create a new TUIO sink connected at the specified port
        TuioSink sink = new TuioSink();
        sink.setSerializationType(serialize_method);
        TuioClient client = new TuioClient(tuio_port);

        System.out.println(
                MessageFormat.format("Listening to TUIO message at port: {0}", Integer.toString(tuio_port)));
        System.out.println(
                MessageFormat.format("Publishing to ZeroMQ at port: {0}", Integer.toString(zeromq_port)));
        System.out.println(MessageFormat.format("Serializing as: {0}", serialize_method));
        client.addTuioListener(sink);
        client.connect();

        //while not halted (infinite loop...)
        //read any available messages and publish
        while (!sink.mailbox.isHalted()) {
            ImmutablePair<String, byte[]> msg = sink.mailbox.getMessage();
            publisher.sendMore(msg.left + "." + serialize_method.toString());
            publisher.send(msg.right, 0);
        }

        //cleanup
    }
    context.term();
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

public static void main(String[] args) {

    int port = 8888;
    String source = "localhost";
    Options options = new Options();
    options.addOption("h", false, "Help");

    @SuppressWarnings("static-access")
    Option optionP = OptionBuilder.withArgName("port").hasArg()
            .withDescription("Source port (default: " + port + ")").create("p");
    options.addOption(optionP);//from w  w w .ja v a  2s .  c  o m

    @SuppressWarnings("static-access")
    Option optionS = OptionBuilder.withArgName("source").hasArg().isRequired().withDescription(
            "Source address of the ZMQ stream (default port " + port + " : use -p to set the port if needed)")
            .create("s");
    options.addOption(optionS);

    @SuppressWarnings("static-access")
    Option optionD = OptionBuilder.withArgName("path").hasArg().isRequired()
            .withDescription("tpath for storing files with relative destination paths").create("d");
    options.addOption(optionD);

    GnuParser parser = new GnuParser();
    CommandLine line;
    String path = ".";
    try {
        line = parser.parse(options, args);
        if (line.hasOption(optionP.getOpt())) {
            port = Integer.parseInt(line.getOptionValue(optionP.getOpt()));
        }
        if (line.hasOption("h")) {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("receiver", options);
            return;
        }

        source = line.getOptionValue(optionS.getOpt());
        path = line.getOptionValue(optionD.getOpt());

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter f = new HelpFormatter();
        f.printHelp("receiver", options);
        System.exit(-1);
    }

    final FileReceiver r = new FileReceiver(source, port, path);
    r.receive();

    // Control+C
    Signal.handle(new Signal("INT"), new SignalHandler() {
        int count = 0;

        public void handle(Signal sig) {
            if (count < 1) {
                count++;
                r.terminate();
            } else {
                System.exit(-1);
            }

        }
    });
}