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:cnxchecker.Server.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption("p", "port", true, "TCP port to bind to (random by default)");
    options.addOption("h", "help", false, "Print help");

    CommandLineParser parser = new GnuParser();
    try {//w  w w.j a v  a 2s .  c  o m
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("h")) {
            HelpFormatter hf = new HelpFormatter();
            hf.printHelp("server", options);
            System.exit(0);
        }

        int port = 0;
        if (cmd.hasOption("p")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("p"));
            } catch (NumberFormatException e) {
                printAndExit("Invalid port number " + cmd.getOptionValue("p"));
            }

            if (port < 0 || port > 65535) {
                printAndExit("Invalid port number " + port);
            }
        }

        Server server = new Server(port);
        server.doit();
    } catch (ParseException e) {
        printAndExit("Failed to parse options: " + e.getMessage());
    }
}

From source file:de.akquinet.dustjs.DustEngine.java

public static void main(String[] args) throws URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(DustOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(DustOptions.DUST_OPTION, true, "Path to a custom dust.js for Rhino version.");
    try {/*from   w  w  w . ja v a 2  s  .com*/
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        DustOptions options = new DustOptions();
        if (cmdLine.hasOption(DustOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(DustOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(DustOptions.DUST_OPTION)) {
            options.setDust(new File(cmdLine.getOptionValue(DustOptions.DUST_OPTION)).toURI().toURL());
        }
        DustEngine engine = new DustEngine(options);
        String[] files = cmdLine.getArgs();

        String src = null;
        if (files == null || files.length == 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            src = sw.toString();
        }

        if (src != null && !src.isEmpty()) {
            System.out.println(engine.compile(src, "test"));
            return;
        }

        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0])));
            return;
        }

        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]));
            return;
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }

    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar dust-engine.jar input [output] [options]", cmdOptions);
    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(//from  w  w w. j a v  a  2 s .  c o 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();
}

From source file:com.mnxfst.stream.server.StreamAnalyzerServer.java

/**
 * Ramps up the server/*from  w w w. j  a  v  a  2s. c  om*/
 * @param args
 */
public static void main(String[] args) throws Exception {

    CommandLineParser parser = new PosixParser();
    CommandLine cl = parser.parse(getOptions(), args);
    if (!cl.hasOption("cfg") || !cl.hasOption("port")) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java " + StreamAnalyzerServer.class.getName(), getOptions());
        return;
    }

    (new StreamAnalyzerServer()).run(cl.getOptionValue("cfg"), Integer.parseInt(cl.getOptionValue("port")));
}

From source file:de.zazaz.iot.bosch.indego.util.IndegoMqttAdapter.java

public static void main(String[] args) {
    System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-normal.xml");

    Options options = new Options();

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*w w w.j a  v a  2  s .  c om*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder("c") //
            .longOpt("config") //
            .desc("The configuration file to use") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("d") //
            .longOpt("debug") //
            .desc("Logs more details") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndegoMqttAdapter.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    if (cmds.hasOption("d")) {
        System.setProperty("log4j.configurationFile", "log4j2-indegoMqttAdapter-debug.xml");
    }

    String configFileName = cmds.getOptionValue('c');
    File configFile = new File(configFileName);

    if (!configFile.exists()) {
        System.err.println(String.format("The specified config file (%s) does not exist", configFileName));
        System.err.println();
        System.exit(2);
        return;
    }

    Properties properties = new Properties();
    try (InputStream in = new FileInputStream(configFile)) {
        properties.load(in);
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
        System.err.println(String.format("Was not able to load the properties file (%s)", configFileName));
        System.err.println();
    }

    MqttIndegoAdapterConfiguration config = new MqttIndegoAdapterConfiguration();
    config.setIndegoBaseUrl(properties.getProperty("indego.mqtt.device.base-url"));
    config.setIndegoUsername(properties.getProperty("indego.mqtt.device.username"));
    config.setIndegoPassword(properties.getProperty("indego.mqtt.device.password"));
    config.setMqttBroker(properties.getProperty("indego.mqtt.broker.connection"));
    config.setMqttClientId(properties.getProperty("indego.mqtt.broker.client-id"));
    config.setMqttUsername(properties.getProperty("indego.mqtt.broker.username"));
    config.setMqttPassword(properties.getProperty("indego.mqtt.broker.password"));
    config.setMqttTopicRoot(properties.getProperty("indego.mqtt.broker.topic-root"));
    config.setPollingIntervalMs(Integer.parseInt(properties.getProperty("indego.mqtt.polling-interval-ms")));

    MqttIndegoAdapter adapter = new MqttIndegoAdapter(config);
    adapter.startup();
}

