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

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

Introduction

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

Prototype

DefaultParser

Source Link

Usage

From source file:fr.ortolang.diffusion.client.cmd.ImportZipCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;// w  w  w. j a v a2 s.  c  o  m
    Map<String, String> params = new HashMap<>();
    Map<String, File> files = new HashMap<>();
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }
        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        if (cmd.hasOption("f")) {
            if (cmd.hasOption("upload")) {
                files.put("zippath", new File(cmd.getOptionValue("f")));
            } else {
                params.put("zippath", cmd.getOptionValue("f"));
            }
        } else {
            help();
        }

        if (cmd.hasOption("k")) {
            params.put("wskey", cmd.getOptionValue("k"));
        } else {
            help();
        }

        if (cmd.hasOption("p")) {
            params.put("ziproot", cmd.getOptionValue("p"));
        } else {
            help();
        }

        if (cmd.hasOption("overwrite")) {
            params.put("zipoverwrites", "true");
        }

        OrtolangClient client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());
        String pkey = client.createProcess("import-zip", "Import Zip", params, files);
        System.out.println("Import-Zip process created with key : " + pkey);

        client.logout();
        client.close();

    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:com.hp.mqm.clt.CliParserTest.java

@Test
public void testArgs_missingArgument() throws ParseException {
    CommandLineParser parser = new DefaultParser();
    try {//from  ww  w.  jav  a 2 s  .  c  o  m
        parser.parse(options, new String[] { "-i", "-d" });
        Assert.fail();
    } catch (MissingArgumentException e) {
        Assert.assertEquals("Missing argument for option: d", e.getMessage());
    }
}

From source file:com.github.horrorho.inflatabledonkey.args.PropertyLoader.java

@Override
public boolean test(String[] args) throws IllegalArgumentException {
    try {//from ww  w  .ja v  a 2s .  c  o m
        Map<Option, Property> optionKeyMap = optionKeyMapSupplier.get();

        Options options = new Options();
        optionKeyMap.keySet().forEach(options::addOption);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);

        Map<Property, String> properties = Stream.of(commandLine.getOptions())
                .collect(Collectors.toMap(optionKeyMap::get, this::parse));

        if (properties.containsKey(Property.ARGS_HELP)) {
            help(OptionsFactory.options().keySet());
            return false;
        }

        List<String> operands = commandLine.getArgList();
        switch (operands.size()) {
        case 0:
            // No setAuthenticationProperties credentials
            throw new IllegalArgumentException("missing appleid/ password or authentication token");
        case 1:
            // Authentication token
            properties.put(Property.AUTHENTICATION_TOKEN, operands.get(0));
            break;
        case 2:
            // AppleId/ password pair
            properties.put(Property.AUTHENTICATION_APPLEID, operands.get(0));
            properties.put(Property.AUTHENTICATION_PASSWORD, operands.get(1));
            break;
        default:
            throw new IllegalArgumentException(
                    "too many non-optional arguments, expected appleid/ password or authentication token only");
        }
        Property.setProperties(properties);
        return true;

    } catch (ParseException ex) {
        throw new IllegalArgumentException(ex.getLocalizedMessage());
    }
}

From source file:com.junoyoon.BullsHtml.java

/**
 * @param args//w  w w  .j av  a  2 s .  co m
 */
