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.opennms.protocols.nsclient.CheckNsc.java

/**
 * <p>main</p>/*  ww w. ja  v a2 s  .com*/
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws org.apache.commons.cli.ParseException if any.
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();
    options.addOption("port", true, "the port to connect to");
    options.addOption("password", true, "the password to use when connecting");
    options.addOption("warning", true, "treat the response as a warning if the level is above this value");
    options.addOption("critical", true,
            "treat the response as a critical error if the level is above this value");

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

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();
    if (arguments.size() < 2) {
        usage(options, cmd);
        System.exit(1);
    }

    NsclientManager client = null;
    NsclientPacket response = null;
    NsclientCheckParams params = null;

    String host = arguments.remove(0);
    String command = arguments.remove(0);
    int warningLevel = 0;
    int criticalLevel = 0;
    int port = 1248;

    if (cmd.hasOption("warning")) {
        warningLevel = Integer.parseInt(cmd.getOptionValue("warning"));
    }
    if (cmd.hasOption("critical")) {
        criticalLevel = Integer.parseInt(cmd.getOptionValue("critical"));
    }
    if (cmd.hasOption("port")) {
        port = Integer.parseInt(cmd.getOptionValue("port"));
    }

    /* whatever's left gets merged into "arg1&arg2&arg3" */
    StringBuffer clientParams = new StringBuffer();
    if (!arguments.isEmpty()) {
        for (Iterator<String> i = arguments.iterator(); i.hasNext();) {
            clientParams.append(i.next());
            if (i.hasNext()) {
                clientParams.append("&");
            }
        }
    }

    try {
        client = new NsclientManager(host, port);
    } catch (Throwable e) {
        usage(options, cmd, "An error occurred creating a new NsclientManager.", e);
    }

    if (cmd.hasOption("password")) {
        client.setPassword(cmd.getOptionValue("password"));
    }

    try {
        client.setTimeout(5000);
        client.init();
    } catch (Throwable e) {
        usage(options, cmd, "An error occurred initializing the NsclientManager.", e);
    }

    try {
        params = new NsclientCheckParams(warningLevel, criticalLevel, clientParams.toString());
    } catch (Throwable e) {
        usage(options, cmd, "An error occurred creating the parameter object.", e);
    }

    try {
        response = client.processCheckCommand(NsclientManager.convertStringToType(command), params);
    } catch (Throwable e) {
        usage(options, cmd, "An error occurred processing the command.", e);
    }

    if (response == null) {
        usage(options, cmd, "No response was returned.", null);
    } else {
        System.out.println("NsclientPlugin: " + command + ": "
                + NsclientPacket.convertStateToString(response.getResultCode()) /* response.getResultCode() */
                + " (" + response.getResponse() + ")");
    }
}

From source file:org.opennms.protocols.vmware.VmwareCimQuery.java

public static void main(String[] args) throws ParseException {
    String hostname, username, password;

    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() < 3) {
        usage(options, cmd);/*from   w ww  .  j  ava2s. c  o m*/
        System.exit(1);
    }

    hostname = arguments.remove(0);
    username = arguments.remove(0);
    password = arguments.remove(0);

    cimQuery(hostname, username, password);
}

From source file:org.opennms.protocols.vmware.VmwareConfigBuilder.java