From source file:cc.twittertools.search.api.RunQueriesThrift.java

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

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(//  w  ww  . j a v  a 2 s. c o  m
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    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(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);
        int i = 1;
        Set<Long> tweetIds = new HashSet<Long>();
        for (TResult result : results) {
            if (!tweetIds.contains(result.id)) {
                tweetIds.add(result.id);
                out.println(
                        String.format("%s Q0 %d %d %f %s", query.getId(), result.id, i, result.rsv, runtag));
                if (verbose) {
                    out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
                }
                i++;
            }
        }
    }
    out.close();
}

From source file:edu.sdsc.scigraph.owlapi.loader.BatchOwlLoader.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;//w  w  w.  java 2  s  . co m
    try {
        cmd = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BatchOwlLoader.class.getSimpleName(), getOptions());
        System.exit(-1);
    }

    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    OwlLoadConfiguration config = mapper.readValue(new File(cmd.getOptionValue('c').trim()),
            OwlLoadConfiguration.class);
    load(config);
    // TODO: Is Guice causing this to hang? #44
    System.exit(0);
}

From source file:de.peregrinus.autocopyreport.AutoCopyReport.java

public static void main(String[] args) {
    SongInfo si;//from w ww.j ava  2s .  c  o  m

    String openlpPath = "";
    String crPath = "";
    String crDataPath = "";
    String crPassword = "";

    System.out.println("AutoCopyReport v.1.00.00");
    System.out.println("(c) 2014 Volksmission Freudenstadt");
    System.out.println("Author: Christoph Fischer <christoph.fischer@volksmission.de>");
    //System.out.println("Available under the General Public License (GPL) v2");
    System.out.println();

    // get options
    Options options = new Options();
    options.addOption("h", "help", false, "display a list of available options");
    options.addOption(OptionBuilder.withLongOpt("openlp-path").withDescription("path to OpenLP data directory")
            .hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-path")
            .withDescription("path to the CopyReport program directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("copyreport-data-path")
            .withDescription("path to the CopyReport data directory").hasArg().withArgName("PATH").create());
    options.addOption(OptionBuilder.withLongOpt("password")
            .withDescription("internal password for the CopyReport database").hasArg().withArgName("PASSWORD")
            .create());

    // parse command line
    try {
        // parse the command line arguments
        CommandLineParser parser = new GnuParser();
        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("AutoCopyReport", options);
            System.exit(0);
        } else {
            if (line.hasOption("openlp-path")) {
                openlpPath = line.getOptionValue("openlp-path") + "/songs/songs.sqlite";
                System.out.println("OpenLP data path: " + openlpPath);
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your OpenLP data folder by using the --openlp-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-path")) {
                crPath = line.getOptionValue("copyreport-path");
                System.out.println("Copyreport application database: " + crPath + "/ccldata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport program folder by using the --copyreport-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("copyreport-data-path")) {
                crDataPath = line.getOptionValue("copyreport-data-path");
                System.out.println("Copyreport user database: " + crDataPath + "/userdata.h2.db");
            } else {
                System.out.println(
                        "ERROR: Please supply the path to your CopyReport data folder by using the --copyreport-data-path parameter.");
                System.exit(0);
            }
            if (line.hasOption("password")) {
                crPassword = line.getOptionValue("password");
            } else {
                System.out.println(
                        "ERROR: Please supply the internal password for the CopyReport database by using the --password parameter.");
                System.exit(0);
            }
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage());
        System.exit(0);
    }

    SongDatabaseConnector sdb = new SongDatabaseConnector(openlpPath);
    SongRepository cdb = new SongRepository(crPath + "/ccldata", "sa", crPassword);

    CopyReport rpt = new CopyReport(crDataPath + "/userdata", "sa", crPassword);
    //rpt.createPeriod("2014");

    List<Song> songs = sdb.findLicensedSongs();
    for (Song song : songs) {
        System.out.println(song.title + ": " + song.ccliNumber);
        if (song.ccliNumber.matches("-?\\d+(\\.\\d+)?")) {
            si = cdb.findById(song.ccliNumber);
            if (si != null)
                rpt.reportSong(si);
        } else {
            System.out.println("Format error: '" + song.ccliNumber + "' is not numeric.");
        }
    }

    // wrap up: close the databases
    cdb.close();
    rpt.close();
    sdb.close();

}

From source file:edu.stanford.muse.Main.java

public static void main(String args[]) throws Exception {
    Options options = getOpt();/*from w  ww . j av a  2  s  .com*/
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    if (cmd.hasOption("debug"))
        PropertyConfigurator.configure("log4j.properties.debug");
    else if (cmd.hasOption("debug-address-book"))
        PropertyConfigurator.configure("log4j.properties.ab");
    else if (cmd.hasOption("debug-groups"))
        PropertyConfigurator.configure("log4j.properties.groups");

    String cacheDir = cmd.getOptionValue('c');
    if (cacheDir == null)
        cacheDir = defaultCacheDir;
    Archive.prepareBaseDir(cacheDir); // prepare default lexicon files etc.
    String alternateEmailAddrs = cmd.getOptionValue('a');
    if (alternateEmailAddrs == null)
        alternateEmailAddrs = defaultAlternateEmailAddrs;

    String[] files = cmd.getArgs();
    for (String file : files) {
        if (!new File(file).canRead()) {
            System.err.println("Sorry, cannot read file: " + file);
            System.exit(2);
        }
    }
    Archive archive = getMessages(alternateEmailAddrs, cacheDir, files);

    String sessionName = "default";

    //      GroupAssigner groupAssigner = doGroups(addressBook, allDocs);

    archive.postProcess();
    // set up results with default # of terms per superdoc
    //        archive.indexer.summarizer.recomputeCards((Collection) archive.getAllDocs(), archive.getAddressBook().getOwnNamesSet(), Summarizer.DEFAULT_N_CARD_TERMS);
    SimpleSessions.saveArchive(cacheDir, sessionName, archive);
}

From source file:fi.helsinki.cs.iot.kahvihub.KahviHub.java

public static void main(String[] args) throws InterruptedException {
    // create Options object
    Options options = new Options();
    // add conf file option
    options.addOption("c", true, "config file");
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*from  ww  w . ja v  a2 s.c  o  m*/
    try {
        cmd = parser.parse(options, args);
        String configFile = cmd.getOptionValue("c");
        if (configFile == null) {
            Log.e(TAG, "The config file option was not provided");
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("d", options);
            System.exit(-1);
        } else {
            try {
                HubConfig hubConfig = ConfigurationFileParser.parseConfigurationFile(configFile);
                Path libdir = Paths.get(hubConfig.getLibdir());
                if (hubConfig.isDebugMode()) {
                    File dir = libdir.toFile();
                    if (dir.exists() && dir.isDirectory())
                        for (File file : dir.listFiles())
                            file.delete();
                }
                final IotHubHTTPD server = new IotHubHTTPD(hubConfig.getPort(), libdir, hubConfig.getHost());
                init(hubConfig);
                try {
                    server.start();
                } catch (IOException ioe) {
                    Log.e(TAG, "Couldn't start server:\n" + ioe);
                    System.exit(-1);
                }
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    @Override
                    public void run() {
                        server.stop();
                        Log.i(TAG, "Server stopped");
                    }
                });

                while (true) {
                    Thread.sleep(1000);
                }
            } catch (ConfigurationParsingException | IOException e) {
                System.out.println("1:" + e.getMessage());
                Log.e(TAG, e.getMessage());
                System.exit(-1);
            }
        }

    } catch (ParseException e) {
        System.out.println(e.getMessage());
        Log.e(TAG, e.getMessage());
        System.exit(-1);
    }
}