public static void main(String[] args) {
    final CommandLineParser clp = new DefaultParser();
    CommandLine line = null;

    // parse CLI options
    try {
        line = clp.parse(BullsHtml.OPTS, args);
    } catch (ParseException e) {
        printMessage("Invalid options");
        usage();
        return;
    }
    String sourceEncoding = BullsHtml.enc;
    // get encoding option
    if (line.hasOption("e")) {
        sourceEncoding = line.getOptionValue("e");
    }
    // print usage if -h
    if (line.hasOption("h")) {
        usage();
    }

    if (line.hasOption("v")) {
        BullsHtml.verbose = true;
    }
    String covfile = null;
    if (line.hasOption("f")) {
        covfile = line.getOptionValue("f");
        if (!new File(covfile).exists()) {
            printErrorAndExit(covfile + " does not exists");
        }
    }

    String outputPath = ".";

    if (line.getArgs().length != 1) {
        printErrorAndExit("please provide the html output directory");
    }
    outputPath = line.getArgs()[0];
    File o = new File(outputPath);
    if (!o.exists()) {
        if (!o.mkdirs()) {
            printErrorAndExit(outputPath + " directory can be not created.");
        }
    } else if (!o.isDirectory()) {
        printErrorAndExit(outputPath + " is not directory.");
    } else if (!o.canWrite()) {
        printErrorAndExit(outputPath + " is not writable.");
    }
    BullsHtml bullshtml = new BullsHtml();
    bullshtml.process(covfile);
    if (BullsHtml.baseList.isEmpty()) {
        printErrorAndExit(
                "No coverage was recorded in cov file. please check if src is compiled with coverage on.");
    }
    try {
        bullshtml.copyResources(outputPath);
    } catch (Exception e) {
        printErrorAndExit("The output " + outputPath + " is not writable.", e);
    }
    BullsHtml.sourceEncoding = Encoding.getEncoding(sourceEncoding);
    bullshtml.generateHtml(o);
    bullshtml.generateCloverXml(o);
}

From source file:fi.aalto.drumbeat.GUIDConverter.java

public GUIDConverter(final String[] args) {
    System.out.println("GUIDConverter:");
    final CommandLineParser parser = new DefaultParser();
    initializeOptions();/*from   www .j a v  a  2  s.  c  om*/

    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption("y"))
            defaultAnswer = "y";

        if (commandLine.hasOption("n"))
            defaultAnswer = "n";

        if (commandLine.hasOption("h"))
            help();
        else
            executeCommandLine(commandLine);
    } catch (ParseException e) {
        System.out.println(" " + e.getMessage());
        System.out.println(" Use -h for instructions."); // Unrecognized option: -x

    }
}

From source file:com.ibm.ie.tachyon.fuse.TachyonFuse.java

/**
 * Parses CLI options/* www .  j  a va2s . c o m*/
 * @param args CLI args
 * @return Tachyon-FUSE configuration options
 */
private static TachyonFuseOptions parseOptions(String[] args) {
    final Options opts = new Options();
    final Option mntPoint = Option.builder("m").hasArg().required(false).longOpt("mount-point")
            .desc("Path where tachyon-fuse should be mounted.").build();

    final Option tachyonAddress = Option.builder("t").hasArg().required(false).longOpt("tachyon-master")
            .desc("URI of the Tachyon Master (e.g. tachyon://localhost:19998/").build();

    final Option tachyonRoot = Option.builder("r").hasArg().required(false).longOpt("tachyon-root")
            .desc("Path within tachyon that will be the root of the mount (e.g., /users/foo)").build();

    final Option help = Option.builder("h").required(false).desc("Print this help").build();

    final Option debug = Option.builder("d").required(false).longOpt("debug").desc("Enable FUSE debug output")
            .build();

    final Option fuseOption = Option.builder("o").valueSeparator(',').required(false).hasArgs()
            .desc("FUSE mount options").build();

    opts.addOption(mntPoint);
    opts.addOption(tachyonAddress);
    opts.addOption(tachyonRoot);
    opts.addOption(help);
    opts.addOption(debug);
    opts.addOption(fuseOption);

    final CommandLineParser parser = new DefaultParser();
    try {
        CommandLine cli = parser.parse(opts, args);

        if (cli.hasOption("h")) {
            final HelpFormatter fmt = new HelpFormatter();
            fmt.printHelp(TachyonFuse.class.getName(), opts);
            return null;
        }

        String m = cli.getOptionValue("m");
        String t = cli.getOptionValue("t");
        String r = cli.getOptionValue("r");
        boolean d = cli.hasOption("d");

        List<String> fuseOpts;
        if (cli.hasOption("o")) {
            String[] fopts = cli.getOptionValues("o");
            fuseOpts = new ArrayList<>(fopts.length);
            // keep the -o
            for (int i = 0; i < fopts.length; i++) {
                fuseOpts.add("-o" + fopts[i]);
            }
        } else {
            fuseOpts = Collections.emptyList();
        }

        if (m == null) {
            LOG.info("Mounting on default {}", TachyonFuse.DEFAULT_MOUNT_POINT);
            m = TachyonFuse.DEFAULT_MOUNT_POINT;
        }

        if (t == null) {
            LOG.info("Using default master address {}", TachyonFuse.DEFAULT_MASTER_ADDR);
            t = TachyonFuse.DEFAULT_MASTER_ADDR;
        }

        if (r == null) {
            LOG.info("Using default tachyon root {}", TachyonFuse.DEFAULT_ROOT);
            r = TachyonFuse.DEFAULT_ROOT;
        }

        return new TachyonFuseOptions(m, t, r, d, fuseOpts);
    } catch (ParseException e) {
        System.err.println("Error while parsing CLI: " + e.getMessage());
        final HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(TachyonFuse.class.getName(), opts);
        return null;
    }

}