public static void main(String[] args) throws ParseException {
    String hostname = null;/*from w  w w .  j  ava2  s.c  o  m*/
    String username = null;
    String password = null;
    String rrdRepository = null;

    final Options options = new Options();

    options.addOption("rrdRepository", true,
            "set rrdRepository path for generated config files, default: '/opt/opennms/share/rrd/snmp/'");

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

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

    if (arguments.size() < 3) {
        usage(options, cmd);
        System.exit(1);
    }

    hostname = arguments.remove(0);
    username = arguments.remove(0);
    password = arguments.remove(0);

    if (cmd.hasOption("rrdRepository")) {
        rrdRepository = cmd.getOptionValue("rrdRepository");
    } else {
        rrdRepository = "/opt/opennms/share/rrd/snmp/";
    }

    TrustManager[] trustAllCerts = new TrustManager[1];

    trustAllCerts[0] = new TrustAllManager();

    SSLContext sc = null;
    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }
    };

    HttpsURLConnection.setDefaultHostnameVerifier(hv);

    VmwareConfigBuilder vmwareConfigBuilder;

    vmwareConfigBuilder = new VmwareConfigBuilder(hostname, username, password);

    try {
        vmwareConfigBuilder.generateData(rrdRepository);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opennms.protocols.wmi.CheckWmi.java

/**
 * <p>main</p>//  ww w  .j a  v  a 2 s .  c  o m
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws org.apache.commons.cli.ParseException if any.
 */
public static void main(final String[] args) throws ParseException {
    final Options options = new Options();
    options.addOption("domain", true, "the NT/AD domain the credentials belong to");
    options.addOption("wmiClass", true, "the object class in WMI to query");
    options.addOption("wmiNamespace", true,
            "the namespace in WMI to use (default: " + WmiParams.WMI_DEFAULT_NAMESPACE + ")");
    options.addOption("wmiObject", true, "the object to query in WMI");
    options.addOption("wmiWql", true, "the query string to execute in WMI");
    options.addOption("op", true, "compare operation: NOOP, EQ, NEQ, GT, LT");
    options.addOption("value", true, "the value to compare to");
    options.addOption("matchType", true, "type of matching for multiple results: all, none, some, one");

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

    @SuppressWarnings("unchecked")
    List<String> arguments = (List<String>) cmd.getArgList();
    if (arguments.size() < 3) {
        usage(options, cmd);
        System.exit(1);
    }

    final String host = arguments.remove(0);
    final String user = arguments.remove(0);
    final String pass = arguments.remove(0);

    String wmiClass = "";
    if (cmd.hasOption("wmiClass")) {
        wmiClass = cmd.getOptionValue("wmiClass");
    } /* else {
        usage(options, cmd);
        System.exit(1);
      }*/

    String wmiObject = "";
    if (cmd.hasOption("wmiObject")) {
        wmiObject = cmd.getOptionValue("wmiObject");
    } else {
        usage(options, cmd);
        System.exit(1);
    }

    String wmiNamespace = WmiParams.WMI_DEFAULT_NAMESPACE;
    if (cmd.hasOption("wmiNamespace")) {
        wmiNamespace = cmd.getOptionValue("wmiNamespace");
    }

    String wmiWql = "";
    if (cmd.hasOption("wmiWql")) {
        wmiWql = cmd.getOptionValue("wmiWql");
    } /*else {
      usage(options, cmd);
      System.exit(1);
      } */

    String compVal = "";
    if (cmd.hasOption("value")) {
        compVal = cmd.getOptionValue("value");
    } else {
        usage(options, cmd);
        System.exit(1);
    }

    String compOp = "";
    if (cmd.hasOption("op")) {
        compOp = cmd.getOptionValue("op");
    } else {
        usage(options, cmd);
        System.exit(1);
    }

    String domain = "";
    if (cmd.hasOption("domain")) {
        domain = cmd.getOptionValue("domain");
    }

    String matchType = "all";
    if (cmd.hasOption("matchType")) {
        matchType = cmd.getOptionValue("matchType");
    }

    try {
        // Hold the WMI objects from the results.
        List<Object> wmiObjects;
        // Create the check parameters holder.
        WmiParams clientParams;
        if (wmiWql == null || wmiWql.length() == 0)
            clientParams = new WmiParams(WmiParams.WMI_OPERATION_INSTANCEOF, compVal, compOp, wmiClass,
                    wmiObject);
        else
            clientParams = new WmiParams(WmiParams.WMI_OPERATION_WQL, compVal, compOp, wmiWql, wmiObject);
        // Create the WMI Manager
        final WmiManager mgr = new WmiManager(host, user, pass, domain, matchType);
        mgr.setNamespace(wmiNamespace);

        // Connect to the WMI server.
        mgr.init();

        // Perform the operation specified in the parameters.
        final WmiResult result = mgr.performOp(clientParams);
        // And retrieve the WMI objects from the results.
        wmiObjects = result.getResponse();

        // Now output a brief report of the check results.
        System.out.println("Checking: " + wmiWql + " for " + wmiObject + " Op: " + compOp + " Val: " + compVal);
        System.out.println("Check results: " + WmiResult.convertStateToString(result.getResultCode()) + " ("
                + wmiObjects.size() + ")");

        for (int i = 0; i < wmiObjects.size(); i++) {
            System.out.println(
                    "Result for (" + (i + 1) + ") " + wmiClass + "\\" + wmiObject + ": " + wmiObjects.get(i));
        }

        // Disconnect when we're done.
        mgr.close();
    } catch (final Exception e) {
        e.printStackTrace();
    }
}

From source file:org.opennms.tools.JrbToRrdConverter.java

/**
 * Main method starting the program. Initializing rrdtool binary, amount of threads
 * and parsing the command line arguments. After
 *
 * @param args Arguments from command line
 * @throws ParseException//ww  w . ja  v  a 2  s  .  c om
 */
public static void main(String[] args) throws ParseException {

    // Init defaults
    String rrdTool = DEFAULT_RRDTOOL;
    int threadCount = DEFAULT_THREADS;

    // current directory
    String path = "./";

    final Options options = new Options();

    // Init options for rrdtool binary and the amount of threads to use
    options.addOption(CMD_OPTION.RRDTOOL.option(), true,
            "set rrdtool to use for converting XML to RRD, default: '" + DEFAULT_RRDTOOL + "'");
    options.addOption(CMD_OPTION.THREADS.option(), true,
            "set number of threads to use, default: " + DEFAULT_THREADS);

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

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

    // No arguments given
    if (arguments.size() < 1) {
        usage(options, cmd);
        System.exit(1);
    }

    // Modified rrdtool binary path
    if (cmd.hasOption(CMD_OPTION.RRDTOOL.option())) {
        rrdTool = cmd.getOptionValue(CMD_OPTION.RRDTOOL.option());
    }

    // Modified amount of threads
    if (cmd.hasOption(CMD_OPTION.THREADS.option())) {
        try {
            threadCount = Integer.valueOf(cmd.getOptionValue(CMD_OPTION.THREADS.option()));
        } catch (NumberFormatException numberFormatException) {
            usage(options, cmd);
            System.exit(1);
        }
    }

    path = arguments.remove(0);

    /*
     * Initialize the JRobin to RRDtool converter for a given directory with JRB files
     * to convert, rrdtool binary path and the amount of threads.
     */
    JrbToRrdConverter jrbToRrdConverter = new JrbToRrdConverter(path, rrdTool, threadCount);

    // Run conversion starts also a monitoring thread to calculate how many JRB/s are converted
    jrbToRrdConverter.runConversion();
}

From source file:org.opens.tanaguru.cli.Tanaguru.java

/**
 * //w w w.java2  s .c  o m
 * @param path
 * @param argument
 * @param testWritable
 * @return whether the given level is valid
 */
private static boolean isValidPageUrl(CommandLine cl) {
    if (cl.getArgList().isEmpty()) {
        System.out.println("\nPlease specify at least one URL\n");
        return false;
    }
    for (int i = 0; i < cl.getArgs().length; i++) {
        try {
            URL url = new URL(cl.getArgs()[i]);
        } catch (MalformedURLException ex) {
            System.out.println("\nThe URL " + cl.getArgs()[i] + " is malformed\n");
            return false;
        }
    }
    return true;
}

From source file:org.opens.tanaguru.cli.Tanaguru.java

private static boolean isValidFilePath(CommandLine cl) {
    if (cl.getArgList().isEmpty()) {
        System.out.println("\nPlease specify at least one file\n");
        return false;
    }/* w  w w.java  2s . co m*/
    for (int i = 0; i < cl.getArgs().length; i++) {
        File file = FileUtils.getFile(cl.getArgs()[i]);
        if (!file.canRead()) {
            System.out.println("\nThe file " + file.getAbsolutePath() + " is unreadable.\n");
            return false;
        }
    }
    return true;
}

From source file:org.opf_labs.fmts.fidget.SigGenCommand.java

/**
 * @param args//from  w  ww  . j  av a  2s  .com
 * @throws MimeTypeException
 * @throws IOException
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws MimeTypeException, IOException {
    // create the command line parser
    CommandLineParser parser = new PosixParser();

    // create the Options
    Options options = new Options();
    // Main option, setting the signature file
    options.addOption(OptionBuilder.withLongOpt("sig-file").withDescription("use this mime-info signature file")
            .hasArg().withArgName("FILE").create("s"));
    // 
    options.addOption("A", "alone", false,
            "use only the supplied signature file, do not load the embedded ones");
    options.addOption("C", "convert-to-droid", false, "convert supplied signature file into DROID form");
    options.addOption("l", "list", false, "list all known types.");
    options.addOption("?", "help", false, "print help message");

    if (args.length == 0) {
        System.err.println("No identification test file found!");
        printHelp(options);
        return;
    }

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

        // validate that sig-file has been set
        String sigfile = null;
        if (line.hasOption("sig-file")) {
            // print the value of sig-file
            sigfile = line.getOptionValue("sig-file");
        }

        // Check mode:
        if (line.hasOption("?")) {
            printHelp(options);

        } else if (line.hasOption("C")) {
            // Convert mode:
            if (sigfile == null) {
                System.err.println("No signature file argument found!");
                return;
            }
            System.out.println("Generate DROID signature...");
            MimeInfo mi = null;
            FileInputStream sigStr = new FileInputStream(sigfile);
            try {
                mi = MimeInfoUtils.parser(sigStr);
            } catch (JAXBException e) {
                e.printStackTrace();
                return;
            } finally {
                sigStr.close();
            }
            SigDefSubmission sigdef = MimeInfoUtils.toDroidSigDef(mi);
            // TODO Make is possible to print out the signature submission definition?
            // This just creates a submission template, but we could output a PRONOM record too.
            PRONOMSigGenerator.generatePRONOMSigFile(sigdef);
        } else if (line.hasOption("l")) {
            // Set up Tika:
            TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A"));
            TikaSigTester.printTypes(tst);

        } else {
            // Set up Tika:
            TikaSigTester tst = SigGenCommand.tikaStarter(sigfile, line.hasOption("A"));
            // Return result:
            System.out.println("" + tst.identify(new File("" + line.getArgList().get(0))));
            return;
        }
    } catch (ParseException exp) {
        System.out.println("Unexpected exception:" + exp.getMessage() + "\n");
        printHelp(options);
    }
}

From source file:org.polago.deployconf.DeployConfRunner.java

/**
 * Main entry point./*from ww  w  .  j  a va  2 s.  c  om*/
 *
 * @param args the runtime program arguments
 */
public static void main(String[] args) {
    Options options = new Options();

    Option help = new Option("h", "help", false, "Display usage information");
    options.addOption(help);

    Option version = new Option("v", "version", false, "Display version information and exit");
    options.addOption(version);

    Option interactive = new Option("i", "interactive", false, "Run in interactive mode");
    options.addOption(interactive);

    Option forceInteractive = new Option("I", "force-interactive", false,
            "Run in interactive mode and configure all tasks");
    options.addOption(forceInteractive);

    Option quiet = new Option("q", "quiet", false, "Suppress most messages");
    options.addOption(quiet);

    Option debug = new Option("d", "debug", false, "Print Debug Information");
    options.addOption(debug);

    boolean debugEnabled = false;

    Option repoDir = new Option("r", "repo", true,
            "Repository directory to use for storing deployment configs");
    options.addOption(repoDir);

    Option configFile = new Option("f", "deployment-config-file", true,
            "File to use for storing the deployment config");
    options.addOption(configFile);

    Option templatePath = new Option("t", "deployment-template-path", true,
            "Path to use for locating the deployment template in the " + "<INPUT> file. Default is '"
                    + DEFAULT_TEMPLATE_PATH + "'");
    options.addOption(templatePath);

    CommandLineParser parser = new DefaultParser();

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

        if (cmd.hasOption(version.getOpt())) {
            System.out.print(projectProperties.getName());
            System.out.print(" version ");
            System.out.println(projectProperties.getVersion());
            System.out.println(projectProperties.getCopyrightMessage());
            System.exit(0);
        }

        if (cmd.hasOption(help.getOpt())) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(projectProperties.getName() + " [OPTION]... <INPUT> <OUTPUT>",
                    projectProperties.getHelpHeader(), options, "");
            System.exit(0);
        }

        if (cmd.hasOption(debug.getOpt())) {
            logger.info("Activating Debug Logging");
            debugEnabled = true;
            setLogConfig("logback-debug.xml");
        } else if (cmd.hasOption(quiet.getOpt())) {
            setLogConfig("logback-quiet.xml");
        }

        RunMode mode = RunMode.NON_INTERACTIVE;
        if (cmd.hasOption(forceInteractive.getOpt())) {
            mode = RunMode.FORCE_INTERACTIVE;
        } else if (cmd.hasOption(interactive.getOpt())) {
            mode = RunMode.INTERACTIVE;
        }

        DeployConfRunner instance = new DeployConfRunner(mode);

        String envRepoDir = instance.getRepositoryDirectoryFromEnvironment();

        if (cmd.hasOption(repoDir.getOpt())) {
            String rd = cmd.getOptionValue(repoDir.getOpt());
            logger.debug("Using repository directory: {}", rd);
            instance.setRepositoryDirectory(rd);
        } else if (envRepoDir != null) {
            logger.debug("Using repository directory from environment {}: {}", ENV_DEPLOYCONF_REPO, envRepoDir);
            instance.setRepositoryDirectory(envRepoDir);
        } else {
            String rd = getDefaultRepository();
            instance.setRepositoryDirectory(rd);
            logger.debug("Using default repository directory: {}", rd);
        }
        Path repo = FileSystems.getDefault().getPath(instance.getRepositoryDirectory());
        if (!Files.exists(repo)) {
            Files.createDirectories(repo);
        } else if (!Files.isDirectory(repo)) {
            logger.error("Specified repository is not a directory: {}", repo);
            System.exit(1);
        }

        instance.setGroupManager(
                new FileSystemConfigGroupManager(Paths.get(instance.getRepositoryDirectory())));

        if (cmd.hasOption(configFile.getOpt())) {
            String f = cmd.getOptionValue(configFile.getOpt());
            logger.debug("Using explicit deployment file: {}", f);
            instance.setDeploymentConfigPath(FileSystems.getDefault().getPath(f));
        }

        if (cmd.hasOption(templatePath.getOpt())) {
            String path = cmd.getOptionValue(templatePath.getOpt());
            logger.debug("Using deployment template path: {}", path);
            instance.setDeploymentTemplatePath(path);
        }

        List<String> argList = cmd.getArgList();
        if (argList.size() != 2) {
            System.out.println("usage: " + projectProperties.getName() + " <INPUT> <OUTPUT>");
            System.exit(1);
        }
        System.exit(instance.run(argList.get(0), argList.get(1)));
    } catch (ParseException e) {
        logger.error("Command Line Parse Error: " + e.getMessage(), e);
        System.exit(1);
    } catch (Exception e) {
        String msg = "Internal Error: " + e.toString();
        if (!debugEnabled) {
            msg += "\n(use the -d option to print stacktraces)";
        }
        logger.error(msg, e);
        System.exit(2);
    }
}

