Example usage for org.apache.commons.cli CommandLineParser parse

List of usage examples for org.apache.commons.cli CommandLineParser parse

Introduction

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

Prototype

CommandLine parse(Options options, String[] arguments) throws ParseException;

Source Link

Document

Parse the arguments according to the specified options.

Usage

From source file:com.github.zk1931.zabkv.Main.java

public static void main(String[] args) throws Exception {
    // Options for command arguments.
    Options options = new Options();

    Option port = OptionBuilder.withArgName("port").hasArg(true).isRequired(true).withDescription("port number")
            .create("port");

    Option ip = OptionBuilder.withArgName("ip").hasArg(true).isRequired(true)
            .withDescription("current ip address").create("ip");

    Option join = OptionBuilder.withArgName("join").hasArg(true).withDescription("the addr of server to join.")
            .create("join");

    Option help = OptionBuilder.withArgName("h").hasArg(false).withLongOpt("help")
            .withDescription("print out usages.").create("h");

    options.addOption(port).addOption(ip).addOption(join).addOption(help);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;/*from www . jav  a  2  s .co m*/

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("zabkv", options);
            return;
        }
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("zabkv", options);
        return;
    }

    int zabPort = Integer.parseInt(cmd.getOptionValue("port"));
    String myIp = cmd.getOptionValue("ip");

    if (zabPort < 5000 && zabPort >= 5010) {
        System.err.println("port parameter can have value only between 5000 & 5010");
        System.exit(1);
    }

    int serverPort = zabPort % 5000 + 8000;

    Database db = new Database(myIp, zabPort, cmd.getOptionValue("join"));

    Server server = new Server(serverPort);
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    ServletHolder holder = new ServletHolder(new RequestHandler(db));
    handler.addServletWithMapping(holder, "/*");
    server.start();
    server.join();
    System.out.println("hi");
}

From source file:com.knewton.mapreduce.example.SSTableMRExample.java

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

    long startTime = System.currentTimeMillis();
    Options options = buildOptions();//from  w ww  .  j  a  v a2s  . c o m

    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = cliParser.parse(options, args);
    if (cli.getArgs().length < 2 || cli.hasOption('h')) {
        printUsage(options);
    }
    Job job = getJobConf(cli);

    job.setJarByClass(SSTableMRExample.class);
    job.setOutputKeyClass(LongWritable.class);
    job.setOutputValueClass(StudentEventWritable.class);

    job.setMapperClass(StudentEventMapper.class);
    job.setReducerClass(StudentEventReducer.class);

    job.setInputFormatClass(SSTableColumnInputFormat.class);
    job.setOutputFormatClass(TextOutputFormat.class);
    // input arg
    String inputPaths = cli.getArgs()[0];
    LOG.info("Setting initial input paths to {}", inputPaths);
    SSTableInputFormat.addInputPaths(job, inputPaths);
    // output arg
    FileOutputFormat.setOutputPath(job, new Path(cli.getArgs()[1]));
    if (cli.hasOption('c')) {
        LOG.info("Using compression for output.");
        FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class);
        FileOutputFormat.setCompressOutput(job, true);
    }
    job.waitForCompletion(true);
    LOG.info("Total runtime: {}s", (System.currentTimeMillis() - startTime) / 1000);
}

From source file:com.vaadin.buildhelpers.CompileTheme.java

/**
 * @param args/* w ww  .  j  a  v a  2  s  .  c o  m*/
 * @throws IOException
 * @throws ParseException
 */
public static void main(String[] args) throws IOException, ParseException {
    Options options = new Options();
    options.addOption("t", "theme", true, "the theme to compile");
    options.addOption("v", "theme-version", true, "the version to add to the compiled theme");
    options.addOption("f", "theme-folder", true, "the folder containing the theme");
    CommandLineParser parser = new PosixParser();
    CommandLine params = parser.parse(options, args);
    if (!params.hasOption("theme") || !params.hasOption("theme-folder")) {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CompileTheme.class.getName(), options);
        return;
    }
    String themeName = params.getOptionValue("theme");
    String themeFolder = params.getOptionValue("theme-folder");
    String themeVersion = params.getOptionValue("theme-version");

    // Regular theme
    try {
        processSassTheme(themeFolder, themeName, "styles", themeVersion);
        System.out.println("Compiling theme " + themeName + " styles successful");
    } catch (Exception e) {
        System.err.println("Compiling theme " + themeName + " styles failed");
        e.printStackTrace();
    }
    // Legacy theme w/o .themename{} wrapping
    try {
        processSassTheme(themeFolder, themeName, "legacy-styles", themeVersion);
        System.out.println("Compiling theme " + themeName + " legacy-styles successful");
    } catch (Exception e) {
        System.err.println("Compiling theme " + themeName + " legacy-styles failed");
        e.printStackTrace();
    }
}

From source file:com.boulmier.machinelearning.jobexecutor.JobExecutor.java