From source file:alluxio.fuse.AlluxioFuse.java

/**
 * Parses CLI options./* ww  w. j av  a2  s.  c o  m*/
 *
 * @param args CLI args
 * @return Alluxio-FUSE configuration options
 */
private static AlluxioFuseOptions parseOptions(String[] args) {
    final Options opts = new Options();
    final Option mntPoint = Option.builder("m").hasArg().required(false).longOpt("mount-point")
            .desc("Desired local mount point for alluxio-fuse.").build();

    final Option alluxioRoot = Option.builder("r").hasArg().required(false).longOpt("alluxio-root")
            .desc("Path within alluxio that will be used as the root of the FUSE mount "
                    + "(e.g., /users/foo; defaults to /)")
            .build();

    final Option help = Option.builder("h").required(false).desc("Print this help").build();

    final Option fuseOption = Option.builder("o").valueSeparator(',').required(false).hasArgs()
            .desc("FUSE mount options").build();

    opts.addOption(mntPoint);
    opts.addOption(alluxioRoot);
    opts.addOption(help);
    opts.addOption(fuseOption);

    final CommandLineParser parser = new DefaultParser();
    try {
        CommandLine cli = parser.parse(opts, args);

        if (cli.hasOption("h")) {
            final HelpFormatter fmt = new HelpFormatter();
            fmt.printHelp(AlluxioFuse.class.getName(), opts);
            return null;
        }

        String mntPointValue = cli.getOptionValue("m");
        String alluxioRootValue = cli.getOptionValue("r");

        List<String> fuseOpts = new ArrayList<>();
        boolean noUserMaxWrite = true;
        if (cli.hasOption("o")) {
            String[] fopts = cli.getOptionValues("o");
            // keep the -o
            for (final String fopt : fopts) {
                fuseOpts.add("-o" + fopt);
                if (noUserMaxWrite && fopt.startsWith("max_write")) {
                    noUserMaxWrite = false;
                }
            }
        }
        // check if the user has specified his own max_write, otherwise get it
        // from conf
        if (noUserMaxWrite) {
            final long maxWrite = Configuration.getLong(PropertyKey.FUSE_MAXWRITE_BYTES);
            fuseOpts.add(String.format("-omax_write=%d", maxWrite));
        }

        if (mntPointValue == null) {
            mntPointValue = Configuration.get(PropertyKey.FUSE_MOUNT_DEFAULT);
            LOG.info("Mounting on default {}", mntPointValue);
        }

        if (alluxioRootValue == null) {
            alluxioRootValue = Configuration.get(PropertyKey.FUSE_FS_ROOT);
            LOG.info("Using default alluxio root {}", alluxioRootValue);
        }

        final boolean fuseDebug = Configuration.getBoolean(PropertyKey.FUSE_DEBUG_ENABLED);

        return new AlluxioFuseOptions(mntPointValue, alluxioRootValue, fuseDebug, fuseOpts);
    } catch (ParseException e) {
        System.err.println("Error while parsing CLI: " + e.getMessage());
        final HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp(AlluxioFuse.class.getName(), opts);
        return null;
    }
}