From source file:org.pshdl.commandline.PSHDLCompiler.java

@SuppressWarnings("rawtypes")
private void run(String[] args) throws Exception {
    final MultiOption options = getOptions();
    final CommandLine parse = options.parse(args);
    final List argList = parse.getArgList();
    if (parse.hasOption("help") || (args.length == 0)) {
        options.printHelp(System.out);
        return;/*from w w  w.  jav  a2  s  .  c  o  m*/
    }
    if (parse.hasOption("version")) {
        System.out.println(PSHDLCompiler.class.getSimpleName() + " version: " + HDLCore.VERSION);
        return;
    }
    final long lastCheck = prefs.getLong("LAST_CHECK", -1);
    final long oneWeek = TimeUnit.MILLISECONDS.convert(7, TimeUnit.DAYS);
    final long oneWeekAgo = System.currentTimeMillis() - oneWeek;
    if ((oneWeekAgo > lastCheck) && !parse.hasOption("nocheck")) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final InputStream stream = new URL(
                            "http://api.pshdl.org/api/v0.1/compiler/version?localVersion=" + HDLCore.VERSION)
                                    .openStream();
                    final byte[] byteArray = ByteStreams.toByteArray(stream);
                    final String remoteVersion = new String(byteArray, StandardCharsets.UTF_8).trim();
                    if (!remoteVersion.equals(HDLCore.VERSION)) {
                        System.err.println("A new version of this compiler is available: " + remoteVersion
                                + " local version: " + HDLCore.VERSION);
                    } else {
                        prefs.putLong("LAST_CHECK", System.currentTimeMillis());
                    }
                } catch (final Exception e) {
                }
            }
        }).start();
    }
    final String arg = argList.get(0).toString();
    final IOutputProvider iop = implementations.get(arg);
    if (iop == null) {
        System.out.println(
                "No such provider: " + arg + " please try one of: " + implementations.keySet().toString());
        System.exit(1);
        return;
    }
    argList.remove(0);
    final String result = iop.invoke(parse);
    if (result != null) {
        System.out.flush();
        System.err.println(result);
        System.exit(2);
        return;
    }
    System.exit(0);
}