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

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

Introduction

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

Prototype

public Option[] getOptions() 

Source Link

Document

Returns an array of the processed Option s.

Usage

From source file:de.oth.keycloak.util.CheckParams.java

private static CommandLine checkCommandline(String[] args, PrintStream printStream) {
    Options options = getCommandLineOptions();
    CommandLineParser parser = new GnuParser();
    try {/*from www . j  av  a 2  s  .c o m*/
        CommandLine ret = parser.parse(options, args);
        if (ret.getOptions().length == 0 || ret.hasOption(CONF_HELP)) {
            printCommandLineHelp(options);
            return null;
        }
        return ret;
    } catch (ParseException e) {
        printStream.println(e.getMessage());
        printCommandLineHelp(options);
        return null;
    }
}

From source file:com.netcrest.pado.tools.pado.util.PadoShellUtil.java

public final static boolean hasSingleLetterOption(CommandLine commandLine, char option, String... excludes) {
    Option[] options = commandLine.getOptions();
    for (Option option2 : options) {
        boolean skip = false;
        if (excludes != null) {
            for (String exclude : excludes) {
                if (option2.getOpt().equals(exclude)) {
                    skip = true;//from  w  ww .  j av  a 2  s  .  c  o m
                    break;
                }
            }
        }
        if (skip == false && option2.getOpt().indexOf(option) != -1) {
            return true;
        }
    }
    return false;
}

From source file:com.github.triceo.robozonky.app.CommandLineInterface.java

/**
 * Convert the command line arguments into a string and log it.
 * @param cli Parsed command line./*from w  w  w.j a  v  a 2 s  .c  o  m*/
 */
private static void logOptionValues(final CommandLine cli) {
    final List<String> optionsString = Arrays.stream(cli.getOptions()).filter(o -> cli.hasOption(o.getOpt()))
            .filter(o -> !o.equals(CommandLineInterface.OPTION_PASSWORD)).map(o -> {
                String result = "-" + o.getOpt();
                final String value = cli.getOptionValue(o.getOpt());
                if (value != null) {
                    result += " " + value;
                }
                return result;
            }).collect(Collectors.toList());
    CommandLineInterface.LOGGER.debug("Processing command line: {}.", optionsString);
}

From source file:com.speed.ob.Obfuscator.java

