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:org.mmadsen.sim.transmissionlab.models.MultipleNeutralTraitModel.java

public static void main(String[] args) {
    // parse command line options to see if this is a batch run
    Options cliOptions = new Options();
    cliOptions.addOption("b", false, "enable batch mode");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {/*from   www. j a v  a 2s  .c o m*/
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException ex) {
        System.out.println("ERROR: Command line exception: " + ex.toString());
        System.exit(1);
    }

    SimInit init = new SimInit();
    MultipleNeutralTraitModel model = new MultipleNeutralTraitModel();

    model.preModelLoadSetup();

    model.isBatchExecution = cmd.hasOption("b");
    String paramFile = null;

    if (model.isBatchExecution) {
        if (!cmd.getArgList().isEmpty()) {
            System.out.println(cmd.getArgList().toString());
            paramFile = (String) cmd.getArgList().get(0);
            System.out.println("debug: " + paramFile);
        }
    }

    System.out.println("INFO: batch mode setting: " + model.isBatchExecution);

    init.loadModel(model, paramFile, model.isBatchExecution);
}

From source file:org.mmadsen.sim.transmissionlab.models.NeutralCTModel.java

public static void main(String[] args) {
    // parse command line options to see if this is a batch run
    Options cliOptions = new Options();
    cliOptions.addOption("b", false, "enable batch mode");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {//from   w w w . j  a v  a 2  s.  c om
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException ex) {
        System.out.println("ERROR: Command line exception: " + ex.toString());
        System.exit(1);
    }

    SimInit init = new SimInit();
    NeutralCTModel model = new NeutralCTModel();

    model.preModelLoadSetup();

    model.isBatchExecution = cmd.hasOption("b");
    String paramFile = null;

    if (model.isBatchExecution) {
        if (!cmd.getArgList().isEmpty()) {
            System.out.println(cmd.getArgList().toString());
            paramFile = (String) cmd.getArgList().get(0);
            System.out.println("debug: " + paramFile);
        }
    }

    System.out.println("INFO: batch mode setting: " + model.isBatchExecution);

    init.loadModel(model, paramFile, model.isBatchExecution);
}

From source file:org.mrgeo.cmd.findholes.FindHoles.java

