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

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

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

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

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*from w w w  .j  av  a  2 s .c  o  m*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:com.baystep.jukeberry.JukeBerry.java

/**
 * @param args the command line arguments
 *//*  www.j  a  va 2 s. c  om*/
public static void main(String[] args) {
    System.out.println("Berry Music\n");

    JukeBerry bm = new JukeBerry();

    buildOptions();
    CommandLineParser cmdParser = new DefaultParser();
    try {
        CommandLine cmd = cmdParser.parse(cmdOptions, args);

        if (cmd.hasOption("h")) {
            cmdHelp.printHelp("BerryMusic", help_Header, cmdOptions, help_Footer, true);
            System.exit(0);
        }

        if (cmd.hasOption("pw"))
            bm.config.httpPort = Integer.parseInt(cmd.getOptionValue("pw"));

        if (cmd.hasOption("ps"))
            bm.config.websocketPort = Integer.parseInt(cmd.getOptionValue("ps"));

        if (cmd.hasOption("d")) {
            String dOpt = cmd.getOptionValue("d");
            bm.config.setDisableOption(dOpt);
        }

        if (cmd.hasOption("ss"))
            bm.config.mpStartService = cmd.getOptionValue("ss");

        if (cmd.hasOption("sc")) {
            BerryLogger.supressConsole();
        }

    } catch (ParseException pe) {
        System.err.println("Command line parsing failed, reason: " + pe.getMessage());
    }

    bm.init();
}

From source file:io.wcm.devops.conga.plugins.aem.tooling.crypto.cli.AemCryptoCli.java

/**
 * CLI entry point//from  ww  w  .  java 2  s  .  c om
 * @param args Command line arguments
 * @throws Exception Exception
 */
//CHECKSTYLE:OFF
public static void main(String[] args) throws Exception {
    //CHECKSTYLE:ON
    CommandLine commandLine = new DefaultParser().parse(CLI_OPTIONS, args, true);

    boolean generateCryptoKeys = commandLine.hasOption(CRYPTO_KEYS_GENERATE);
    boolean ansibleVaultEncrypt = commandLine.hasOption(CRYPTO_KEYS_ANSIBLE_VAULT_ENCRYPT);
    File targetDir = new File(commandLine.getOptionValue(TARGET, "target"));
    String ansibleVaultEncryptPath = commandLine.getOptionValue(ANSIBLE_VAULT_ENCRYPT);
    String ansibleVaultDecryptPath = commandLine.getOptionValue(ANSIBLE_VAULT_DECRYPT);

    if (generateCryptoKeys) {
        CryptoKeys.generate(targetDir, ansibleVaultEncrypt)
                .forEach(file -> System.out.println("Generated: " + file.getPath()));
        return;
    } else if (StringUtils.isNotBlank(ansibleVaultEncryptPath)) {
        AnsibleVault.encrypt(new File(ansibleVaultEncryptPath));
        return;
    } else if (StringUtils.isNotBlank(ansibleVaultDecryptPath)) {
        AnsibleVault.decrypt(new File(ansibleVaultDecryptPath));
        return;
    }

    // print usage help
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(150);
    formatter.printHelp("java -jar conga-aem-crypto-cli-<version>.jar <arguments>", CLI_OPTIONS);
}

From source file:com.picdrop.security.SecureStoreMain.java

static public void main(String[] args)
        throws ParseException, IOException, FileNotFoundException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException, KeyStoreException, InterruptedException {

    CommandLineParser cliP = new DefaultParser();

    Options ops = generateBasicOptions();
    CommandLine cli = cliP.parse(ops, args);
    HelpFormatter hlp = new HelpFormatter();

    SecureStore ss;//  w ww. j  a v a2  s. c  o  m
    String path = ".";

    try {
        if (cli.hasOption("help")) {
            hlp.printHelp("SecureStore", ops);
            System.exit(0);
        }

        if (cli.hasOption("keystore")) {
            path = cli.getOptionValue("keystore", ".");
        }

        if (cli.hasOption("create")) {
            ss = new SecureStore(path, false);
            ss.createKeyStore();
            System.exit(0);
        } else {
            ss = new SecureStore(path, true);
        }

        if (cli.hasOption("list")) {
            Enumeration<String> en = ss.listAlias();
            while (en.hasMoreElements()) {
                System.out.println(en.nextElement());
            }
            System.exit(0);
        }

        if (cli.hasOption("store")) {
            ss.storeValue(cli.getOptionValues("store")[0], cli.getOptionValues("store")[1]);
            ss.writeStore();
            System.exit(0);
        }

        if (cli.hasOption("clear")) {
            ss.deleteValue(cli.getOptionValue("clear"));
            ss.writeStore();
            System.exit(0);
        }
    } finally {
        hlp.printHelp("SecureStore", ops);
        System.exit(0);
    }
}

