Example usage for org.apache.commons.cli CommandLine getArgList

List of usage examples for org.apache.commons.cli CommandLine getArgList

Introduction

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

Prototype

public List getArgList() 

Source Link

Document

Retrieve any left-over non-recognized options and arguments

Usage

From source file:ca.uqac.info.monitor.BeepBeepMonitor.java

public static void main(String[] args) {
    int verbosity = 1, slowdown = 0, tcp_port = 0;
    boolean show_stats = false, to_stdout = false;
    String trace_filename = "", pipe_filename = "", event_name = "message";
    final MonitorFactory mf = new MonitorFactory();

    // In case we open a socket
    ServerSocket m_serverSocket = null;
    Socket m_connection = null;//from  w ww . j  av a2 s  .  co m

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("version")) {
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("slowdown")) {
        slowdown = Integer.parseInt(c_line.getOptionValue("slowdown"));
        if (verbosity > 0)
            System.err.println("Slowdown factor: " + slowdown + " ms");
    }
    if (c_line.hasOption("stats")) {
        show_stats = true;
    }
    if (c_line.hasOption("csv")) {
        // Will output data in CSV format to stdout
        to_stdout = true;
    }
    if (c_line.hasOption("eventname")) {
        // Set event name
        event_name = c_line.getOptionValue("eventname");
    }
    if (c_line.hasOption("t")) {
        // Read events from a trace
        trace_filename = c_line.getOptionValue("t");
    }
    if (c_line.hasOption("p")) {
        // Read events from a pipe
        pipe_filename = c_line.getOptionValue("p");
    }
    if (c_line.hasOption("k")) {
        // Read events from a TCP port
        tcp_port = Integer.parseInt(c_line.getOptionValue("k"));
    }
    if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) {
        System.err.println("ERROR: you must specify at most one of trace file or named pipe");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no input formula specified");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    // Instantiate the event notifier
    boolean notify = (verbosity > 0);
    EventNotifier en = new EventNotifier(notify);
    en.m_slowdown = slowdown;
    en.m_csvToStdout = to_stdout;
    // Create one monitor for each input file and add it to the notifier 
    for (String formula_filename : remaining_args) {
        try {
            String formula_contents = FileReadWrite.readFile(formula_filename);
            Operator op = Operator.parseFromString(formula_contents);
            op.accept(mf);
            Monitor mon = mf.getMonitor();
            Map<String, String> metadata = getMetadata(formula_contents);
            metadata.put("Filename", formula_filename);
            en.addMonitor(mon, metadata);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(ERR_IO);
        } catch (Operator.ParseException e) {
            System.err.println("Error parsing input formula");
            System.exit(ERR_PARSE);
        }
    }

    // Read trace and iterate
    // Opens file
    PipeReader pr = null;
    try {
        if (!pipe_filename.isEmpty()) {
            // We tell the pipe reader we read a pipe
            File f = new File(pipe_filename);
            if (verbosity > 0)
                System.err.println("Reading from pipe named " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, false);
        } else if (!trace_filename.isEmpty()) {
            // We tell the pipe reader we read a regular file
            File f = new File(trace_filename);
            if (verbosity > 0)
                System.err.println("Reading from file " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, true);
        } else if (tcp_port > 0) {
            // We tell the pipe reader we read from a socket
            if (verbosity > 0)
                System.err.println("Reading from TCP port " + tcp_port);
            m_serverSocket = new ServerSocket(tcp_port);
            m_connection = m_serverSocket.accept();
            pr = new PipeReader(m_connection.getInputStream(), en, false);
        } else {
            // We tell the pipe reader we read from standard input
            if (verbosity > 0)
                System.err.println("Reading from standard input");
            pr = new PipeReader(System.in, en, false);
        }
    } catch (FileNotFoundException ex) {
        // We print both trace and pipe since one of them must be empty
        System.err.println("ERROR: file not found " + trace_filename + pipe_filename);
        System.exit(ERR_IO);
    } catch (IOException e) {
        // Caused by socket error
        e.printStackTrace();
        System.exit(ERR_IO);
    }
    pr.setSeparator("<" + event_name + ">", "</" + event_name + ">");

    // Check parameters for the event notifier
    if (c_line.hasOption("no-trigger")) {
        en.m_notifyOnVerdict = false;
    } else {
        en.m_notifyOnVerdict = true;
    }
    if (c_line.hasOption("mirror")) {
        en.m_mirrorEventsOnStdout = true;
    }

    // Start event notifier
    en.reset();
    Thread th = new Thread(pr);
    long clock_start = System.nanoTime();
    th.start();
    try {
        th.join(); // Wait for thread to finish
    } catch (InterruptedException e1) {
        // Thread is finished
    }
    if (tcp_port > 0 && m_serverSocket != null) {
        // We opened a socket; now we close it
        try {
            m_serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    long clock_end = System.nanoTime();
    int ret_code = pr.getReturnCode();
    switch (ret_code) {
    case PipeReader.ERR_EOF:
        if (verbosity > 0)
            System.err.println("\nEnd of file reached");
        break;
    case PipeReader.ERR_EOT:
        if (verbosity > 0)
            System.err.println("\nEOT received on pipe: closing");
        break;
    case PipeReader.ERR_OK:
        // Do nothing
        break;
    default:
        // An error
        System.err.println("Runtime error");
        System.exit(ERR_RUNTIME);
        break;
    }
    if (show_stats) {
        if (verbosity > 0) {
            System.out.println("Messages:   " + en.m_numEvents);
            System.out.println("Time:       " + (int) (en.m_totalTime / 1000000f) + " ms");
            System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms");
            System.out.println("Max heap:   " + (int) (en.heapSize / 1048576f) + " MB");
        } else {
            // If stats are asked but verbosity = 0, only show time value
            // (both monitor and wall clock) 
            System.out.print((int) (en.m_totalTime / 1000000f));
            System.out.print(",");
            System.out.print((int) ((clock_end - clock_start) / 1000000f));
        }
    }
    System.exit(ERR_OK);
}

From source file:io.s4.tools.loadgenerator.LoadGenerator.java

public static void main(String args[]) {
    Options options = new Options();
    boolean warmUp = false;

    options.addOption(/*from  www  . j  av  a  2  s  . c  o  m*/
            OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r"));

    options.addOption(OptionBuilder.withArgName("display_rate").hasArg()
            .withDescription("Display Rate at specified second boundary").create("d"));

    options.addOption(OptionBuilder.withArgName("adapter_address").hasArg()
            .withDescription("Address of client adapter").create("a"));

    options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg()
            .withDescription("Listener application name").create("g"));

    options.addOption(
            OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o"));

    options.addOption(new Option("w", "Warm-up"));

    CommandLineParser parser = new GnuParser();

    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    int expectedRate = 250;
    if (line.hasOption("r")) {
        try {
            expectedRate = Integer.parseInt(line.getOptionValue("r"));
        } catch (Exception e) {
            System.err.println("Bad expected rate specified " + line.getOptionValue("r"));
            System.exit(1);
        }
    }

    int displayRateIntervalSeconds = 20;
    if (line.hasOption("d")) {
        try {
            displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d"));
        } catch (Exception e) {
            System.err.println("Bad display rate value specified " + line.getOptionValue("d"));
            System.exit(1);
        }
    }

    int updateFrequency = 0;
    if (line.hasOption("f")) {
        try {
            updateFrequency = Integer.parseInt(line.getOptionValue("f"));
        } catch (Exception e) {
            System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f"));
            System.exit(1);
        }
        System.out.printf("Update frequency is %d\n", updateFrequency);
    }

    String clientAdapterAddress = null;
    String clientAdapterHost = null;
    int clientAdapterPort = -1;
    if (line.hasOption("a")) {
        clientAdapterAddress = line.getOptionValue("a");
        String[] parts = clientAdapterAddress.split(":");
        if (parts.length != 2) {
            System.err.println("Bad adapter address specified " + clientAdapterAddress);
            System.exit(1);
        }
        clientAdapterHost = parts[0];

        try {
            clientAdapterPort = Integer.parseInt(parts[1]);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad adapter address specified " + clientAdapterAddress);
            System.exit(1);
        }
    }

    long sleepOverheadMicros = -1;
    if (line.hasOption("o")) {
        try {
            sleepOverheadMicros = Long.parseLong(line.getOptionValue("o"));
        } catch (NumberFormatException e) {
            System.err.println("Bad sleep overhead specified " + line.getOptionValue("o"));
            System.exit(1);
        }
        System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros);
    }

    if (line.hasOption("w")) {
        warmUp = true;
    }

    List loArgs = line.getArgList();
    if (loArgs.size() < 1) {
        System.err.println("No input file specified");
        System.exit(1);
    }

    String inputFilename = (String) loArgs.get(0);

    LoadGenerator loadGenerator = new LoadGenerator();
    loadGenerator.setInputFilename(inputFilename);
    loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds);
    loadGenerator.setExpectedRate(expectedRate);
    loadGenerator.setClientAdapterHost(clientAdapterHost);
    loadGenerator.setClientAdapterPort(clientAdapterPort);
    loadGenerator.run();

    System.exit(0);
}

From source file:io.s4.util.LoadGenerator.java

public static void main(String args[]) {
    Options options = new Options();
    boolean warmUp = false;

    options.addOption(//w w  w .j  av a2s.  c om
            OptionBuilder.withArgName("rate").hasArg().withDescription("Rate (events per second)").create("r"));

    options.addOption(OptionBuilder.withArgName("display_rate").hasArg()
            .withDescription("Display Rate at specified second boundary").create("d"));

    options.addOption(OptionBuilder.withArgName("start_boundary").hasArg()
            .withDescription("Start boundary in seconds").create("b"));

    options.addOption(OptionBuilder.withArgName("run_for").hasArg()
            .withDescription("Run for a specified number of seconds").create("x"));

    options.addOption(OptionBuilder.withArgName("cluster_manager").hasArg().withDescription("Cluster manager")
            .create("z"));

    options.addOption(OptionBuilder.withArgName("sender_application_name").hasArg()
            .withDescription("Sender application name").create("a"));

    options.addOption(OptionBuilder.withArgName("listener_application_name").hasArg()
            .withDescription("Listener application name").create("g"));

    options.addOption(
            OptionBuilder.withArgName("sleep_overhead").hasArg().withDescription("Sleep overhead").create("o"));

    options.addOption(new Option("w", "Warm-up"));

    CommandLineParser parser = new GnuParser();

    CommandLine line = null;
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        System.exit(1);
    }

    int expectedRate = 250;
    if (line.hasOption("r")) {
        try {
            expectedRate = Integer.parseInt(line.getOptionValue("r"));
        } catch (Exception e) {
            System.err.println("Bad expected rate specified " + line.getOptionValue("r"));
            System.exit(1);
        }
    }

    int displayRateIntervalSeconds = 20;
    if (line.hasOption("d")) {
        try {
            displayRateIntervalSeconds = Integer.parseInt(line.getOptionValue("d"));
        } catch (Exception e) {
            System.err.println("Bad display rate value specified " + line.getOptionValue("d"));
            System.exit(1);
        }
    }

    int startBoundary = 2;
    if (line.hasOption("b")) {
        try {
            startBoundary = Integer.parseInt(line.getOptionValue("b"));
        } catch (Exception e) {
            System.err.println("Bad start boundary value specified " + line.getOptionValue("b"));
            System.exit(1);
        }
    }

    int updateFrequency = 0;
    if (line.hasOption("f")) {
        try {
            updateFrequency = Integer.parseInt(line.getOptionValue("f"));
        } catch (Exception e) {
            System.err.println("Bad query udpdate frequency specified " + line.getOptionValue("f"));
            System.exit(1);
        }
        System.out.printf("Update frequency is %d\n", updateFrequency);
    }

    int runForTime = 0;
    if (line.hasOption("x")) {
        try {
            runForTime = Integer.parseInt(line.getOptionValue("x"));
        } catch (Exception e) {
            System.err.println("Bad run for time specified " + line.getOptionValue("x"));
            System.exit(1);
        }
        System.out.printf("Run for time is %d\n", runForTime);
    }

    String clusterManagerAddress = null;
    if (line.hasOption("z")) {
        clusterManagerAddress = line.getOptionValue("z");
    }

    String senderApplicationName = null;
    if (line.hasOption("a")) {
        senderApplicationName = line.getOptionValue("a");
    }

    String listenerApplicationName = null;
    if (line.hasOption("a")) {
        listenerApplicationName = line.getOptionValue("g");
    }

    if (listenerApplicationName == null) {
        listenerApplicationName = senderApplicationName;
    }

    long sleepOverheadMicros = -1;
    if (line.hasOption("o")) {
        try {
            sleepOverheadMicros = Long.parseLong(line.getOptionValue("o"));
        } catch (NumberFormatException e) {
            System.err.println("Bad sleep overhead specified " + line.getOptionValue("o"));
            System.exit(1);
        }
        System.out.printf("Specified sleep overhead is %d\n", sleepOverheadMicros);
    }

    if (line.hasOption("w")) {
        warmUp = true;
    }

    List loArgs = line.getArgList();
    if (loArgs.size() < 1) {
        System.err.println("No input file specified");
        System.exit(1);
    }

    String inputFilename = (String) loArgs.get(0);

    EventEmitter emitter = null;

    SerializerDeserializer serDeser = new KryoSerDeser();

    CommLayerEmitter clEmitter = new CommLayerEmitter();
    clEmitter.setAppName(senderApplicationName);
    clEmitter.setListenerAppName(listenerApplicationName);
    clEmitter.setClusterManagerAddress(clusterManagerAddress);
    clEmitter.setSenderId(String.valueOf(System.currentTimeMillis() / 1000));
    clEmitter.setSerDeser(serDeser);
    clEmitter.init();
    emitter = clEmitter;

    long endTime = 0;
    if (runForTime > 0) {
        endTime = System.currentTimeMillis() + (runForTime * 1000);
    }

    LoadGenerator loadGenerator = new LoadGenerator();
    loadGenerator.setInputFilename(inputFilename);
    loadGenerator.setEventEmitter(clEmitter);
    loadGenerator.setDisplayRateInterval(displayRateIntervalSeconds);
    loadGenerator.setExpectedRate(expectedRate);
    loadGenerator.run();

    System.exit(0);
}