private static void parse(CommandLine cmd, CommandLineParser parser, Options options, HelpFormatter formatter) {
    Config config = new Config();
    if (cmd.getOptions().length == 0 || cmd.hasOption('h')) {
        formatter.printHelp("java com.speed.ob.Obfuscate", options, true);
        return;// www  .  java2  s  . c o m
    }
    if (cmd.hasOption("C")) {
        try {
            Config oneTrueConfig = new Config(cmd.getOptionValue('C'));
            Obfuscator obfuscator = new Obfuscator(oneTrueConfig);
            obfuscator.execute();
            obfuscator.postExecute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        if (cmd.hasOption("f")) {
            config.set("Obfuscator.input", (cmd.getOptionValue('f')));
        }
        if (cmd.hasOption("a")) {
            config.set("Obfuscator.all_transforms", "true");
        } else {
            if (cmd.hasOption('s')) {
                config.set("Obfuscator.string_obfuscation", "true");
            }
            if (cmd.hasOption('c')) {
                config.set("Obfuscator.controlow_obfuscation", "true");
            }
            if (cmd.hasOption('l')) {
                config.set("Obfuscator.fieldname_transforms", "true");
                config.set("Obfuscator.methodname_transforms", "true");
                config.set("Obfuscator.classname_transforms", "true");
            }
        }
        if (cmd.hasOption('o')) {
            config.set("Obfuscator.out_dir", cmd.getOptionValue('o'));
        }
        Obfuscator obfuscator = new Obfuscator(config);
        obfuscator.execute();
        obfuscator.postExecute();
    }
}

From source file:de.haber.xmind2latex.cli.CliParameters.java

/**
 * Creates a {@link XMindToLatexExporter} for the given arguments.
 * /*from  w  w  w .  j  a va  2 s  .  co m*/
 * @param args Arguments to configure this {@link XMindToLatexExporter}.
 * 
 * @return A created {@link XMindToLatexExporter} or null, if no {@link CliParameters#INPUT} parameter is used.
 * 
 * @throws ParseException, NumberFormatException for invalid arguments
 * @throws ConfigurationException for invalid input files
 * @throws IllegalArgumentException if the given input file does not exist
 */
public static XMindToLatexExporter build(String[] args) throws ParseException {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(options, args, false);

    if (cmd.getOptions().length == 0) {
        throw new ParseException("Parameter -" + INPUT + " expected.");
    }

    if (cmd.hasOption(VERSION)) {
        printVersion();
    }

    CliParameters.validateNumberOfArguments(cmd, INPUT, options);
    if (cmd.hasOption(INPUT)) {
        File in = new File(cmd.getOptionValue(INPUT));
        Builder builder = new Builder(in);
        if (cmd.hasOption(FORCE)) {
            CliParameters.validateNumberOfArguments(cmd, FORCE, options);
            builder.overwritesExistingFiles(true);
        }

        File out;
        if (cmd.hasOption(OUTPUT)) {
            CliParameters.validateNumberOfArguments(cmd, OUTPUT, options);
            out = new File(cmd.getOptionValue(OUTPUT));
            builder.withTargetFile(out);
        }

        if (cmd.hasOption(TEMPLATE_LEVEL)) {
            CliParameters.validateNumberOfArguments(cmd, TEMPLATE_LEVEL, options);

            String level = cmd.getOptionValue(TEMPLATE_LEVEL);
            try {
                int levelAsInt = Integer.parseInt(level);
                if (levelAsInt < 0) {
                    throw new NumberFormatException();
                }
                builder.withMaxLevel(levelAsInt);
            } catch (NumberFormatException e) {
                ParseException ex = new ParseException(
                        "The level argument of option " + TEMPLATE_LEVEL + " has to be a positive integer.");
                ex.addSuppressed(e);
                throw ex;
            }

        }
        if (cmd.hasOption(HELP)) {
            CliParameters.validateNumberOfArguments(cmd, HELP, options);

            showHelp();
        }

        if (cmd.hasOption(ENVIRONMENT)) {
            CliParameters.validateNumberOfArguments(cmd, ENVIRONMENT, options);

            String[] env = cmd.getOptionValues(ENVIRONMENT);
            for (int i = 0; i + 2 < env.length; i = i + 3) {
                String level = env[i];
                String start = env[i + 1];
                String end = env[i + 2];
                try {
                    int levelAsInt = Integer.parseInt(level);
                    builder.withEnvironmentTemplates(levelAsInt, start, end);
                } catch (NumberFormatException e) {
                    ParseException ex = new ParseException(
                            "The level argument of option " + ENVIRONMENT + " has to be an integer.");
                    ex.addSuppressed(e);
                    throw ex;
                }
            }
        }
        if (cmd.hasOption(LEVEL)) {
            CliParameters.validateNumberOfArguments(cmd, LEVEL, options);

            String[] tmp = cmd.getOptionValues(LEVEL);

            for (int i = 0; i + 1 < tmp.length; i = i + 2) {
                String level = tmp[i];
                String template = tmp[i + 1];
                try {
                    int levelAsInt = Integer.parseInt(level);
                    builder.withTemplate(levelAsInt, template);
                } catch (NumberFormatException e) {
                    ParseException ex = new ParseException(
                            "The level argument of option " + LEVEL + " has to be an integer.");
                    ex.addSuppressed(e);
                    throw ex;
                }
            }
        }
        return builder.build();
    } else {
        return null;
    }
}

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

/**
 * Parse command line options.//  w  ww .  j  a v  a 2 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:com.marklogic.contentpump.utilities.AuditUtil.java

/**
 * @param job//from   www . ja  va  2s  .  co  m
 * @param cmd
 * @param cmdline
 */
public static void prepareAuditMlcpStart(Job job, String cmd, CommandLine cmdline) {
    Configuration conf = job.getConfiguration();
    StringBuilder buf = new StringBuilder();
    buf.append(cmd);
    buf.append(" ");
    Option[] options = cmdline.getOptions();
    for (int i = 0; i < options.length; i++) {
        String name = options[i].getOpt();
        // Hide password from command
        if ("password".equalsIgnoreCase(name)) {
            continue;
        }
        if (i != 0) {
            buf.append(' ');
        }
        buf.append('-');
        buf.append(name);
        String value = cmdline.getOptionValue(name);
        if (value != null) {
            buf.append(' ');
            buf.append(value);
        }
    }

    conf.set(ConfigConstants.CONF_AUDIT_MLCPSTART_MESSAGE, buf.toString());
}

From source file:de.pniehus.odal.App.java

/**S
 * Parses the command line arguments/*from w ww .  j a v a  2s.  c  om*/
 * 
 * @param args
 * @param filters
 * @return
 */
public static Profile parseArgs(String[] args, List<Filter> filters) {
    boolean windowsConsole = false;

    Profile profile = new Profile(filters);

    Options options = new Options();
    Options helpOptions = new Options();

    Option profileOption = Option.builder("p").longOpt("profile").hasArg().argName("profile name")
            .desc("Loads or generates the profile with the given name").build();

    if (System.getProperty("os.name").toLowerCase().contains("windows")) {
        Console console = System.console();
        if (console != null) {
            windowsConsole = true;
            profileOption.setRequired(true);
        }
    }

    options.addOption(profileOption);
    options.addOption(Option.builder("url").hasArg().argName("url")
            .desc("Sets the url of the open directory which will be parsed and downloaded").build());
    options.addOption(Option.builder("a").longOpt("select-all").desc(
            "Downloads all available files (except the ones removed by filters), overrules the corresponding setting if a profile is used")
            .build());
    options.addOption(Option.builder("o").longOpt("outputDir").hasArg().argName("directory path").desc(
            "Sets the output directory to the given directory, overrules the corresponding setting if a profile is used")
            .build());
    options.addOption(Option.builder("w").longOpt("windows-mode")
            .desc("Enables the windows console mode on non-windows systems. Requires -url and -p to be used.")
            .build());
    Option helpOption = Option.builder("h").longOpt("help").desc("Displays this help dialog").build();

    helpOptions.addOption(helpOption);
    options.addOption(helpOption);

    CommandLineParser cliParser = new DefaultParser();

    try {
        CommandLine cmd = cliParser.parse(helpOptions, args, true);

        if (cmd.getOptions().length == 0) {
            cmd = cliParser.parse(options, args);

            if (cmd.hasOption("w")) {
                windowsConsole = true;
                if (!cmd.hasOption("p")) {
                    System.out.println("ERROR: The profile option is required for windows mode!");
                    printHelp(filters, options);
                }
            }

            if (cmd.hasOption("p")) {
                String profileName = cmd.getOptionValue("p");
                File profileFile = new File(profileName + ".odal");
                if (profileFile.exists()) {
                    try {
                        profile = Profile.loadProfile(profileName);
                        profile.setUserProfile(true);
                    } catch (IOException e) {
                        System.out.println("An error occured while loading the specified profile!");
                    }
                } else {
                    try {
                        Profile.saveProfile(profileName, profile);
                        System.out.println("The profile " + profileFile.getName() + " has been created!");
                        System.exit(0);
                    } catch (IOException e) {
                        System.out.println("An error occured during the creation of the profile "
                                + profileFile.getName() + " : " + e.getMessage());
                        System.out.println("Terminating.");
                        System.exit(1);
                    }
                }

            }

            if (cmd.hasOption("a")) {
                profile.setSelectAll(true);
            }

            if (cmd.hasOption("o")) {
                File out = new File(cmd.getOptionValue("o"));
                if (out.isDirectory() || out.canWrite()) {
                    profile.setOutputPath(out.getAbsolutePath());
                } else {
                    System.out.println(out.getAbsolutePath() + " is not a directory or not writeable!");
                    System.out.println("Terminating.");
                    System.exit(1);
                }
            }

            if (cmd.hasOption("url")) {
                profile.setUrl(cmd.getOptionValue("url"));
            } else if (windowsConsole) {
                System.out.println("ERROR: The -url argument is required for console use on windows systems.");
                printHelp(filters, options);
                System.exit(1);
            }

        } else {
            printHelp(filters, options);
            System.exit(0);
        }
    } catch (ParseException e) {
        System.out.println("\nUnable to parse command line arguments: " + e.getLocalizedMessage() + "\n");
        printHelp(filters, options);
        System.exit(1);
    }

    if (windowsConsole) {
        profile.setWindowsConsoleMode(true);
    }

    return profile;
}

From source file:eu.project.ttc.tools.cli.TermSuiteCLIUtils.java

/**
 * Displays all command line options in log messages.
 * @param line//w ww  . j  a va  2s.co  m
 */
public static void logCommandLineOptions(CommandLine line) {
    for (Option myOption : line.getOptions()) {
        String message;
        String opt = "";
        if (myOption.getOpt() != null) {
            opt += "-" + myOption.getOpt();
            if (myOption.getLongOpt() != null)
                opt += " (--" + myOption.getLongOpt() + ")";
        } else
            opt += "--" + myOption.getLongOpt() + "";

        if (myOption.hasArg())
            message = opt + " " + myOption.getValue();
        else
            message = opt;

        LOGGER.info("with option: " + message);
    }
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static Properties commandLine2Properties(final CommandLine commandLine) {
    Properties properties = new Properties();
    Option[] opts = commandLine.getOptions();

    if (opts != null) {
        for (Option opt : opts) {
            String name = opt.getLongOpt();
            String value = commandLine.getOptionValue(name);
            if (value != null) {
                properties.setProperty(name, value);
            }//from  ww  w  . j  a  va2 s.  c  o  m
        }
    }

    return properties;
}