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:com.esri.geoportal.cli.Application.java

private void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    Options options = createOptions();/*w  w  w  .  j  ava 2  s.  c o  m*/

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

        if (cli.getOptions().length == 0 || cli.hasOption('h') || cli.hasOption("v")) {
            if (cli.hasOption("v")) {
                printVersion();
            } else {
                printHeader();
                printHelp(options);
            }
        } else {
            // See if the geometry service is configured
            if (cli.hasOption('g')) {
                String geoUrl = cli.getOptionValue('g');
                this.geometryServiceUrl = geoUrl;
            }

            if (cli.hasOption('f')) {
                String fileName = cli.getOptionValue('f');
                File file = new File(fileName);
                try (InputStream inputStream = new FileInputStream(file)) {
                    TaskDefinition taskDefinition = deserialize(inputStream, TaskDefinition.class);
                    harvest(taskDefinition);
                }
            } else if (cli.hasOption('t')) {
                String sTaskDef = cli.getOptionValue('t');
                TaskDefinition taskDefinition = deserialize(sTaskDef, TaskDefinition.class);
                harvest(taskDefinition);
            } else {
                printHeader();
                printHelp(options);
            }
        }
    } catch (IOException | DataProcessorException | InvalidDefinitionException ex) {
        ex.printStackTrace(System.err);
    } catch (ParseException ex) {
        printHeader();
        printHelp(options);
    }

}

From source file:edu.psu.cse.siis.coal.CommandLineParser.java

/**
 * Parses the command line options. This method parses default options that are common to all
 * analyses and it also causes analysis-specific options to be processed.
 * //from w w  w.  j a v a 2 s .  c o  m
 * @param args The command line arguments.
 * @param clazz The class type of the {@link CommandLineArguments} that should be returned.
 * @return The parsed command line arguments.
 */
public A parseCommandLine(String[] args, Class<A> clazz) {
    Options options = new Options();

    parseDefaultCommandLineArguments(options);
    parseAnalysisSpecificArguments(options);

    CommandLine commandLine = null;
    try {
        org.apache.commons.cli.CommandLineParser commandLineParser = new DefaultParser();
        commandLine = commandLineParser.parse(options, args);
    } catch (ParseException e) {
        printHelp(options);
        logger.error("Could not parse command line arguments", e);
        return null;
    }

    A commandLineArguments = null;
    try {
        commandLineArguments = clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        logger.error("Could not instantiate type " + clazz, e);
        return null;
    }
    commandLineArguments.setCommandLine(commandLine);
    commandLineArguments.setModel(commandLine.getOptionValue("model"));
    commandLineArguments.setCompiledModel(commandLine.getOptionValue("cmodel"));
    commandLineArguments.setInput(commandLine.getOptionValue("in"));
    commandLineArguments.setClasspath(commandLine.getOptionValue("cp") + File.pathSeparator
            + commandLineArguments.getInput() + File.pathSeparator);
    commandLineArguments.setOutput(commandLine.getOptionValue("out"));
    commandLineArguments.setTraverseModeled(commandLine.hasOption("traversemodeled"));
    AnalysisParameters.v().setInferNonModeledTypes(!commandLine.hasOption("modeledtypesonly"));

    int threadCount;
    try {
        threadCount = commandLineArguments.hasOption("threadcount")
                ? ((Number) commandLineArguments.getParsedOptionValue("threadcount")).intValue()
                : Runtime.getRuntime().availableProcessors();
    } catch (ParseException exception) {
        logger.error("Could not parse thread count: " + commandLineArguments.getOptionValue("threadcount"),
                exception);
        return null;
    }
    AnalysisParameters.v().setThreadCount(threadCount);

    return commandLineArguments;
}

From source file:grakn.core.server.Grakn.java

private static boolean parseBenchmarkArg(String[] args) {
    Option enableBenchmark = Option.builder("b").longOpt("benchmark").hasArg(false)
            .desc("Enable benchmarking via Zipkin on the server").required(false).type(Boolean.class).build();

    Options options = new Options();
    options.addOption(enableBenchmark);// w w  w . j a  v a  2  s . c o  m

    CommandLineParser parser = new DefaultParser();
    CommandLine arguments;
    try {
        arguments = parser.parse(options, args);
    } catch (ParseException e) {
        (new HelpFormatter()).printHelp("Grakn options", options);
        throw new RuntimeException(e.getMessage());
    }

    return arguments.hasOption("benchmark");
}