From source file:de.topobyte.utilities.apache.commons.cli.commands.GitRemoteRemove.java

public static void main(String name, CommonsCliArguments arguments) {
    System.out.println(String.format("This is '%s'", name));
    CommandLine line = arguments.getLine();
    List<String> extra = line.getArgList();
    if (extra.size() != 1) {
        if (extra.size() == 0) {
            System.out.println("Please specify a name");
        } else {//w  w w .  jav a  2 s.co m
            System.out.println("Too many arguments");
        }
        arguments.getOptions().usage(name);
        return;
    }

    String remote = extra.get(0);
    System.out.println("remote name: " + remote);
}

From source file:com.twcable.grabbit.tools.cli.CliOptions.java

private static boolean hasValidOptions(CommandLine line) {
    val argList = line.getArgList();
    return (line.hasOption('s') || line.hasOption('m')) && argList.size() == 3;
}

From source file:de.uni_freiburg.informatik.ultimate.licence_manager.Main.java

private static CommandLine parseArguments(final String[] args, final Options cliOptions) {
    final CommandLineParser cliParser = new DefaultParser();
    try {/*from w ww.ja  va 2  s. co  m*/
        final CommandLine cmds = cliParser.parse(cliOptions, args);
        if (!cmds.getArgList().isEmpty()) {
            System.err.print("Superfluous arguments: " + String.join(",", cmds.getArgList()));
            return null;
        }
        return cmds;
    } catch (ParseException e) {
        System.err.println("Exception while parsing command line arguments: " + e.getMessage());
        printHelp(cliOptions);
        return null;
    }
}