From source file:com.octo.mbo.CopyNotes.java

static CommandLine parseCommandLine(String[] args) throws CommandLineException {
    Options options = new Options();
    Option optSource = new Option("s",
            "Source file where the comments can be extracted (only pptx format supported)");
    optSource.setRequired(true);// w  ww  . j av a 2s .c om
    optSource.setArgs(1);
    optSource.setLongOpt("source");
    options.addOption(optSource);

    Option optTarget = new Option("t", "Target file where the comments are merged (case of pptx format)");
    optTarget.setRequired(true);
    optTarget.setArgs(1);
    optTarget.setLongOpt("target");
    options.addOption(optTarget);

    HelpFormatter formatter = new HelpFormatter();
    final String header = "CopyNotes allows to extract, copy and merge notes of pptx files. \n"
            + "Notes can be merged with the notes of an existing files \n"
            + "Notes can be exported to a xml file with a custom format or imported \n"
            + "from this xml format and merged into an existing pptx document. \n"
            + "The target file is updated \n";
    final String footer = "";

    CommandLineParser cliParser = new DefaultParser();
    try {
        return cliParser.parse(options, args);
    } catch (MissingOptionException mex) {
        log.error(mex.getMessage());
        log.debug("Error parsing command line", mex);
        formatter.printHelp(
                "java -jar copypptxnotes-<version>-jar-with-dependencies.jar -s <source> -t <target>", header,
                options, footer);
        throw new CommandLineException("Missing option", mex);
    } catch (ParseException pex) {
        log.debug("Error parsing the command line. Please use CopyComment --help", pex);
        formatter.printHelp(
                "java -jar copypptxnotes-<version>-jar-with-dependencies.jar  -s <source> -t <target>", header,
                options, footer);
        throw new CommandLineException("Parse Exception", pex);
    }
}

From source file:fr.ortolang.diffusion.client.cmd.ReindexCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;/* w  w w. j av  a 2 s.c  o  m*/
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        String type = cmd.getOptionValue("t");
        String service = cmd.getOptionValue("s");
        String status = cmd.getOptionValue("a", "PUBLISHED");
        boolean fakeMode = cmd.hasOption("F");

        if (service != null) {

            OrtolangClient client = OrtolangClient.getInstance();
            if (username.length() > 0) {
                client.getAccountManager().setCredentials(username, password);
                client.login(username);
            }
            System.out.println("Connected as user: " + client.connectedProfile());
            System.out.println("Retrieving for published objects from service " + service + ", with type "
                    + type + " and with status " + status + " ...");

            List<String> objectKeys = new ArrayList<>();

            int offset = 0;
            int limit = 100;
            JsonObject listOfObjects = client.listObjects(service, type, status, offset, limit);
            JsonArray keys = listOfObjects.getJsonArray("entries");

            while (!keys.isEmpty()) {
                objectKeys.addAll(keys.getValuesAs(JsonString.class).stream().map(JsonString::getString)
                        .collect(Collectors.toList()));
                offset += limit;
                listOfObjects = client.listObjects(service, type, status, offset, limit);
                keys = listOfObjects.getJsonArray("entries");
            }
            System.out.println("Reindex keys (" + objectKeys.size() + ") : " + objectKeys);
            if (!fakeMode) {
                for (String key : objectKeys) {
                    client.reindex(key);
                }
                System.out.println("All keys reindexed.");
            }
            client.logout();
            client.close();
        } else {
            help();
        }
    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:com.cloudera.csd.tools.codahale.AbstractCodahaleFixtureGenerator.java

public AbstractCodahaleFixtureGenerator(String[] args, Options options) throws Exception {
    Preconditions.checkNotNull(args);//www.java  2  s  .  co m
    Preconditions.checkNotNull(options);

    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine cmdLine = parser.parse(options, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        config = new MapConfiguration(Maps.<String, Object>newHashMap());
        for (Option option : cmdLine.getOptions()) {
            config.addProperty(option.getLongOpt(), option.getValue());
        }
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err, options);
        throw ex;
    }
}