@Override
public int run(String[] args, Configuration conf, ProviderProperties providerProperties) {

    CommandLine line = null;
    try {/*from   www .ja  v a2s .c  o  m*/
        CommandLineParser parser = new GnuParser();
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        new HelpFormatter().printHelp("findholes <options> <input>", options);
        return -1;
    }

    if (line != null) {
        if (line.hasOption("v")) {
            LoggingUtils.setDefaultLogLevel(LoggingUtils.INFO);
        }
        if (line.hasOption("d")) {
            LoggingUtils.setDefaultLogLevel(LoggingUtils.DEBUG);
        }

        if (line.hasOption("l")) {
            System.out.println("Using local runner");
            try {
                HadoopUtils.setupLocalRunner(conf);
            } catch (IOException ioe) {
                ioe.printStackTrace();
                return -1;
            }
        }

        String tmp = line.getOptionValue("z");
        zoomLevel = Integer.parseInt(tmp);
        out = line.getOptionValue("o");

        // DataProviderFactory.PROVIDER_PROPERTY_USER_ROLES
        ProviderProperties props = null;
        if (line.hasOption("r")) {
            props = new ProviderProperties("", line.getOptionValue("r"));
        } else {
            props = new ProviderProperties();
        }

        List<String> al = line.getArgList();
        System.out.print("Input:     ");
        for (String a : al) {
            System.out.print(a + " ");
        }
        System.out.println();
        System.out.println("Output:    " + out);
        System.out.println("ZoomLevel: " + zoomLevel);

        System.out.println();

        FindHolesDriver fhd = new FindHolesDriver();
        try {
            fhd.runJob(al.get(0), out, zoomLevel, props, conf);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        return 0;
    }
    return -1;
}

From source file:org.nuxeo.launcher.NuxeoLauncher.java

/**
 * @since 5.6/*from w  w  w. j  ava2s .co m*/
 */
protected static CommandLine parseOptions(String[] args) throws ParseException {
    initParserOptions();
    CommandLineParser parser = new PosixParser();
    CommandLine cmdLine = null;
    Boolean stopAfterParsing = true;
    try {
        cmdLine = parser.parse(launcherOptions, args);
        if (cmdLine.hasOption(OPTION_HELP) || cmdLine.getArgList().contains(OPTION_HELP)) {
            printLongHelp();
        } else if (cmdLine.getArgList().isEmpty()) {
            printShortHelp();
        } else {
            stopAfterParsing = false;
        }
    } catch (UnrecognizedOptionException e) {
        log.error(e.getMessage());
        printShortHelp();
    } catch (MissingArgumentException e) {
        log.error(e.getMessage());
        printShortHelp();
    } catch (ParseException e) {
        log.error("Error while parsing command line: " + e.getMessage());
        printShortHelp();
    } finally {
        if (stopAfterParsing) {
            throw new ParseException("Invalid command line");
        }
    }
    return cmdLine;
}

From source file:org.objectweb.proactive.core.ssh.SSHClient.java

public static void main(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption(OPT_PASSWORD, true, "Password for password authentication");
    options.addOption(OPT_USERNAME, true, "Username");
    options.addOption(OPT_IDENTITY, true, "Identity file");
    options.addOption(OPT_IDENTITY_PASSWORD, true, "Password for identity file");
    options.addOption(OPT_HELP, false, "Help");
    options.addOption(OPT_VERBOSE, false, "Verbose");

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

    String username = System.getProperty("user.name");
    String password = null;/*  ww w  . j  a  va2 s  .c  om*/
    File identity = null;
    String identityPassword = null;
    String hostname = null;

    if (cmd.hasOption(OPT_HELP)) {
        printHelp(true);
    }

    if (cmd.hasOption(OPT_USERNAME)) {
        username = cmd.getOptionValue(OPT_USERNAME);
    }

    if (cmd.hasOption(OPT_PASSWORD)) {
        password = cmd.getOptionValue(OPT_PASSWORD);
    }

    if (cmd.hasOption(OPT_IDENTITY)) {
        identity = new File(cmd.getOptionValue(OPT_IDENTITY));
        if (!identity.exists()) {
            System.err.println("[E] specified identity file," + identity + ", does not exist");
            System.exit(EXIT_ERROR);
        }
        if (!identity.isFile()) {
            System.err.println("[E] specified identity file" + identity + " is not a file");
            System.exit(EXIT_ERROR);
        }
        if (!identity.canRead()) {
            System.err.println("[E] specified identity file" + identity + " is not readable");
            System.exit(EXIT_ERROR);
        }
    }

    if (cmd.hasOption(OPT_IDENTITY_PASSWORD)) {
        identityPassword = cmd.getOptionValue(OPT_IDENTITY_PASSWORD);
    }

    if (cmd.hasOption(OPT_VERBOSE)) {
        verbose = true;
    }

    List<String> remArgs = cmd.getArgList();
    if (remArgs.size() == 0) {
        System.err.println("[E] You must specify an hostname");
        printHelp(true);
    }

    hostname = remArgs.remove(0);
    int exitCode = EXIT_ERROR;

    try {
        Connection conn = new Connection(hostname);
        conn.connect();

        boolean isAuthenticated = false;

        // 1. Password authentication requested
        if (password != null) {
            isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated) {
                info("Password authentication succeeded");
            } else {
                info("Password authentication failed");
            }
        } else {
            // 2. Pubkey authentication

            // 2.1 An identity file is specified use it 
            if (identity != null) {
                isAuthenticated = conn.authenticateWithPublicKey(username, identity, identityPassword);
                if (isAuthenticated) {
                    info("Pubkey authentication succeeded with " + identity);
                } else {
                    info("Pubkey authentication failed with " + identity);
                }
            } else {
                // 2.2 Try to find identity files automagically
                SshConfig config = new SshConfig();
                SSHKeys keys = new SSHKeys(config.getKeyDir());
                for (String id : keys.getKeys()) {
                    File f = new File(id);
                    if (!(f.exists() && f.isFile() && f.canRead())) {
                        continue;
                    }

                    isAuthenticated = conn.authenticateWithPublicKey(username, f, identityPassword);
                    info("Pubkey authentication succeeded with " + f);
                    if (isAuthenticated) {
                        break;
                    }
                }
            }
        }

        if (!isAuthenticated) {
            System.err.println("[E] Authentication failed");
            System.exit(2);
        }

        conn.setTCPNoDelay(true);
        Session sess = conn.openSession();

        sess.execCommand(buildCmdLine(remArgs));

        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();

        byte[] buffer = new byte[8192];

        while (true) {
            if ((stdout.available() == 0) && (stderr.available() == 0)) {

                /* Even though currently there is no data available, it may be that new data arrives
                 * and the session's underlying channel is closed before we call waitForCondition().
                 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may
                 * be set together.
                 */
                int conditions = sess.waitForCondition(
                        ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 0);

                /* Wait no longer than 2 seconds (= 2000 milliseconds) */
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {

                    /* A timeout occured. */
                    throw new IOException("Timeout while waiting for data from peer.");
                }

                /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */
                if ((conditions & ChannelCondition.EOF) != 0) {

                    /* The remote side won't send us further data... */
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        // PROACTIVE-879: Ugly fix
                        // Calling Session.getExitStatus() can throw an NPE for an unknown reason
                        // After some investigation, I noticed that a subsequent call to this method could succeed
                        // So we try to call session.getExitStatus() until it does not throw an NPE or the timeout expires
                        TimeoutAccounter ta = TimeoutAccounter.getAccounter(1000);
                        while (!ta.isTimeoutElapsed()) {
                            try {
                                exitCode = sess.getExitStatus();
                                break;
                            } catch (NullPointerException e) {
                                Thread.yield();
                            }
                        }

                        break;
                    }
                }

                /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */

                // You can be paranoid and check that the library is not going nuts:
                // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)
                //   throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
            }

            /* If you below replace "while" with "if", then the way the output appears on the local
             * stdout and stder streams is more "balanced". Addtionally reducing the buffer size
             * will also improve the interleaving, but performance will slightly suffer.
             * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)
             */
            while (stdout.available() > 0) {
                int len = stdout.read(buffer);
                if (len > 0) { // this check is somewhat paranoid
                    System.out.write(buffer, 0, len);
                }
            }

            while (stderr.available() > 0) {
                int len = stderr.read(buffer);
                if (len > 0) { // this check is somewhat paranoid
                    System.err.write(buffer, 0, len);
                }
            }
        }

        sess.close();
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(EXIT_ERROR);
    }
    System.exit(exitCode);
}