From source file:com.cloudera.beeswax.Server.java

/**
 * Parse command line options.//w ww.j a  v a2  s.  c o m
 *
 * -b <port> specifies the port for beeswax to use.
 * -m <port>, if given, starts the metastore at this port.
 */
private static void parseArgs(String[] args) throws ParseException {
    Options options = new Options();

    Option metastoreOpt = new Option("m", "metastore", true, "port to use for metastore");
    metastoreOpt.setRequired(false);
    options.addOption(metastoreOpt);

    Option beeswaxOpt = new Option("b", "beeswax", true, "port to use for beeswax");
    beeswaxOpt.setRequired(true);
    options.addOption(beeswaxOpt);

    Option dtHostOpt = new Option("h", "desktop-host", true, "host running desktop");
    dtHostOpt.setRequired(true);
    options.addOption(dtHostOpt);

    Option dtHttpsOpt = new Option("s", "desktop-https", true, "desktop is running https");
    options.addOption(dtHttpsOpt);

    Option dtPortOpt = new Option("p", "desktop-port", true, "port used by desktop");
    dtPortOpt.setRequired(true);
    options.addOption(dtPortOpt);

    Option superUserOpt = new Option("u", "superuser", true, "Username of Hadoop superuser (default: hadoop)");
    superUserOpt.setRequired(false);
    options.addOption(superUserOpt);

    PosixParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (!cmd.getArgList().isEmpty()) {
        throw new ParseException("Unexpected extra arguments: " + cmd.getArgList());
    }

    for (Option opt : cmd.getOptions()) {
        if (opt.getOpt() == "m") {
            mport = parsePort(opt);
        } else if (opt.getOpt() == "b") {
            bport = parsePort(opt);
        } else if (opt.getOpt() == "u") {
            superUser = opt.getValue();
        } else if (opt.getOpt() == "h") {
            dtHost = opt.getValue();
        } else if (opt.getOpt() == "p") {
            dtPort = parsePort(opt);
        } else if (opt.getOpt() == "s") {
            dtHttps = true;
        }
    }
}