From source file:com.deploymentio.cfnstacker.StackerOptions.java

public StackerOptions(String[] args) {

    Options options = new Options();
    options.addOption(Option.builder("c").desc("Stack configuration file").longOpt("config").hasArg()
            .argName("file").type(File.class).required().build());
    options.addOption(Option.builder("a").desc("Action to take").longOpt("action").hasArg().argName("name")
            .required().build());//from w w  w.  j a v a2s. c om
    options.addOption(Option.builder("d").desc("Print debug messages").longOpt("debug").build());
    options.addOption(Option.builder("t").desc("Print trace messages").longOpt("trace").build());

    String desiredActionValue = null;

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

        desiredActionValue = commandLine.getOptionValue("action");
        configFile = (File) commandLine.getParsedOptionValue("config");
        debugEnabled = commandLine.hasOption("debug");
        traceEnabled = commandLine.hasOption("trace");

    } catch (ParseException e) {
        errors.add("Invalid or missing arguments, see usage message");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usageWriter, 100,
                "java -jar cfn-stacker.jar -c <file> -a <" + StringUtils.join(Action.values(), '|') + ">",
                "\nCFN Stacker is used to create/update/delete an AWS CloudFormation stack\n", options, 3, 3,
                "");
        usageWriter.append('\n').flush();
    }

    if (!hasErrors()) {

        if (!configFile.exists() || !configFile.isFile()) {
            errors.add("Config file doesn't exist: Path=" + configFile.getAbsolutePath());
        } else {
            try {
                stackConfig = new StackConfigCreator(configFile).getStackConfig();
            } catch (Exception e) {
                errors.add("Can't load stack configuration: File=" + configFile.getAbsolutePath() + " Error="
                        + e.getClass().getName() + " ErrorMessage=" + e.getMessage());
            }
        }

        try {
            desiredAction = Action.valueOf(desiredActionValue);
        } catch (IllegalArgumentException e) {
            errors.add("Action is not valid: Found=" + desiredActionValue + " Expected="
                    + StringUtils.join(Action.values(), '|'));
        }
    }
}

From source file:com.act.lcms.db.analysis.FeedingAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w w  w  . j av a2 s.  c  o  m*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        System.out.format("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        System.out.format("Running feeding analysis\n");
        performFeedingAnalysis(db, cl.getOptionValue(OPTION_DIRECTORY), cl.getOptionValue(OPTION_ION_NAME),
                cl.getOptionValue(OPTION_SEARCH_MZ), cl.getOptionValue(OPTION_PLATE_BARCODE),
                cl.getOptionValue(OPTION_FEEDING_STRAIN_OR_CONSTRUCT),
                cl.getOptionValue(OPTION_FEEDING_EXTRACT), cl.getOptionValue(OPTION_FEEDING_FED_CHEMICAL),
                cl.getOptionValue(OPTION_OUTPUT_PREFIX), "pdf");
    }
}

From source file:com.dattack.dbtools.drules.DrulesClient.java

private static void execute(final String[] args) throws ConfigurationException, DrulesNestableException {

    final Options options = createOptions();

    try {/* w  ww .java 2s.  c  o m*/
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cmd = parser.parse(options, args);
        final String filename = cmd.getOptionValue(DRULES_OPTION);

        CompositeConfiguration configuration = null;
        if (cmd.hasOption(PROPERTIES_OPTION)) {
            configuration = loadProperties(cmd.getOptionValues(PROPERTIES_OPTION));
        }

        final DrulesEngine engine = new DrulesEngine(filename, configuration);

        if (cmd.hasOption(TASK_OPTION)) {
            for (final String taskName : cmd.getOptionValues(TASK_OPTION)) {
                final Identifier taskId = new IdentifierBuilder().withValue(taskName).build();
                engine.execute(taskId);
            }
        } else {
            // list available tasks
            showTaskList(engine.listTasks());

        }
    } catch (@SuppressWarnings("unused") final ParseException e) {
        showUsage(options);
    }
}

From source file:io.github.felsenhower.stine_calendar_bot.main.CallLevelWrapper.java