From source file:org.opennms.features.newts.converter.rrd.converter.JRobinConverter.java

public void execute(final String[] args) throws ParseException, ConverterException, RrdException {
    if (args.length == 0) {
        LogUtils.errorf(this, "no files or directories specified!");
        System.exit(1);/*from  ww w.  ja  v a  2 s. c o m*/
    }

    final Options options = new Options();
    options.addOption("h", "help", false, "This help.");
    options.addOption("f", "factory", true,
            "The JRobin factory to use. (Default: " + DEFAULT_JROBIN_FACTORY + ")");
    options.addOption("l", "log", true, "The log level to use. (Default: " + DEFAULT_LOG_LEVEL + ")");
    options.addOption("t", "threads", true,
            "Number of threads to start. (Default: " + DEFAULT_NUMBER_OF_THREADS + ")");
    options.addOption("c", "clean", false,
            "Remove old single-metric JRBs and temporal files. (Use it only after migrating all your files)");
    options.addOption("v", "validate", false, "Validate current JRBs ffiles.");

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

    LogUtils.setLevel(Level.valueOf(cmd.getOptionValue("l", DEFAULT_LOG_LEVEL)));
    RrdBackendFactory.setDefaultFactory(cmd.getOptionValue("f", DEFAULT_JROBIN_FACTORY));

    final Set<File> rrds = new ConcurrentSkipListSet<File>();

    if (cmd.hasOption("h")) {
        new HelpFormatter().printHelp("jrobin-converter [options] [file-or-directory1] [...file-or-directoryN]",
                options);
        System.exit(1);
    }
    if (cmd.getArgList().size() == 0) {
        LogUtils.infof(this, "No files or directories specified!  Exiting.");
        System.exit(0);
    }
    if (cmd.hasOption("c")) {
        new RrdCleaner().execute(cmd);
        System.exit(1);
    }
    if (cmd.hasOption("v")) {
        new RrdValidator().execute(cmd);
        System.exit(1);
    }

    int threads = DEFAULT_NUMBER_OF_THREADS;
    if (cmd.hasOption("t")) {
        try {
            threads = Integer.valueOf(cmd.getOptionValue("t"));
        } catch (final NumberFormatException e) {
            LogUtils.warnf(JRobinConverter.class, e, "failed to format -t %s to a number",
                    cmd.getOptionValue("t"));
        }
    }
    final ExecutorService executor = Executors.newFixedThreadPool(threads);

    for (final Object arg : cmd.getArgList()) {
        LogUtils.infof(this, "Scanning %s for storeByGroup data.", arg);
        final File f = new File((String) arg);
        if (f.exists()) {
            if (f.isDirectory()) {
                rrds.addAll(findGroupRrds(f));
                for (final File rrdFile : findGroupRrds(f)) {
                    consolidateRrd(executor, rrdFile);
                }
            } else {
                consolidateRrd(executor, f);
            }
        }
    }
    LogUtils.infof(this, "Finished scanning for storeByGroup RRDs. (Total RRD count: %d)", m_total.get());

    executor.shutdown();
}