public static void main(String[] args) throws ParseException, IOException, InterruptedException {
    Options options = defineOptions();//from  ww w  .jav a 2s.c o  m
    sysMon = new JavaSysMon();
    InetAddress vmscheduler_ip, mongodb_ip = null;
    Integer vmscheduler_port = null, mongodb_port = null;
    CommandLineParser parser = new BasicParser();

    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD)) {
            vmscheduler_port = Integer.valueOf(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGPORTFIELD));
        }
        mongodb_port = (int) (cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                ? cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGMONGOPORTFIELD)
                : JobExecutorConfig.OPTIONS.LOGGING.MONGO_DEFAULT_PORT);
        mongodb_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGMONGOIPFIELD));

        vmscheduler_ip = InetAddress.getByName(cmd.getOptionValue(JobExecutorConfig.OPTIONS.CMD.LONGIPFIELD));

        decryptKey = cmd.getOptionValue("decrypt-key");

        debugState = cmd.hasOption(JobExecutorConfig.OPTIONS.CMD.LONGDEBUGFIELD);

        logger = LoggerFactory.getLogger();
        logger.info("Attempt to connect on master @" + vmscheduler_ip + ":" + vmscheduler_port);

        new RequestConsumer().start();

    } catch (MissingOptionException moe) {
        logger.error(moe.getMissingOptions() + " are missing");
        HelpFormatter help = new HelpFormatter();
        help.printHelp(JobExecutor.class.getSimpleName(), options);

    } catch (UnknownHostException ex) {
        logger.error(ex.getMessage());
    } finally {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                logger.info("JobExeutor is shutting down");
            }
        });
    }
}

From source file:com.dumontierlab.pdb2rdf.cluster.ClusterServer.java

public static void main(String[] args) {

    Options options = createOptions();/*w  w  w  .j a v  a  2  s  .  c o  m*/
    CommandLineParser parser = createCliParser();

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

        if (!cmd.hasOption("dir")) {
            LOG.fatal("You need to specify the input directory");
            System.exit(1);
        }
        File inputDir = new File(cmd.getOptionValue("dir"));
        if (!inputDir.exists() || !inputDir.isDirectory()) {
            LOG.fatal("The specified input directory is not a valid directory");
            System.exit(1);
        }

        int port = DEFAULT_PORT;
        if (cmd.hasOption("port")) {
            try {
                port = Integer.parseInt(cmd.getOptionValue("port"));
            } catch (NumberFormatException e) {
                LOG.fatal("Invalid port number", e);
                System.exit(1);
            }
        }
        boolean gzip = cmd.hasOption("gzip");

        try {
            startServer(inputDir, gzip, port);
        } catch (Exception e) {
            LOG.fatal("Unable to start the server.", e);
            System.exit(1);
        }

    } catch (ParseException e) {
        LOG.fatal("Unable understand your command.");
        printUsage();
        System.exit(1);
    }

}

From source file:com.spotify.cassandra.opstools.CountTombstones.java

/**
 * Counts the number of tombstones, per row, in a given SSTable
 *
 * Assumes RandomPartitioner, standard columns and UTF8 encoded row keys
 *
 * Does not require a cassandra.yaml file or system tables.
 *
 * @param args command lines arguments/*from w  w  w .j  a v a2 s .  co  m*/
 *
 * @throws java.io.IOException on failure to open/read/write files or output streams
 */
public static void main(String[] args) throws IOException, ParseException {
    String usage = String.format("Usage: %s [-l] <sstable> [<sstable> ...]%n", CountTombstones.class.getName());

    final Options options = new Options();
    options.addOption("l", "legend", false, "Include column name explanation");
    options.addOption("p", "partitioner", true, "The partitioner used by database");

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

    if (cmd.getArgs().length < 1) {
        System.err.println("You must supply at least one sstable");
        System.err.println(usage);
        System.exit(1);
    }

    // Fake DatabaseDescriptor settings so we don't have to load cassandra.yaml etc
    Config.setClientMode(true);
    String partitionerName = String.format("org.apache.cassandra.dht.%s",
            options.hasOption("p") ? options.getOption("p") : "RandomPartitioner");
    try {
        Class<?> clazz = Class.forName(partitionerName);
        IPartitioner partitioner = (IPartitioner) clazz.newInstance();
        DatabaseDescriptor.setPartitioner(partitioner);
    } catch (Exception e) {
        throw new RuntimeException("Can't instantiate partitioner " + partitionerName);
    }

    PrintStream out = System.out;

    for (String arg : cmd.getArgs()) {
        String ssTableFileName = new File(arg).getAbsolutePath();

        Descriptor descriptor = Descriptor.fromFilename(ssTableFileName);

        run(descriptor, cmd, out);
    }

    System.exit(0);
}

