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

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

Introduction

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

Prototype

HelpFormatter

Source Link

Usage

From source file:com.trovit.hdfstree.HdfsTree.java

public static void main(String... args) {
    Options options = new Options();
    options.addOption("l", false, "Use local filesystem.");
    options.addOption("p", true, "Path used as root for the tree.");
    options.addOption("s", false, "Display the size of the directory");
    options.addOption("d", true, "Maximum depth of the tree (when displaying)");

    CommandLineParser parser = new PosixParser();

    TreeBuilder treeBuilder;//from w  w w.  ja v  a 2  s  . com
    FSInspector fsInspector = null;
    String rootPath = null;

    Displayer displayer = new ConsoleDisplayer();

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

        // local or hdfs.
        if (cmd.hasOption("l")) {
            fsInspector = new LocalFSInspector();
        } else {
            fsInspector = new HDFSInspector();
        }

        // check that it has the root path.
        if (cmd.hasOption("p")) {
            rootPath = cmd.getOptionValue("p");
        } else {
            throw new ParseException("Mandatory option (-p) is not specified.");
        }

        if (cmd.hasOption("d")) {
            displayer.setMaxDepth(Integer.parseInt(cmd.getOptionValue("d")));
        }

        if (cmd.hasOption("s")) {
            displayer.setDisplaySize();
        }
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("hdfstree", options);
        System.exit(1);
    }

    treeBuilder = new TreeBuilder(rootPath, fsInspector);
    TreeNode tree = treeBuilder.buildTree();
    displayer.display(tree);

}

From source file:com.sanaldiyar.projects.nanohttpd.nanoinstaller.App.java