From source file:org.opennms.features.newts.converter.rrd.converter.RrdCleaner.java

public void execute(final CommandLine cmd) {
    for (final Object arg : cmd.getArgList()) {
        LogUtils.infof(this, "Scanning %s for single-metric JRBs and temporal files.", arg);
        final File f = new File((String) arg);
        if (f.exists() && f.isDirectory()) {
            for (final File rrdFile : findRrds(f)) {
                cleanRrd(rrdFile);/*  w  w  w.j  a  va2  s .c o m*/
            }
        } else {
            LogUtils.warnf(this, "File or directory %s doesn't exist", f);
        }
    }
}

From source file:org.opennms.features.newts.converter.rrd.converter.RrdValidator.java

public void execute(final CommandLine cmd) {
    for (final Object arg : cmd.getArgList()) {
        LogUtils.infof(this, "Scanning %s for corrupted JRBs.", arg);
        final File f = new File((String) arg);
        if (f.exists() && f.isDirectory()) {
            for (final File rrdFile : findRrds(f)) {
                validateRrd(rrdFile);//from ww  w  . j  a va  2 s.c  om
            }
        } else {
            LogUtils.warnf(this, "File or directory %s doesn't exist", f);
        }
        LogUtils.infof(this, "Invalid files found: %s", invalidFiles);
    }
}

From source file:org.opennms.netmgt.config.tester.ConfigTester.java