From source file:com.google.api.codegen.DiscoveryFragmentGeneratorTool.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("h", "help", false, "show usage");
    options.addOption(Option.builder().longOpt("discovery_doc")
            .desc("The Discovery doc representing the service description.").hasArg().argName("DISCOVERY-DOC")
            .required(true).build());//from w ww.  jav a  2 s  .c  o m
    options.addOption(Option.builder().longOpt("overrides").desc("The path to the sample config overrides file")
            .hasArg().argName("OVERRIDES").build());
    options.addOption(Option.builder().longOpt("gapic_yaml").desc("The GAPIC YAML configuration file or files.")
            .hasArg().argName("GAPIC-YAML").required(true).build());
    options.addOption(Option.builder("o").longOpt("output")
            .desc("The directory in which to output the generated fragments.").hasArg()
            .argName("OUTPUT-DIRECTORY").build());
    options.addOption(Option.builder().longOpt("auth_instructions")
            .desc("An @-delimited map of language to auth instructions URL: lang:URL@lang:URL@...").hasArg()
            .argName("AUTH-INSTRUCTIONS").build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    if (cl.hasOption("help")) {
        HelpFormatter formater = new HelpFormatter();
        formater.printHelp("CodeGeneratorTool", options);
    }

    generate(cl.getOptionValue("discovery_doc"), cl.getOptionValues("gapic_yaml"),
            cl.getOptionValue("overrides", ""), cl.getOptionValue("output", ""),
            cl.getOptionValue("auth_instructions", ""));
}

From source file:com.ignorelist.kassandra.steam.scraper.TaggerCli.java

/**
 * @param args the command line arguments
 * @throws java.io.IOException//  w w w. j  ava  2 s  .  c om
 * @throws org.antlr.runtime.RecognitionException
 * @throws org.apache.commons.cli.ParseException
 */