public static void main(String[] args) {
    try {//from   w  w w  .  j  av a 2  s. com
        String executableName = new File(
                App.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName();
        Options options = new Options();

        Option destination = OptionBuilder.withArgName("folder").withLongOpt("destination").hasArgs(1)
                .withDescription("destionation folder").withType(String.class).create("d");

        Option lrfolder = OptionBuilder.withArgName("folder").withLongOpt("localrepo").hasArgs(1)
                .withDescription("local repository folder").withType(String.class).create("lr");

        Option rmlrfolder = OptionBuilder.withLongOpt("deletelocalrepo").hasArg(false)
                .withDescription("delete local repository after installation").create("dlr");

        Option help = OptionBuilder.withLongOpt("help").withDescription("print this help").create("h");

        options.addOption(destination);
        options.addOption(lrfolder);
        options.addOption(rmlrfolder);
        options.addOption(help);

        HelpFormatter helpFormatter = new HelpFormatter();

        CommandLineParser commandLineParser = new PosixParser();
        CommandLine commands;
        try {
            commands = commandLineParser.parse(options, args);
        } catch (ParseException ex) {
            System.out.println("Error at parsing arguments");
            helpFormatter.printHelp("java -jar " + executableName, options);
            return;
        }

        if (commands.hasOption("h")) {
            helpFormatter.printHelp("java -jar " + executableName, options);
            return;
        }

        String sdest = commands.getOptionValue("d", "./nanosystem");
        System.out.println("The nano system will be installed into " + sdest);
        File dest = new File(sdest);
        if (dest.exists()) {
            FileUtils.deleteDirectory(dest);
        }
        dest.mkdirs();
        File bin = new File(dest, "bin");
        bin.mkdir();
        File bundle = new File(dest, "bundle");
        bundle.mkdir();
        File conf = new File(dest, "conf");
        conf.mkdir();
        File core = new File(dest, "core");
        core.mkdir();
        File logs = new File(dest, "logs");
        logs.mkdir();
        File nanohttpdcore = new File(dest, "nanohttpd-core");
        nanohttpdcore.mkdir();
        File nanohttpdservices = new File(dest, "nanohttpd-services");
        nanohttpdservices.mkdir();
        File temp = new File(dest, "temp");
        temp.mkdir();
        File apps = new File(dest, "apps");
        apps.mkdir();

        File local = new File(commands.getOptionValue("lr", "./local-repository"));
        Collection<RemoteRepository> repositories = Arrays.asList(
                new RemoteRepository("sanaldiyar-snap", "default", "http://maven2.sanaldiyar.com/snap-repo"),
                new RemoteRepository("central", "default", "http://repo1.maven.org/maven2/"));
        Aether aether = new Aether(repositories, local);

        //Copy core felix main
        System.out.println("Downloading Felix main executable");
        List<Artifact> felixmain = aether.resolve(
                new DefaultArtifact("org.apache.felix", "org.apache.felix.main", "jar", "LATEST"), "runtime");
        for (Artifact artifact : felixmain) {
            if (artifact.getArtifactId().equals("org.apache.felix.main")) {
                FileUtils.copyFile(artifact.getFile(), new File(bin, "felix-main.jar"));
                System.out.println(artifact.getArtifactId());
                break;
            }
        }
        System.out.println("OK");

        //Copy core felix bundles
        System.out.println("Downloading Felix core bundles");
        Collection<String> felixcorebundles = Arrays.asList("fileinstall", "bundlerepository", "gogo.runtime",
                "gogo.shell", "gogo.command");
        for (String felixcorebunlde : felixcorebundles) {
            List<Artifact> felixcore = aether.resolve(new DefaultArtifact("org.apache.felix",
                    "org.apache.felix." + felixcorebunlde, "jar", "LATEST"), "runtime");
            for (Artifact artifact : felixcore) {
                if (artifact.getArtifactId().equals("org.apache.felix." + felixcorebunlde)) {
                    FileUtils.copyFileToDirectory(artifact.getFile(), core);
                    System.out.println(artifact.getArtifactId());
                }
            }
        }
        System.out.println("OK");

        //Copy nanohttpd core bundles
        System.out.println("Downloading nanohttpd core bundles and configurations");
        List<Artifact> nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "nanohttpd", "jar", "LATEST"),
                "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            if (!artifact.getArtifactId().equals("org.osgi.core")) {
                FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
                System.out.println(artifact.getArtifactId());
            }
        }

        nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("com.sanaldiyar.projects", "engender", "jar", "LATEST"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        nanohttpdcorebundle = aether.resolve(
                new DefaultArtifact("org.codehaus.jackson", "jackson-mapper-asl", "jar", "1.9.5"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        nanohttpdcorebundle = aether
                .resolve(new DefaultArtifact("org.mongodb", "mongo-java-driver", "jar", "LATEST"), "runtime");
        for (Artifact artifact : nanohttpdcorebundle) {
            FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore);
            System.out.println(artifact.getArtifactId());
        }

        //Copy nanohttpd conf
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/nanohttpd.conf"),
                new File(dest, "nanohttpd.conf"));
        System.out.println("Configuration: nanohttpd.conf");

        //Copy nanohttpd start script
        File startsh = new File(dest, "start.sh");
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/start.sh"), startsh);
        startsh.setExecutable(true);
        System.out.println("Script: start.sh");

        System.out.println("OK");

        //Copy nanohttpd service bundles
        System.out.println("Downloading nanohttpd service bundles");
        List<Artifact> nanohttpdservicebundle = aether
                .resolve(new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "mongodbbasedsessionhandler",
                        "jar", "1.0-SNAPSHOT"), "runtime");
        for (Artifact artifact : nanohttpdservicebundle) {
            if (artifact.getArtifactId().equals("mongodbbasedsessionhandler")) {
                FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdservices);
                System.out.println(artifact.getArtifactId());
                break;
            }
        }

        //Copy nanohttpd mongodbbasedsessionhandler conf
        FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/mdbbasedsh.conf"),
                new File(dest, "mdbbasedsh.conf"));
        System.out.println("Configuration: mdbbasedsh.conf");

        System.out.println("OK");

        if (commands.hasOption("dlr")) {
            System.out.println("Local repository is deleting");
            FileUtils.deleteDirectory(local);
            System.out.println("OK");
        }

        System.out.println("You can reconfigure nanohttpd and services. To start system run start.sh script");

    } catch (Exception ex) {
        System.out.println("Error at installing.");
    }
}