public static void main(String[] argv) {

    FilterDaoFactory.setInstance(new ConfigTesterFilterDao());
    DataSourceFactory.setInstance(new ConfigTesterDataSource());
    ConfigTester tester = BeanUtils.getBean("configTesterContext", "configTester", ConfigTester.class);

    final CommandLineParser parser = new PosixParser();

    final Options options = new Options();
    options.addOption("h", "help", false, "print this help and exit");
    options.addOption("a", "all", false, "check all supported configuration files");
    options.addOption("l", "list", false, "list supported configuration files and exit");
    options.addOption("v", "verbose", false, "list each configuration file as it is tested");
    options.addOption("i", "ignore-unknown", false,
            "ignore unknown configuration files and continue processing");

    final CommandLine line;
    try {/*from w w w  . ja v  a2  s  .c  om*/
        line = parser.parse(options, argv, false);
    } catch (ParseException e) {
        System.err.println("Invalid usage: " + e.getMessage());
        System.err.println("Run 'config-tester -h' for help.");
        System.exit(1);

        return; // not reached; here to eliminate warning on line being uninitialized
    }

    final boolean ignoreUnknown = line.hasOption("i");

    if ((line.hasOption('l') || line.hasOption('h') || line.hasOption('a'))) {
        if (line.getArgList().size() > 0) {
            System.err
                    .println("Invalid usage: No arguments allowed when using the '-a', '-h', or '-l' options.");
            System.err.println("Run 'config-tester -h' for help.");
            System.exit(1);
        }
    } else {
        if (line.getArgs().length == 0) {
            System.err.println("Invalid usage: too few arguments.  Use the '-h' option for help.");
            System.exit(1);
        }
    }

    boolean verbose = line.hasOption('v');

    DataSourceFactory.setInstance(new ConfigTesterDataSource());

    if (line.hasOption('l')) {
        System.out.println("Supported configuration files: ");
        for (String configFile : tester.getConfigs().keySet()) {
            System.out.println("    " + configFile);
        }
        System.out.println("Note: not all OpenNMS configuration files are currently supported.");
    } else if (line.hasOption('h')) {
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(
                "config-tester -a\nOR: config-tester [config files]\nOR: config-tester -l\nOR: config-tester -h",
                options);
    } else if (line.hasOption('a')) {
        for (String configFile : tester.getConfigs().keySet()) {
            tester.testConfig(configFile, verbose, ignoreUnknown);
        }
    } else {
        for (String configFile : line.getArgs()) {
            tester.testConfig(configFile, verbose, ignoreUnknown);
        }
    }
}

From source file:org.opennms.netmgt.provision.service.vmware.VmwareRequisitionTool.java

public static void main(String[] args) throws Exception {
    final Options options = new Options();

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

    @SuppressWarnings("unchecked")
    List<String> arguments = (List<String>) cmd.getArgList();

    if (arguments.size() < 1) {
        usage(options, cmd);//  ww  w.ja  v  a2 s. co  m
        System.exit(1);
    }

    String urlString = arguments.remove(0).replaceFirst("vmware", "http"); // Internal trick to avoid confusions.
    URL url = new URL(urlString);

    // Parse vmware-config.xml and retrieve the credentials to avoid initialize Spring
    if (url.getUserInfo() == null) {
        File cfg = new File(ConfigFileConstants.getFilePathString(), "vmware-config.xml");
        if (cfg.exists()) {
            String username = null;
            String password = null;
            VmwareConfig config = JaxbUtils.unmarshal(VmwareConfig.class, cfg);
            for (VmwareServer srv : config.getVmwareServerCollection()) {
                if (srv.getHostname().equals(url.getHost())) {
                    username = srv.getUsername();
                    password = srv.getPassword();
                }
            }
            if (username == null || password == null) {
                throw new IllegalArgumentException(
                        "Can't retrieve credentials for " + url.getHost() + " from " + cfg);
            }
            int i = urlString.lastIndexOf("//");
            if (i > 0) {
                urlString = urlString.substring(0, i + 2) + username + ':' + password + '@'
                        + urlString.substring(i + 2);
            }
            url = new URL(urlString);
        }
    }

    VmwareRequisitionUrlConnection c = new VmwareRequisitionUrlConnection(url) {
        @Override
        protected Requisition getExistingRequisition() {
            // This is not elegant but it is necessary to avoid booting Spring
            File req = new File(ConfigFileConstants.getFilePathString(),
                    "imports" + File.separator + m_foreignSource + ".xml");
            if (req.exists()) {
                return JaxbUtils.unmarshal(Requisition.class, req);
            }
            return null;
        }
    };
    c.connect();
    InputStream is = c.getInputStream();
    if (is == null) {
        System.err.println("Couldn't generate requisition from " + urlString);
        System.exit(1);
    } else {
        System.out.println(IOUtils.toString(is, "UTF-8"));
    }
}