public static void main(String[] args) throws IOException, RecognitionException, ParseException {
    Options options = buildOptions();
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.out.println(pe.getMessage());
        System.out.println();
        printHelp(options);
        System.exit(0);
        return;
    }
    if (commandLine.hasOption("h")) {
        printHelp(options);
        System.exit(0);
    }
    final PathResolver pathResolver = new PathResolver();

    Configuration configuration;
    Path configurationFile = pathResolver.findConfiguration();
    if (Files.isRegularFile(configurationFile)) {
        configuration = Configuration.fromPropertiesFile(configurationFile);
    } else {
        configuration = new Configuration();
    }
    configuration = toConfiguration(configuration, commandLine);
    //configuration.toProperties().store(System.err, null);

    if (!Files.isRegularFile(configurationFile)) {
        configuration.writeProperties(configurationFile);
        System.err.println(
                "no configuration file present, write based on CLI options: " + configurationFile.toString());
        configuration.toProperties().store(System.err, null);
    }

    Set<Path> sharedConfigPaths = configuration.getSharedConfigPaths();
    if (sharedConfigPaths.size() > 1 && !commandLine.hasOption("w")) {
        System.err.println("multiple sharedconfig.vdf available:\n" + Joiner.on("\n").join(sharedConfigPaths)
                + "\n, can not write to stdout. Need to specify -w or -f with a single sharedconfig.vdf");
        System.exit(1);
    }

    Tagger.Options taggerOptions = Tagger.Options.fromConfiguration(configuration);

    final String[] removeTagsValues = commandLine.getOptionValues("remove");
    if (null != removeTagsValues) {
        taggerOptions.setRemoveTags(Sets.newHashSet(removeTagsValues));
    }

    Set<TagType> tagTypes = configuration.getTagTypes();
    if (null == tagTypes) {
        System.err.println("no tag types!");
        System.exit(1);
    }

    final boolean printTags = commandLine.hasOption("p");

    final HtmlTagLoader htmlTagLoader = new HtmlTagLoader(pathResolver.findCachePath("html"),
            null == configuration.getCacheExpiryDays() ? 7 : configuration.getCacheExpiryDays());
    final BatchTagLoader tagLoader = new BatchTagLoader(htmlTagLoader, configuration.getDownloadThreads());
    if (true || commandLine.hasOption("v")) {
        tagLoader.registerEventListener(new CliEventLoggerLoaded());
    }
    Tagger tagger = new Tagger(tagLoader);

    if (printTags) {
        Set<String> availableTags = tagger.getAvailableTags(sharedConfigPaths, taggerOptions);
        Joiner.on("\n").appendTo(System.out, availableTags);
    } else {
        for (Path path : sharedConfigPaths) {
            VdfNode tagged = tagger.tag(path, taggerOptions);
            if (commandLine.hasOption("w")) {
                Path backup = path.getParent()
                        .resolve(path.getFileName().toString() + ".bak" + new Date().getTime());
                Files.copy(path, backup, StandardCopyOption.REPLACE_EXISTING);
                System.err.println("backup up " + path + " to " + backup);
                Files.copy(new ByteArrayInputStream(tagged.toPrettyString().getBytes(StandardCharsets.UTF_8)),
                        path, StandardCopyOption.REPLACE_EXISTING);
                try {
                    Files.setPosixFilePermissions(path, SHARED_CONFIG_POSIX_PERMS);
                } catch (Exception e) {
                    System.err.println(e);
                }
                System.err.println("wrote " + path);
            } else {
                System.out.println(tagged.toPrettyString());
                System.err.println("pipe to file and copy to: " + path.toString());
            }
        }
    }
}

From source file:com.chigix.autosftp.Application.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("P").longOpt("port").hasArg().build())
            .addOption(Option.builder("h").longOpt("help").desc("Print this message").build())
            .addOption(Option.builder("i").argName("identity_file").hasArg().build());
    int port = 22;
    CommandLine line;//from  ww w . ja va2s .com
    try {
        line = new DefaultParser().parse(options, args);
    } catch (UnrecognizedOptionException ex) {
        System.err.println(ex.getMessage());
        return;
    } catch (ParseException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("autosftp /path/to/watch [user@]host2:[file2]", options, true);
        return;
    }
    String givenPort;
    if (line.hasOption("port") && StringUtils.isNumeric(givenPort = line.getOptionValue("port"))) {
        port = Integer.valueOf(givenPort);
    }
    if (line.getArgs().length < 0) {
        System.err.println("Please provide a path to watch.");
        return;
    }
    localPath = Paths.get(line.getArgs()[0]);
    if (line.getArgs().length < 1) {
        System.err.println("Please provide remote ssh information.");
        return;
    }
    SshAddressParser addressParse;
    try {
        addressParse = new SshAddressParser().parse(line.getArgs()[1]);
    } catch (SshAddressParser.InvalidAddressException ex) {
        System.err.println(ex.getMessage());
        return;
    }
    if (addressParse.getDefaultDirectory() != null) {
        remotePath = Paths.get(addressParse.getDefaultDirectory());
    }
    try {
        sshSession = new JSch().getSession(addressParse.getUsername(), addressParse.getHost(), port);
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    try {
        sshOpen();
    } catch (JSchException ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        sshClose();
    }
    System.out.println("Remote Default Path: " + remotePath);
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            sshClose();
            System.out.println("Bye~~~");
        }

    });
    try {
        watchDir(Paths.get(line.getArgs()[0]));
    } catch (Exception ex) {
        Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.datastax.sparql.ConsoleCompiler.java

public static void main(final String[] args) throws IOException {
    //args = "/examples/modern1.sparql";
    final Options options = new Options();
    options.addOption("f", "file", true, "a file that contains a SPARQL query");
    options.addOption("g", "graph", true,
            "the graph that's used to execute the query [classic|modern|crew|kryo file]");
    // TODO: add an OLAP option (perhaps: "--olap spark"?)

    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;

    try {//ww  w.  j ava2  s.c om
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(1);
        return;
    }

    final InputStream inputStream = commandLine.hasOption("file")
            ? new FileInputStream(commandLine.getOptionValue("file"))
            : System.in;
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder queryBuilder = new StringBuilder();

    if (!reader.ready()) {
        printHelp(1);
    }

    String line;
    while (null != (line = reader.readLine())) {
        queryBuilder.append(System.lineSeparator()).append(line);
    }

    final String queryString = queryBuilder.toString();
    final Graph graph;

    if (commandLine.hasOption("graph")) {
        switch (commandLine.getOptionValue("graph").toLowerCase()) {
        case "classic":
            graph = TinkerFactory.createClassic();
            break;
        case "modern":
            graph = TinkerFactory.createModern();
            System.out.println("Modern Graph Created");
            break;
        case "crew":
            graph = TinkerFactory.createTheCrew();
            break;
        default:
            graph = TinkerGraph.open();
            System.out.println("Graph Created");
            long startTime = System.nanoTime();
            graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
            long endTime = System.nanoTime();
            System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000
                    + " mili seconds");
            break;
        }
    } else {

        graph = TinkerFactory.createModern();
    }

    final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph,
            queryString);

    printWithHeadline("SPARQL Query", queryString);
    printWithHeadline("Traversal (prior execution)", traversal);

    Bytecode traversalByteCode = traversal.asAdmin().getBytecode();

    //JavaTranslator.of(graph.traversal()).translate(traversalByteCode);

    System.out.println("the Byte Code : " + traversalByteCode.toString());
    printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal())
            .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList())));
    printWithHeadline("Traversal (after execution)", traversal);
}