From source file:com.happy_coding.viralo.coordinator.ViraloRunner.java

/**
 * Main task./*  ww  w. ja v a2s .  c om*/
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    // Parser
    CommandLineParser parser = new PosixParser();

    // Options
    Options options = new Options();

    Option createFriends = OptionBuilder.withDescription("Create friends by using the given keywords.").hasArg()
            .withArgName("keywords").create("createFriends");

    options.addOption(createFriends);
    options.addOption("R", "refreshFollowers", false, "refresh followers for current user.");
    options.addOption("C", "cleanup", false, "delete friends which don't follow");
    options.addOption("S", "smartTweet", false, "Posts a smart tweet.");
    options.addOption("F", "createTrendFriends", false, "Create friends to a random trend.");
    options.addOption("T", "answerTopQuestion", false, "answer a top question and post it.");
    options.addOption("RC", "robotConversation", false, "starts a task which answers mentions automatically.");

    if (args.length < 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar ...jar", options);
        System.exit(0);
    }

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

    if (line.hasOption("createFriends")) {

        String keywords = line.getOptionValue("createFriends");

        Viralo viralo = new Viralo();

        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();

        System.out.println("Create friends for " + forContact.getName());

        viralo.createNewFriends(forContact, keywords, ";");

    } else if (line.hasOption("refreshFollowers")) {

        Viralo viralo = new Viralo();

        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();

        viralo.refreshFollowers(forContact);

    } else if (line.hasOption("cleanup")) {

        Viralo viralo = new Viralo();

        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();

        viralo.cleanup(forContact);

    } else if (line.hasOption("smartTweet")) {
        Viralo viralo = new Viralo();
        viralo.postSmartTweet();
    } else if (line.hasOption("createTrendFriends")) {
        FriendDiscoverer friendDiscoverer = new FriendDiscoverer();
        Contact forContact = friendDiscoverer.returnMyself();
        Viralo viralo = new Viralo();
        viralo.createNewFriends(forContact);
    } else if (line.hasOption("answerTopQuestion")) {
        Viralo viralo = new Viralo();
        viralo.answerTopQuestion();
    } else if (line.hasOption("robotConversation")) {

        boolean taskFlag = true;
        Viralo viralo = new Viralo();

        while (taskFlag) {

            /*
            reply to mentions
             */
            viralo.autoConversation();

            /*
            wait some seconds.
             */
            Thread.sleep(WAIT_MS_BETWEEN_ACTIONS);
        }

    }

    System.exit(0);
}

From source file:edu.washington.data.sentimentreebank.StanfordNLPDict.java

public static void main(String args[]) {
    Options options = new Options();
    options.addOption("d", "dict", true, "dictionary file.");
    options.addOption("s", "sentiment", true, "sentiment value file.");

    CommandLineParser parser = new GnuParser();
    try {//from  w  ww. j a  va  2s. c  o m
        CommandLine line = parser.parse(options, args);
        if (!line.hasOption("dict") && !line.hasOption("sentiment")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("StanfordNLPDict", options);
            return;
        }

        Path dictPath = Paths.get(line.getOptionValue("dict"));
        Path sentimentPath = Paths.get(line.getOptionValue("sentiment"));

        StanfordNLPDict snlp = new StanfordNLPDict(dictPath, sentimentPath);
        String sentence = "take off";
        System.out.printf("sentence [%1$s] %2$s\n", sentence,
                String.valueOf(snlp.getPhraseSentiment(sentence)));

    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("StanfordNLPDict", options);
    } catch (IOException ex) {
        Logger.getLogger(StanfordNLPDict.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ingby.socbox.bischeck.migration.Properties2ServerProperties.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;/*from w ww.j a v a  2 s.com*/
    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("v", "verbose", false, "verbose - do not write to files");
    options.addOption("s", "source", true, "directory old properties.xml is located");
    options.addOption("d", "destination", true, "directory where the new xml files while be stored");

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

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        Util.ShellExit(1);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DB2XMLConvert", options);
        Util.ShellExit(0);
    }

    Properties2ServerProperties converter = new Properties2ServerProperties();

    if (line.hasOption("source")) {
        String sourcedir = line.getOptionValue("source");
        String destdir = ".";
        if (line.hasOption("destination")) {
            destdir = line.getOptionValue("destination");
        }

        converter.createXMLServerProperties(sourcedir, destdir);

    }
}

From source file:cc.twittertools.util.ExtractSubcollection.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  . ja 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);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    while ((status = stream.next()) != null) {
        if (tweetids.contains(status.getId())) {
            out.println(status.getJsonObject().toString());
        }
    }
    stream.close();
    out.close();
}