From source file:be.i8c.sag.wm.is.SwaggerImporter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options options = getOptions();/*w  ww  .ja  v  a  2s  . co  m*/
    CommandLine cmd = parser.parse(options, args);
    HelpFormatter formatter = new HelpFormatter();
    if (cmd.hasOption("h")) {
        formatter.printHelp("", options);
    } else if (cmd.hasOption("is") && cmd.hasOption("u") && cmd.hasOption("p") && cmd.hasOption("swf")
            && cmd.hasOption("pkg")) {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swaggerModel = swaggerParser.read(cmd.getOptionValue("swf"));
        String[] conn = cmd.getOptionValue("is").split(":");
        String host = conn[0];
        String port = "80";
        if (conn.length > 1) {
            port = conn[1];
        }
        ServerConnection sc = new ServerConnection(host, port, cmd.getOptionValue("u"), cmd.getOptionValue("p"),
                false);
        try {
            logger.info("Connecting to server " + host + "(" + port + ")");
            sc.connect();
            logger.info("Connected to server");

            RestImplementation ri = new RestImplementation(sc, swaggerModel, cmd.getOptionValue("pkg"),
                    cmd.getOptionValue("acl"));

            ri.generateImplementation();

        } catch (Throwable e) {
            logger.error("Error: " + e.getMessage());
            //logger.error(e.getStackTrace());
            e.printStackTrace();
        } finally {
            logger.info("Disconnecting from server");
            sc.disconnect();
            ServerConnectionManager.getInstance().closeServerConnectionManager();
            logger.info("Disconnected from server");
            logger.info("BYE");
            System.exit(0);
        }
    }

}

From source file:com.mebigfatguy.roomstore.RoomStore.java

public static void main(String[] args) {
    Options options = createOptions();/*w  ww .j  a  v a2 s  .  c om*/

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cmdLine = parser.parse(options, args);
        String nickname = cmdLine.getOptionValue(NICK_NAME);
        String server = cmdLine.getOptionValue(IRCSERVER);
        String[] channels = cmdLine.getOptionValues(CHANNELS);
        String[] endPoints = cmdLine.getOptionValues(ENDPOINTS);
        String rf = cmdLine.getOptionValue(RF);

        if ((endPoints == null) || (endPoints.length == 0)) {
            endPoints = new String[] { "127.0.0.1" };
        }

        int replicationFactor;
        try {
            replicationFactor = Integer.parseInt(rf);
        } catch (Exception e) {
            replicationFactor = 1;
        }

        final IRCConnector connector = new IRCConnector(nickname, server, channels);

        Cluster cluster = new Cluster.Builder().addContactPoints(endPoints).build();
        final Session session = cluster.connect();

        CassandraWriter writer = new CassandraWriter(session, replicationFactor);
        connector.setWriter(writer);

        connector.startRecording();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                connector.stopRecording();
                session.close();
            }
        }));

    } catch (ParseException pe) {
        System.out.println("Parse Error on command line options:");
        System.out.println(commandLineRepresentation(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("roomstore", options);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.usc.pgroup.floe.client.commands.Signal.java

/**
 * Entry point for Scale command./*  w w  w .j  a  v  a  2 s .co m*/
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    Option pelletNameOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Pellet Name").create("pellet");

    Option signalOption = OptionBuilder.withArgName("data").hasArg().withType(new String())
            .withDescription("signal data to send to the pellet").create("data");

    options.addOption(appOption);
    options.addOption(pelletNameOption);
    options.addOption(signalOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

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

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");
    String pellet = line.getOptionValue("pellet");
    String data = line.getOptionValue("data");

    LOGGER.info("Application: {}", app);
    LOGGER.info("Pellet: {}", pellet);
    LOGGER.info("data: {}", data);

    byte[] datab = Utils.serialize(data);
    try {
        TSignal signal = new TSignal();
        signal.set_destApp(app);
        signal.set_destPellet(pellet);
        signal.set_data(datab);
        FloeClient.getInstance().getClient().signal(signal);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:lapispaste.Main.java

public static void main(String[] args) throws Exception {
    // create Options object
    Options options = new Options();
    String version;/*from  ww w .ja  v  a2 s .c om*/

    version = "0.1";

    // populate Options with.. well options :P
    options.addOption("v", false, "Display version");
    options.addOption("f", true, "File to paste");

    // non-critical options
    options.addOption("t", true, "Code language");
    options.addOption("p", false, "Read from pipe");

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

    // assemble a map of values
    final Map<String, String> pastemap = new HashMap<String, String>();

    if (cmd.hasOption("t"))
        pastemap.put("format", cmd.getOptionValue("t").toString());
    else
        pastemap.put("format", "text");

    // critical options
    if (cmd.hasOption("v"))
        System.out.println("lapispaste version " + version);
    else if (cmd.hasOption("f")) {
        File file = new File(cmd.getOptionValue("f"));
        StringBuffer pdata = readData(new FileReader(file));
        paster(pastemap, pdata);
    } else if (cmd.hasOption("p")) {
        StringBuffer pdata = readData(new InputStreamReader(System.in));
        paster(pastemap, pdata);
    } else {
        // Did not recieve what was expected
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("lapispaste [OPTIONS] [FILE]", options);
    }

}