public CallLevelWrapper(String[] args) throws IOException {
    String username = null;//from  w  w  w. j ava2  s .  com
    String password = null;
    boolean echoPages = false;
    Path calendarCache = null;
    Path outputFile = null;
    boolean echoCalendar = false;

    // These temporary options don't have descriptions and have their
    // required-value all set to false
    final Options tempOptions = getOptions();

    final CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    StringProvider strings = null;

    // Get the StringProvider
    try {
        cmd = parser.parse(tempOptions, args, true);
        if (cmd.hasOption("language")) {
            String lang = cmd.getOptionValue("language").toLowerCase();
            if (lang.equals("de")) {
                strings = new StringProvider(Locale.GERMAN);
            } else {
                strings = new StringProvider(Locale.ENGLISH);
                if (!lang.equals("en")) {
                    System.err.println(strings.get("HumanReadable.CallLevel.LangNotRecognised", lang));
                }
            }
        } else {
            strings = new StringProvider(new Locale(Locale.getDefault().getLanguage()));
        }
    } catch (Exception e) {
        strings = new StringProvider(Locale.ENGLISH);
    }

    this.strings = strings;
    this.cliStrings = strings.from("HumanReadable.CallLevel");
    this.messages = strings.from("HumanReadable.Messages");
    this.appInfo = strings.from("MachineReadable.App");

    // Get the localised options, with all required fields enabled as well.
    // Note that we are not yet applying the options to any command line,
    // because we still want to exit if only the help screen shall be
    // displayed first, but of course, we do need the localised options
    // here.
    this.isLangInitialised = true;
    this.options = getOptions();

    try {
        // If no arguments are supplied, or --help is used, we will exit
        // after printing the help screen
        if (cmd.hasOption("help") || (cmd.hasOption("language") && cmd.getOptions().length == 1)) {
            printHelp();
        }

        cmd = parser.parse(this.options, args, false);

        username = cmd.getOptionValue("user");

        // URL-decode the password (STiNE doesn't actually allow special
        // chars in passwords, but meh...)
        password = URLDecoder.decode(cmd.getOptionValue("pass"), "UTF-8");
        // Double-dash signals that the password shall be read from stdin
        if (password.equals("--")) {
            password = readPassword(messages.get("PasswordQuery"), messages.get("PasswordFallbackMsg"));
        }

        echoPages = cmd.hasOption("echo");

        // the cache-dir argument is optional, so we read it with a default
        // value
        calendarCache = Paths
                .get(cmd.getOptionValue("cache-dir", strings.get("MachineReadable.Paths.CalendarCache")))
                .toAbsolutePath();

        // output-argument is optional as well, but this time we check if
        // double-dash is specified (for echo to stdout)
        String outputStr = cmd.getOptionValue("output", strings.get("MachineReadable.Paths.OutputFile"));
        if (outputStr.equals("--")) {
            echoCalendar = true;
            outputFile = null;
        } else {
            echoCalendar = false;
            outputFile = Paths.get(outputStr).toAbsolutePath();
        }

    } catch (UnrecognizedOptionException e) {
        System.err.println(messages.get("UnrecognisedOption", e.getOption().toString()));
        this.printHelp();
    } catch (MissingOptionException e) {
        // e.getMissingOptions() is just extremely horribly designed and
        // here is why:
        //
        // It returns an unparametrised list, to make your job especially
        // hard, whose elements may be:
        // - String-instances, if there are single independent options
        // missing (NOT the stupid Option itself, just why????)
        // - OptionGroup-instances, if there are whole OptionGroups missing
        // (This time the actual OptionGroup and not an unparametrised Set
        // that may or may not contain an Option, how inconsequential).
        // - Basically anything because the programmer who wrote that
        // function was clearly high and is most probably not to be trusted.
        //
        // This makes the job of actually displaying all the options as a
        // comma-separated list unnecessarily hard and hence leads to this
        // ugly contraption of Java-8-statements. But hey, at least it's not
        // as ugly as the Java 7 version (for me at least).
        // Sorry!
        // TODO: Write better code.
        // TODO: Write my own command line interpreter, with blackjack and
        // hookers.
        try {
            System.err.println(messages.get("MissingRequiredOption", ((List<?>) (e.getMissingOptions()))
                    .stream().filter(Object.class::isInstance).map(Object.class::cast).map(o -> {
                        if (o instanceof String) {
                            return Collections.singletonList(options.getOption((String) o));
                        } else {
                            return ((OptionGroup) o).getOptions();
                        }
                    }).flatMap(o -> o.stream()).filter(Option.class::isInstance).map(Option.class::cast)
                    .map(o -> o.getLongOpt()).collect(Collectors.joining(", "))));
            this.printHelp();
        } catch (Exception totallyMoronicException) {
            throw new RuntimeException("I hate 3rd party libraries!", totallyMoronicException);
        }
    } catch (MissingArgumentException e) {
        System.err.println(messages.get("MissingRequiredArgument", e.getOption().getLongOpt()));
        this.printHelp();
    } catch (ParseException e) {
        System.err.println(messages.get("CallLevelParsingException", e.getMessage()));
    }

    this.username = username;
    this.password = password;
    this.echoPages = echoPages;
    this.calendarCache = calendarCache;
    this.outputFile = outputFile;
    this.echoCalendar = echoCalendar;
}