From source file:com.uber.tchannel.ping.PingClient.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "host", true, "Server Host to connect to");
    options.addOption("p", "port", true, "Server Port to connect to");
    options.addOption("n", "requests", true, "Number of requests to make");
    options.addOption("?", "help", false, "Usage");
    HelpFormatter formatter = new HelpFormatter();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("?")) {
        formatter.printHelp("PingClient", options, true);
        return;//  ww w .  ja v a 2  s . c  o m
    }

    String host = cmd.getOptionValue("h", "localhost");
    int port = Integer.parseInt(cmd.getOptionValue("p", "8888"));
    int requests = Integer.parseInt(cmd.getOptionValue("n", "10000"));

    System.out.println(String.format("Connecting from client to server on port: %d", port));
    new PingClient(host, port, requests).run();
    System.out.println("Stopping Client...");
}

From source file:Compiler.java

/** A command line entry point to the mini Java compiler.
 *///  ww w  . j  av  a  2s  .c  om
public static void main(String[] args) {
    CommandLineParser parser = new BasicParser();
    Options options = new Options();

    options.addOption("L", "LLVM", true, "LLVM Bitcode Output Location.");
    options.addOption("x", "x86", true, "x86 Output File Location");
    options.addOption("l", "llvm", false, "Dump Human Readable LLVM Code.");
    options.addOption("i", "input", true, "Compile to x86 Assembly.");
    options.addOption("I", "interp", false, "Run the interpreter.");
    options.addOption("h", "help", false, "Print this help message.");
    options.addOption("V", "version", false, "Version information.");

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

        if (cmd.hasOption("v")) {
            System.out.println("MiniJava Compiler");
            System.out.println("Written By Mark Jones http://web.cecs.pdx.edu/~mpj/");
            System.out.println("Extended for LLVM by Mitch Souders and Mark Smith");
        }
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("java -jar mjc.jar -i <INPUT> (--x86 <OUT>|--LLVM <OUT>|--llvm)", options);
            System.exit(0);
        }
        int errors = 0;
        if (!cmd.hasOption("i")) {
            System.out.println("-i|--input requires a MiniJava input file");
            System.out.println("--help for more info.");
            errors++;
        }
        if (!cmd.hasOption("x") && !cmd.hasOption("l") && !cmd.hasOption("L") && !cmd.hasOption("I")) {
            System.out.println("--x86|--llvm|--LLVM|--interp required for some sort of output.");
            System.out.println("--help for more info.");
            errors++;
        }

        if (errors > 0) {
            System.exit(1);
        }
        String inputFile = cmd.getOptionValue("i");
        compile(inputFile, cmd);
    } catch (ParseException exp) {
        System.out.println("Argument Error: " + exp.getMessage());
    }
}

From source file:com.rapleaf.hank.cli.AddDomainToDomainGroup.java

/**
 * @param args/*from  www  .  j  a  va2s  . c o  m*/
 * @throws IOException
 * @throws ParseException
 * @throws NumberFormatException
 * @throws InvalidConfigurationException
 */