From source file:cz.muni.fi.crocs.JeeTool.Main.java

/**
 * @param args the command line arguments
 *///from w ww. java 2 s  .  co m
public static void main(String[] args) {
    System.out.println("JeeTool \n");

    checkDependencies();

    Options options = OptionsMain.createOptions();

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println("cannot parse parameters");
        OptionsMain.printHelp(options);
        System.err.println(ex.toString());
        return;
    }
    boolean silent = cmd.hasOption("s");
    boolean verbose = cmd.hasOption("v");

    //help
    if (cmd.hasOption("h")) {
        OptionsMain.printHelp(options);
        return;
    }

    String filepath;
    //path to config list of nodes
    if (cmd.hasOption("a")) {
        filepath = cmd.getOptionValue("a");
    } else {
        filepath = "/opt/motePaths.txt";
    }

    //create motelist
    MoteList moteList = new MoteList(filepath);
    if (verbose) {
        moteList.setVerbose();
    }
    if (silent) {
        moteList.setSilent();
    }

    if (verbose) {
        System.out.println("reading motelist from file " + filepath);
    }

    if (cmd.hasOption("i")) {
        List<Integer> ids = new ArrayList<Integer>();
        String arg = cmd.getOptionValue("i");
        String[] IdArgs = arg.split(",");
        for (String s : IdArgs) {
            if (s.contains("-")) {
                int start = Integer.parseInt(s.substring(0, s.indexOf("-")));
                int end = Integer.parseInt(s.substring(s.indexOf("-") + 1, s.length()));
                for (int i = start; i <= end; i++) {
                    ids.add(i);
                }
            } else {
                ids.add(Integer.parseInt(s));
            }
        }
        moteList.setIds(ids);
    }

    moteList.readFile();

    if (cmd.hasOption("d")) {
        //only detect nodes
        return;
    }

    //if make
    if (cmd.hasOption("m") || cmd.hasOption("c") || cmd.hasOption("u")) {
        UploadMain upload = new UploadMain(moteList, cmd);
        upload.runMake();
    }
}

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;/*w w w  . j ava  2  s .c om*/
    }

    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...");
}