From source file:me.zhanghai.mipsasm.Cli.java

public static boolean checkCommandLine(CommandLine commandLine) {
    @SuppressWarnings("unchecked")
    List<String> args = (List<String>) commandLine.getArgList();
    if (!args.isEmpty()) {
        System.err.println("Unknown argument: " + args);
        printHelp();/*from  w w w  . j a va  2s .c om*/
        return false;
    } else {
        return true;
    }
}

From source file:com.aliyun.openservices.odps.console.commands.ShowPartitionsCommand.java

public static TablePart getTablePartFromPublicCommand(String target) throws ODPSConsoleException {

    String project = null;//from  w  ww .  j a  v a 2  s .  c o  m
    TablePart tablePart = null;

    String originalTarget = target;

    AntlrObject antlr = new AntlrObject(target);
    String[] args = antlr.getTokenStringArray();

    if (args == null || args.length < 1) {
        return null;
    }

    CommandLine cl = getCommandLine(args);

    if (cl.getArgList().size() < 1) {
        return null;
    }

    if (cl.hasOption("p")) {
        project = cl.getOptionValue("p");
        target = StringUtils.join(args, "", 2, args.length);
    } else {
        target = originalTarget;
    }

    tablePart = ODPSConsoleUtils.getTablePartFromPubCommand(target);
    if (null != project) {
        String table = tablePart.tableName;
        tablePart.tableName = project + "." + table;
    }

    return tablePart;
}