public static void main(String[] args)
        throws IOException, ParseException, NumberFormatException, InvalidConfigurationException {
    Options options = new Options();
    options.addOption("g", "domain-group", true, "the name of the domain group");
    options.addOption("d", "domain", true, "the name of the domain to be added to the group");
    options.addOption("i", "id", true, "the id for the domain in this group");
    options.addOption("c", "config", true,
            "path of a valid config file with coordinator connection information");
    try {
        CommandLine line = new GnuParser().parse(options, args);
        CommandLineChecker.check(line, options, new String[] { "config", "domain-group", "domain" },
                AddDomainToDomainGroup.class);
        ClientConfigurator configurator = new YamlClientConfigurator(line.getOptionValue("config"));
        addDomainToDomainGroup(configurator, line.getOptionValue("domain-group"), line.getOptionValue("domain"),
                Integer.parseInt(line.getOptionValue("id")));
    } catch (ParseException e) {
        new HelpFormatter().printHelp("add_domain", options);
        throw e;
    }
}

From source file:it.tizianofagni.sparkboost.BoostClassifierExe.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("b", "binaryProblem", false,
            "Indicate if the input dataset contains a binary problem and not a multilabel one");
    options.addOption("z", "labels0based", false,
            "Indicate if the labels IDs in the dataset to classifyLibSvmWithResults are already assigned in the range [0, numLabels-1] included");
    options.addOption("l", "enableSparkLogging", false, "Enable logging messages of Spark");
    options.addOption("w", "windowsLocalModeFix", true,
            "Set the directory containing the winutils.exe command");
    options.addOption("p", "parallelismDegree", true,
            "Set the parallelism degree (default: number of available cores in the Spark runtime");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;/*from ww w. j a v  a2  s  .co m*/
    String[] remainingArgs = null;
    try {
        cmd = parser.parse(options, args);
        remainingArgs = cmd.getArgs();
        if (remainingArgs.length != 3)
            throw new ParseException("You need to specify all mandatory parameters");
    } catch (ParseException e) {
        System.out.println("Parsing failed.  Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                BoostClassifierExe.class.getSimpleName() + " [OPTIONS] <inputFile> <inputModel> <outputFile>",
                options);
        System.exit(-1);
    }

    boolean binaryProblem = false;
    if (cmd.hasOption("b"))
        binaryProblem = true;
    boolean labels0Based = false;
    if (cmd.hasOption("z"))
        labels0Based = true;
    boolean enablingSparkLogging = false;
    if (cmd.hasOption("l"))
        enablingSparkLogging = true;

    if (cmd.hasOption("w")) {
        System.setProperty("hadoop.home.dir", cmd.getOptionValue("w"));
    }

    String inputFile = remainingArgs[0];
    String inputModel = remainingArgs[1];
    String outputFile = remainingArgs[2];

    long startTime = System.currentTimeMillis();

    // Disable Spark logging.
    if (!enablingSparkLogging) {
        Logger.getLogger("org").setLevel(Level.OFF);
        Logger.getLogger("akka").setLevel(Level.OFF);
    }

    // Create and configure Spark context.
    SparkConf conf = new SparkConf().setAppName("Spark MPBoost classifier");
    JavaSparkContext sc = new JavaSparkContext(conf);

    // Load boosting classifier from disk.
    BoostClassifier classifier = DataUtils.loadModel(sc, inputModel);

    // Get the parallelism degree.
    int parallelismDegree = sc.defaultParallelism();
    if (cmd.hasOption("p")) {
        parallelismDegree = Integer.parseInt(cmd.getOptionValue("p"));
    }

    // Classify documents available on specified input file.
    classifier.classifyLibSvm(sc, inputFile, parallelismDegree, labels0Based, binaryProblem, outputFile);
    long endTime = System.currentTimeMillis();
    System.out.println("Execution time: " + (endTime - startTime) + " milliseconds.");
}