From source file:com.github.horrorho.liquiddonkey.settings.commandline.CommandLinePropertiesFactory.java

public Properties from(Properties parent, CommandLineOptions commandLineOptions, String[] args)
        throws ParseException {

    Properties properties = new Properties(parent);
    CommandLineParser parser = new DefaultParser();
    Options options = commandLineOptions.options();
    CommandLine cmd = parser.parse(options, args);

    switch (cmd.getArgList().size()) {
    case 0://from  ww  w .  ja va2s .c om
        // No authentication credentials
        break;
    case 1:
        // Authentication token
        properties.put(Property.AUTHENTICATION_TOKEN.name(), cmd.getArgList().get(0));
        break;
    case 2:
        // AppleId/ password pair
        properties.put(Property.AUTHENTICATION_APPLEID.name(), cmd.getArgList().get(0));
        properties.put(Property.AUTHENTICATION_PASSWORD.name(), cmd.getArgList().get(1));
        break;
    default:
        throw new ParseException(
                "Too many non-optional arguments, expected appleid/ password or authentication token only.");
    }

    Iterator<Option> it = cmd.iterator();

    while (it.hasNext()) {
        Option option = it.next();
        String opt = commandLineOptions.opt(option);
        String property = commandLineOptions.property(option).name();

        if (option.hasArgs()) {
            // String array
            properties.put(property, joined(cmd.getOptionValues(opt)));
        } else if (option.hasArg()) {
            // String value
            properties.put(property, cmd.getOptionValue(opt));
        } else {
            // String boolean
            properties.put(property, Boolean.toString(cmd.hasOption(opt)));
        }
    }
    return properties;
}

From source file:com.ibm.crail.storage.nvmf.NvmfStorageTier.java

public void init(CrailConfiguration crailConfiguration, String[] args) throws IOException {

    if (initialized) {
        throw new IOException("NvmfStorageTier already initialized");
    }/*from  w  w w .  ja  v  a2 s  .com*/
    initialized = true;

    NvmfStorageConstants.updateConstants(crailConfiguration);

    if (args != null) {
        Options options = new Options();
        Option bindIp = Option.builder("a").desc("ip address to bind to").hasArg().build();
        Option port = Option.builder("p").desc("port to bind to").hasArg().type(Number.class).build();
        Option pcieAddress = Option.builder("s").desc("PCIe address of NVMe device").hasArg().build();
        options.addOption(bindIp);
        options.addOption(port);
        options.addOption(pcieAddress);
        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        CommandLine line = null;
        try {
            line = parser.parse(options, Arrays.copyOfRange(args, 0, args.length));
            if (line.hasOption(port.getOpt())) {
                NvmfStorageConstants.PORT = ((Number) line.getParsedOptionValue(port.getOpt())).intValue();
            }
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            formatter.printHelp("NVMe storage tier", options);
            System.exit(-1);
        }
        if (line.hasOption(bindIp.getOpt())) {
            NvmfStorageConstants.IP_ADDR = InetAddress.getByName(line.getOptionValue(bindIp.getOpt()));
        }
        if (line.hasOption(pcieAddress.getOpt())) {
            NvmfStorageConstants.PCIE_ADDR = line.getOptionValue(pcieAddress.getOpt());
        }
    }

    NvmfStorageConstants.verify();
}

From source file:fr.ortolang.diffusion.client.cmd.PublishWorkspaceCommand.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<>();
    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("k")) {
            params.put("wskey", cmd.getOptionValue("k"));
        } else {
            help();
        }

        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("publish-workspace",
                "Publish Workspace '" + cmd.getOptionValue("k") + "'", params, null);
        System.out.println("Publish-Workspace 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();
    }
}