From source file:io.proscript.jlight.Runtime.java

public static void run(CommandLine line) throws IOException {

    Environment environment = new Environment();

    if (1 == line.getArgList().size()) {
        File cwdCandidate = new File(line.getArgList().get(0));
        if (cwdCandidate.isDirectory()) {
            environment.setCwd(cwdCandidate);
        } else {//from  ww  w . j  a v  a 2 s.co  m
            throw new IOException("Last argument must be valid source root directory");
        }
    } else {
        environment.setCwd(new File(System.getProperty("user.dir")));
    }

    if (line.hasOption("port")) {
        environment.setPort(Integer.valueOf(line.getOptionValue("port")));
    }

    if (line.hasOption("host")) {
        environment.setHost(line.getOptionValue("host"));
    }

    environment.setCacheDirectory(new File(environment.getCwd().toString() + "/.jlcache"));
    environment.setMainClassName(line.getOptionValue("class"));

    CacheManager cacheManager = new CacheManager(environment);

    try {
        cacheManager.initialize();
    } catch (IOException e) {
        log.log(Level.SEVERE, "Failed to initialize class file cache: %s", e.getMessage());
        return;
    }

    Collection<File> javaFiles = SourcesLocator.locateRecursive(environment.getCwd());

    ApplicationCompiler compiler = new ApplicationCompiler(environment.getCacheDirectory());

    boolean result = false;

    try {
        result = compiler.compile(javaFiles);
    } catch (IOException e) {
        log.log(Level.SEVERE, "Compilation failed: %s", e.getMessage());
        return;
    }

    if (!result) {
        for (Diagnostic diagnostic : compiler.getLastDiagnosticCollector().getDiagnostics()) {
            System.out.println(diagnostic.getMessage(Locale.getDefault()));
            LogRecord record = new LogRecord(Level.SEVERE, diagnostic.getMessage(Locale.getDefault()));
            log.log(record);
        }
    } else {

        Application application = buildApplication(environment);
        ThreadedHTTPServer server = new ThreadedHTTPServer(environment);
        server.run(application);
    }

    try {
        cacheManager.destroy();
    } catch (IOException e) {
        e.printStackTrace();
    }
}