org.apache.commons.cli.CommandLine.hasOption()

Here are the examples of the java api org.apache.commons.cli.CommandLine.hasOption() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

777 Examples 7

19 Source : SendRecvCmdLine.java
with Apache License 2.0
from zrlio

@Override
protected void getOptionsValue(CommandLine line) throws ParseException {
    super.getOptionsValue(line);
    if (line.hasOption(QUEUEDEPTH_KEY)) {
        queueDepth = ((Number) line.getParsedOptionValue(QUEUEDEPTH_KEY)).intValue();
    } else {
        queueDepth = QUEUEDEPTH_DEFAULT;
    }
}

19 Source : RdmaBenchmarkCmdLine.java
with Apache License 2.0
from zrlio

@Override
protected void getOptionsValue(CommandLine line) throws ParseException {
    super.getOptionsValue(line);
    if (line.hasOption(SIZE_KEY)) {
        size = ((Number) line.getParsedOptionValue(SIZE_KEY)).intValue();
    } else {
        size = SIZE_DEFAULT;
    }
    if (line.hasOption(LOOP_KEY)) {
        loop = ((Number) line.getParsedOptionValue(LOOP_KEY)).intValue();
    } else {
        loop = LOOP_DEFAULT;
    }
}

19 Source : CmdLineOpts.java
with Apache License 2.0
from yugabyte

private void initializeTableProperties(CommandLine cmd) {
    // Initialize the TTL.
    if (cmd.hasOption("table_ttl_seconds")) {
        AppBase.appConfig.tableTTLSeconds = Long.parseLong(cmd.getOptionValue("table_ttl_seconds"));
    }
    LOG.info("Table TTL (secs): " + AppBase.appConfig.tableTTLSeconds);
}

19 Source : CmdLineOpts.java
with Apache License 2.0
from yugabyte

private void initializeNumKeys(CommandLine cmd) {
    if (cmd.hasOption("num_writes")) {
        AppBase.appConfig.numKeysToWrite = Long.parseLong(cmd.getOptionValue("num_writes"));
    }
    if (cmd.hasOption("num_reads")) {
        AppBase.appConfig.numKeysToRead = Long.parseLong(cmd.getOptionValue("num_reads"));
    }
    if (cmd.hasOption("num_unique_keys")) {
        AppBase.appConfig.numUniqueKeysToWrite = Long.parseLong(cmd.getOptionValue("num_unique_keys"));
    }
    AppBase.appConfig.maxWrittenKey = Long.parseLong(cmd.getOptionValue("max_written_key", String.valueOf(AppBase.appConfig.maxWrittenKey)));
    if (cmd.hasOption("value_size")) {
        AppBase.appConfig.valueSize = Integer.parseInt(cmd.getOptionValue("value_size"));
    }
    if (cmd.hasOption("sleep_time")) {
        AppBase.appConfig.sleepTime = Integer.parseInt(cmd.getOptionValue("sleep_time"));
    }
    if (cmd.hasOption("socket_timeout")) {
        AppBase.appConfig.jedisSocketTimeout = Integer.parseInt(cmd.getOptionValue("socket_timeout"));
    }
    if (cmd.hasOption("cql_connect_timeout_ms")) {
        AppBase.appConfig.cqlConnectTimeoutMs = Integer.parseInt(cmd.getOptionValue("cql_connect_timeout_ms"));
    }
    if (cmd.hasOption("cql_read_timeout_ms")) {
        AppBase.appConfig.cqlReadTimeoutMs = Integer.parseInt(cmd.getOptionValue("cql_read_timeout_ms"));
    }
    if (cmd.hasOption("use_ascii_values")) {
        AppBase.appConfig.restrictValuesToAscii = true;
    }
    if (cmd.hasOption("sanity_check_at_end")) {
        AppBase.appConfig.sanityCheckAtEnd = true;
    }
    if (cmd.hasOption("disable_yb_load_balancing_policy")) {
        AppBase.appConfig.disableYBLoadBalancingPolicy = true;
    }
    if (cmd.hasOption("print_all_exceptions")) {
        AppBase.appConfig.printAllExceptions = true;
    }
    if (cmd.hasOption("create_table_name") && cmd.hasOption("drop_table_name")) {
        LOG.error("Both create and drop table options cannot be provided together.");
        System.exit(1);
    }
    if (cmd.hasOption("keep_table")) {
        if (cmd.hasOption("drop_table_name")) {
            LOG.error("Both keep and drop table options cannot be provided together.");
            System.exit(1);
        }
        AppBase.appConfig.tableOp = TableOp.NoOp;
    }
    if (cmd.hasOption("create_table_name")) {
        AppBase.appConfig.tableName = cmd.getOptionValue("create_table_name");
        LOG.info("Create table name: " + AppBase.appConfig.tableName);
    }
    if (cmd.hasOption("truncate")) {
        AppBase.appConfig.tableOp = TableOp.TruncateTable;
        LOG.info("Going to truncate table");
    }
    if (cmd.hasOption("default_postgres_database")) {
        AppBase.appConfig.defaultPostgresDatabase = cmd.getOptionValue("default_postgres_database");
        LOG.info("Default postgres database: " + AppBase.appConfig.defaultPostgresDatabase);
    }
    if (cmd.hasOption("drop_table_name")) {
        AppBase.appConfig.tableName = cmd.getOptionValue("drop_table_name");
        LOG.info("Drop table name: " + AppBase.appConfig.tableName);
        AppBase.appConfig.tableOp = TableOp.DropTable;
    }
    LOG.info("Num unique keys to insert: " + AppBase.appConfig.numUniqueKeysToWrite);
    LOG.info("Num keys to update: " + (AppBase.appConfig.numKeysToWrite - AppBase.appConfig.numUniqueKeysToWrite));
    LOG.info("Num keys to read: " + AppBase.appConfig.numKeysToRead);
    LOG.info("Value size: " + AppBase.appConfig.valueSize);
    LOG.info("Restrict values to ASCII strings: " + AppBase.appConfig.restrictValuesToAscii);
    LOG.info("Perform sanity check at end of app run: " + AppBase.appConfig.sanityCheckAtEnd);
}

19 Source : CmdLineOpts.java
with Apache License 2.0
from yugabyte

private static void parseHelpOverview(String[] args, Options options) throws Exception {
    Options helpOptions = new Options();
    helpOptions.addOption("help", false, "Print help.");
    CommandLineParser helpParser = new BasicParser();
    CommandLine helpCommandLine = null;
    try {
        helpCommandLine = helpParser.parse(helpOptions, args);
    } catch (ParseException e) {
        return;
    }
    if (helpCommandLine.hasOption("help")) {
        printUsage(options, "Usage:");
        System.exit(0);
    }
}

19 Source : Main.java
with GNU Lesser General Public License v2.1
from yangziwen

/**
 * Verifies threads number CLI parameter value.
 * @param cmdLine a command line
 * @param result a resulting list of errors
 * @param cliParameterName a CLI parameter name
 * @param mustBeGreaterThanZeroMessage a message which should be reported
 *                                     if the number of threads is less than or equal to zero
 * @param invalidNumberMessage a message which should be reported if the preplaceded value
 *                             is not a valid number
 */
private static void verifyThreadsNumberParameter(CommandLine cmdLine, List<String> result, String cliParameterName, String mustBeGreaterThanZeroMessage, String invalidNumberMessage) {
    if (cmdLine.hasOption(cliParameterName)) {
        final String checkerThreadsNumberStr = cmdLine.getOptionValue(cliParameterName);
        if (CommonUtil.isInt(checkerThreadsNumberStr)) {
            final int checkerThreadsNumber = Integer.parseInt(checkerThreadsNumberStr);
            if (checkerThreadsNumber < 1) {
                result.add(mustBeGreaterThanZeroMessage);
            }
        } else {
            result.add(invalidNumberMessage);
        }
    }
}

19 Source : MQAdminStartup.java
with GNU General Public License v3.0
from y123456yz

public static void main0(String[] args, RPCHook rpcHook) {
    System.setProperty(RemotingCommand.RemotingVersionKey, Integer.toString(MQVersion.CurrentVersion));
    PackageConflictDetect.detectFastjson();
    initCommand();
    try {
        initLogback();
        switch(args.length) {
            case 0:
                printHelp();
                break;
            case 2:
                if (args[0].equals("help")) {
                    SubCommand cmd = findSubCommand(args[1]);
                    if (cmd != null) {
                        Options options = ServerUtil.buildCommandlineOptions(new Options());
                        options = cmd.buildCommandlineOptions(options);
                        if (options != null) {
                            ServerUtil.printCommandLineHelp("mqadmin " + cmd.commandName(), options);
                        }
                    } else {
                        System.out.println("The sub command \'" + args[1] + "\' not exist.");
                    }
                    break;
                }
            case 1:
            default:
                SubCommand cmd = findSubCommand(args[0]);
                if (cmd != null) {
                    String[] subargs = parseSubArgs(args);
                    Options options = ServerUtil.buildCommandlineOptions(new Options());
                    final CommandLine commandLine = ServerUtil.parseCmdLine("mqadmin " + cmd.commandName(), subargs, cmd.buildCommandlineOptions(options), new PosixParser());
                    if (null == commandLine) {
                        System.exit(-1);
                        return;
                    }
                    if (commandLine.hasOption('n')) {
                        String namesrvAddr = commandLine.getOptionValue('n');
                        System.setProperty(MixAll.NAMESRV_ADDR_PROPERTY, namesrvAddr);
                    }
                    // 见 MQAdminStartup.initCommand  例如 UpdateTopicSubCommand 对应的是updateTopic 命令
                    // SubCommand.execute
                    cmd.execute(commandLine, options, rpcHook);
                } else {
                    System.out.println("The sub command \'" + args[0] + "\' not exist.");
                }
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

19 Source : Producer.java
with GNU General Public License v3.0
from y123456yz

public static CommandLine buildCommandline(String[] args) {
    final Options options = new Options();
    // ////////////////////////////////////////////////////
    Option opt = new Option("h", "help", false, "Print help");
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("g", "producerGroup", true, "Producer Group Name");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("t", "topic", true, "Topic Name");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("a", "tags", true, "Tags Name");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("k", "keys", true, "Keys Name");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("c", "msgCount", true, "Message Count");
    opt.setRequired(true);
    options.addOption(opt);
    // ////////////////////////////////////////////////////
    PosixParser parser = new PosixParser();
    HelpFormatter hf = new HelpFormatter();
    hf.setWidth(110);
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption('h')) {
            hf.printHelp("producer", options, true);
            return null;
        }
    } catch (ParseException e) {
        hf.printHelp("producer", options, true);
        return null;
    }
    return commandLine;
}

19 Source : Consumer.java
with GNU General Public License v3.0
from y123456yz

public static CommandLine buildCommandline(String[] args) {
    final Options options = new Options();
    // ////////////////////////////////////////////////////
    Option opt = new Option("h", "help", false, "Print help");
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("g", "consumerGroup", true, "Consumer Group Name");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("t", "topic", true, "Topic Name");
    opt.setRequired(true);
    options.addOption(opt);
    opt = new Option("s", "subscription", true, "subscription");
    opt.setRequired(false);
    options.addOption(opt);
    opt = new Option("f", "returnFailedHalf", true, "return failed result, for half message");
    opt.setRequired(true);
    options.addOption(opt);
    // ////////////////////////////////////////////////////
    PosixParser parser = new PosixParser();
    HelpFormatter hf = new HelpFormatter();
    hf.setWidth(110);
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption('h')) {
            hf.printHelp("producer", options, true);
            return null;
        }
    } catch (ParseException e) {
        hf.printHelp("producer", options, true);
        return null;
    }
    return commandLine;
}

19 Source : GceAdminMain.java
with Apache License 2.0
from Xceptance

/**
 * The main method.
 *
 * @param args
 *            the command line arguments
 */
public static void main(final String[] args) {
    final Options options = createCommandLineOptions();
    final CommandLine commandLine = parseCommandLine(options, args);
    if (commandLine.hasOption("help")) {
        printUsageInfo(options);
    } else {
        try {
            final GceAdmin gceAdmin = new GceAdmin();
            if (commandLine.getArgs().length > 0) {
                // start in non-interactive mode
                gceAdmin.startNonInteractiveMode(commandLine);
            } else {
                // Enter the command loop
                gceAdmin.startInteractiveMode();
            }
        } catch (final Exception e) {
            // In case any exception slips through
            GceAdminUtils.dieWithMessage("An unexpected error occurred: " + e.getMessage(), e);
        }
    }
}

19 Source : Validator.java
with GNU Lesser General Public License v3.0
from waterguo

private void run() throws Exception {
    CommandLine line = this.cmd;
    // help
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("antsdb-validate", getOptions());
        return;
    }
    // now options
    println("log location: %s", this.home);
    if (line.hasOption("replay")) {
        this.doesValidateReplay = true;
    }
    println("replay validation: %b", this.doesValidateReplay);
    // now go go go
    this.humpback = getHumpbackReadOnly();
    if (this.humpback == null) {
        return;
    }
    this.spaceman = this.humpback.getSpaceManager();
    this.startTime = System.currentTimeMillis();
    validateTablets();
    this.endTime = System.currentTimeMillis();
    report();
}

19 Source : DumpRow.java
with GNU Lesser General Public License v3.0
from waterguo

private void run(String[] args) throws Exception {
    CommandLine line = parse(getOptions(), args);
    // help
    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("dumprow <table id> <row key base64>", getOptions());
        return;
    }
    // arguments
    if (line.getArgList().size() != 2) {
        println("error: invalid command line arguments");
        return;
    }
    this.tableId = Integer.parseInt(line.getArgList().get(0));
    this.key = Base64.getDecoder().decode(line.getArgList().get(1));
    this.pKey = KeyBytes.allocSet(this.heap, this.key).getAddress();
    // options
    this.home = new File(line.getOptionValue("home"));
    this.isVerbose = line.hasOption('v');
    this.dumpHex = line.hasOption("hex");
    this.dumpValues = line.hasOption("values");
    // validate
    if (!this.home.isDirectory()) {
        println("error: invalid home directory {}", this.home);
        return;
    }
    if (!new File(this.home, "checkpoint.bin").exists()) {
        println("error: invalid home directory {}", this.home);
        return;
    }
    // init space manager
    this.spaceman = new SpaceManager(this.home, false);
    spaceman.open();
    // proceed
    dump();
}

19 Source : BaseCommandLine.java
with Apache License 2.0
from wangrenlei

protected CommandLine doParse(String[] args) throws CommandLineParseException {
    CommandLineParser parser = new DefaultParser();
    CommandLine commandLine;
    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption(HELP_ARG)) {
            return printUsageAndThrow(null, ExitCode.HELP);
        }
        certificateAuthorityHostname = commandLine.getOptionValue(CERTIFICATE_AUTHORITY_HOSTNAME_ARG, TlsConfig.DEFAULT_HOSTNAME);
        days = getIntValue(commandLine, DAYS_ARG, TlsConfig.DEFAULT_DAYS);
        keySize = getIntValue(commandLine, KEY_SIZE_ARG, TlsConfig.DEFAULT_KEY_SIZE);
        keyAlgorithm = commandLine.getOptionValue(KEY_ALGORITHM_ARG, TlsConfig.DEFAULT_KEY_PAIR_ALGORITHM);
        keyStoreType = commandLine.getOptionValue(KEY_STORE_TYPE_ARG, getKeyStoreTypeDefault());
        if (KeystoreType.PKCS12.toString().equalsIgnoreCase(keyStoreType)) {
            logger.info("Command line argument --" + KEY_STORE_TYPE_ARG + "=" + keyStoreType + " only applies to keystore, recommended truststore type of " + KeystoreType.JKS.toString() + " unaffected.");
        }
        signingAlgorithm = commandLine.getOptionValue(SIGNING_ALGORITHM_ARG, TlsConfig.DEFAULT_SIGNING_ALGORITHM);
        differentPreplacedwordForKeyAndKeystore = commandLine.hasOption(DIFFERENT_KEY_AND_KEYSTORE_PreplacedWORDS_ARG);
    } catch (ParseException e) {
        return printUsageAndThrow("Error parsing command line. (" + e.getMessage() + ")", ExitCode.ERROR_PARSING_COMMAND_LINE);
    }
    return commandLine;
}

19 Source : JcePolicyInfo.java
with Apache License 2.0
from wangrenlei

public static void main(String[] args) throws Exception {
    try {
        boolean showHelp = true;
        CommandLine cli = new DefaultParser().parse(options(), args);
        if (cli.hasOption("lc")) {
            listCiphers();
            showHelp = false;
        }
        if (cli.hasOption("tu")) {
            testUnlimitedKeyJCEPolicy();
            showHelp = false;
        }
        if (showHelp) {
            printHelp(null);
        }
    } catch (UnrecognizedOptionException e) {
        printHelp(e);
    }
}

19 Source : GatewayOptionsParser.java
with Apache License 2.0
from ververica

private static List<URL> checkUrls(CommandLine line, Option option) {
    if (line.hasOption(option.getOpt())) {
        final String[] urls = line.getOptionValues(option.getOpt());
        return Arrays.stream(urls).distinct().map((url) -> {
            try {
                return Path.fromLocalFile(new File(url).getAbsoluteFile()).toUri().toURL();
            } catch (Exception e) {
                throw new SqlGatewayException("Invalid path for option '" + option.getLongOpt() + "': " + url, e);
            }
        }).collect(Collectors.toList());
    }
    return null;
}

19 Source : GatewayOptionsParser.java
with Apache License 2.0
from ververica

// --------------------------------------------------------------------------------------------
// Line Parsing
// --------------------------------------------------------------------------------------------
public static GatewayOptions parseGatewayOptions(String[] args) {
    try {
        DefaultParser parser = new DefaultParser();
        CommandLine line = parser.parse(GATEWAY_OPTIONS, args, true);
        Integer port = null;
        if (line.hasOption(GatewayOptionsParser.OPTION_PORT.getOpt())) {
            port = Integer.valueOf(line.getOptionValue(GatewayOptionsParser.OPTION_PORT.getOpt()));
        }
        return new GatewayOptions(line.hasOption(GatewayOptionsParser.OPTION_HELP.getOpt()), port, checkUrl(line, GatewayOptionsParser.OPTION_DEFAULTS), checkUrls(line, GatewayOptionsParser.OPTION_JAR), checkUrls(line, GatewayOptionsParser.OPTION_LIBRARY));
    } catch (ParseException e) {
        throw new SqlGatewayException(e.getMessage());
    }
}

19 Source : OptionsProcessor.java
with Apache License 2.0
from ucarGroup

/**
 * 解析参数
 */
public boolean parseAgr(String[] args) {
    CommandLine commandLine = null;
    try {
        commandLine = new GnuParser().parse(options, args);
    } catch (ParseException e) {
        LOG.error("Command line option args error.");
        return false;
    }
    if (commandLine.hasOption('h')) {
        printUsage();
        return false;
    }
    ss.setSilent(commandLine.hasOption('s'));
    ss.setFileName(commandLine.getOptionValue('f'));
    return true;
}

19 Source : JGrade.java
with MIT License
from tkutcher

private static Grader initGrader(CommandLine line) {
    formatter = null;
    Grader grader = new Grader();
    if (line.hasOption(FORMAT_OPT) && !line.getOptionValue(FORMAT_OPT).equals(DEFAULT_FORMAT)) {
        String val = line.getOptionValue(FORMAT_OPT);
        switch(val) {
            case TXT_VAL:
                throw new UnsupportedOperationException("have not implemented textual output");
            default:
                throw new IllegalArgumentException("unrecognized format value " + val);
        }
    } else if (!line.hasOption(NO_OUTPUT_OPT)) {
        formatter = new GradescopeJsonFormatter();
    }
    if (line.hasOption(PP_OPT)) {
        if (formatter == null) {
            throw new IllegalArgumentException("pretty-print without json formatting");
        }
        formatter.setPrettyPrint(2);
    }
    return grader;
}

19 Source : JGrade.java
with MIT License
from tkutcher

/**
 * Main entry point. See usage or run with <code>--help</code>
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    CommandLine line = null;
    try {
        line = readCommandLine(args);
    } catch (ParseException e) {
        fatal("could not parse command line", e);
    }
    replacedert line != null;
    if (args.length == 0 || line.hasOption(HELP_OPT)) {
        usage();
    } else if (line.hasOption(VERSION_OPT)) {
        System.out.println(VERSION);
    } else if (!line.hasOption(CLreplaced_OPT)) {
        fatal("missing required clreplaced flag", new ParseException("missing required clreplaced flag"));
    } else {
        Grader grader = initGrader(line);
        Clreplaced<?> c = getClreplacedToGrade(line.getOptionValue(CLreplaced_OPT));
        grade(grader, c);
        outputResult(grader, line);
    }
}

19 Source : CommandCli.java
with Apache License 2.0
from thulab

private boolean parseParams(CommandLine commandLine, CommandLineParser parser, Options options, String[] args, HelpFormatter hf) {
    try {
        commandLine = parser.parse(options, args);
        if (commandLine.hasOption(HELP_ARGS)) {
            hf.printHelp(Constants.CONSOLE_PREFIX, options, true);
            return false;
        }
        if (commandLine.hasOption(CONFIG_ARGS)) {
            System.setProperty(Constants.BENCHMARK_CONF, commandLine.getOptionValue(CONFIG_ARGS));
        }
    } catch (ParseException e) {
        System.out.println("Require more params input, please check the following hint.");
        hf.printHelp(Constants.CONSOLE_PREFIX, options, true);
        return false;
    } catch (Exception e) {
        System.out.println("Error params input, because " + e.getMessage());
        hf.printHelp(Constants.CONSOLE_PREFIX, options, true);
        return false;
    }
    return true;
}

19 Source : Main.java
with Apache License 2.0
from Teradata

public static void main(String[] args) throws Exception {
    // disable jline trace messages on SLES systems
    jline.internal.Log.setOutput(new PrintStream(new OutputStream() {

        @Override
        public void write(int b) throws IOException {
        }
    }));
    Globals globals = new Globals();
    // initiate the name and version
    Package pkg = Main.clreplaced.getPackage();
    globals.setName(pkg.getImplementationreplacedle());
    globals.setVersion(pkg.getImplementationVersion());
    globals.getOs();
    // install Jansi
    if (Os.isWindows()) {
        AnsiConsole.systemInstall();
    }
    // initiate the greeting message.
    try {
        String greet = StringUtils.getStringFromStream(Main.clreplaced.getResourcereplacedtream(GREET_RC));
        globals.setGreeting(greet);
    } catch (Exception ex) {
    }
    // initiate the display
    ConsoleDisplay display = new ConsoleDisplay(globals);
    // Add shutdown hook that closes all sessions on exit.
    JaqyShutdownHook.register(globals);
    globals.getOs();
    // register signal handlers for dealing with Ctrl-C
    if (!Os.isWindows()) {
    // The signal handler only works on Linux
    // new ConsoleSignalHandler (display).register ();
    }
    // now create an initial session and set the session to it.
    Session session = globals.createSession(display);
    // create an interpreter
    JaqyInterpreter interpreter = new JaqyInterpreter(globals, display, session);
    // initiate settings
    SettingSetup.init(globals);
    // initiate commands
    CommandSetup.init(globals);
    // handle command line options
    OptionSetup.init(globals);
    // install predefined helper factories
    HelperSetup.init(globals);
    try {
        globals.loadRC(ClreplacedLoader.getSystemClreplacedLoader(), interpreter);
    } catch (Exception ex) {
    }
    // load initiation scripts
    Path initFile = new FilePath(getDefaultInitFile());
    CommandLine cmdLine = globals.getOptionManager().getCommandLine(args);
    if (cmdLine.hasOption("norc")) {
        initFile = null;
    } else if (cmdLine.hasOption("rcfile")) {
        String fileName = cmdLine.getOptionValue("rcfile");
        initFile = new FilePath(new File(fileName));
    }
    loadInit(globals, interpreter, display, initFile);
    // Now handle command line options
    // We want to do this after loading the initiation script to
    // allow any custom addons to be installed.
    args = globals.getOptionManager().handleOptions(globals, display, args);
    // print the start up screen
    initScreen(globals, display);
    // we are done with the loading phase
    display.setInitiated();
    // display the replacedle
    if (display.isInteractive()) {
        display.showreplacedle(interpreter);
    }
    // reset the command counter so we get consistent result regardless
    // of the initiation script
    interpreter.resetCommandCount();
    Path currentDir = new FilePath(globals.getDirectory());
    // Current dir
    // setup the input
    StackedLineInput lineInput = new StackedLineInput();
    if (display.isInteractive()) {
        globals.getOs();
        if (Os.isWindows()) {
            // windows
            // 
            // Windows have its own readline-like support for
            // all apps, so we can just use the default system
            // behavior.
            lineInput.push(LineInputFactory.getSimpleLineInput(System.in, currentDir, true));
        } else {
            try {
                // we use JLine other systems.
                lineInput.push(new JLineConsoleLineInput(currentDir));
            } catch (IOException ex) {
                // just in case we fail with JLine,
                // fall back to default.
                lineInput.push(LineInputFactory.getSimpleLineInput(System.in, currentDir, true));
            }
        }
    } else {
        if (!skipStdin) {
            String encoding = null;
            if (System.in.available() == 0) {
                // If the input available bytes is 0, it is possible the input
                // is not available.  So we do not want to guess the input
                // encoding at all.  Instead, use the default.
                encoding = Charset.defaultCharset().displayName();
            }
            lineInput.push(LineInputFactory.getLineInput(System.in, currentDir, encoding, false));
        }
    }
    // Interpret any remaining command line arguments first
    if (args.length > 0) {
        lineInput.push(new CommandLineInput(args, currentDir));
    }
    // parse the user commands
    interpreter.interpret(lineInput);
    if (!skipStdin) {
        globals.log(Level.INFO, "Errors: " + interpreter.getErrorCount() + ", Failures: " + interpreter.getFailureCount());
        System.exit(interpreter.getExitCode());
    }
}

19 Source : AMLPlan4ClassificationCLIModule.java
with GNU Affero General Public License v3.0
from starlibs

protected void configureLoss(final CommandLine cl, final ICategoricalAttribute labelAtt, final AMLPlanBuilder builder) {
    int positiveClreplacedIndex = Integer.parseInt(cl.getOptionValue(MLPlanCLI.O_POS_CLreplaced_INDEX, getDefault(MLPlanCLI.O_POS_CLreplaced_INDEX)));
    if (cl.hasOption(MLPlanCLI.O_POS_CLreplaced_NAME)) {
        positiveClreplacedIndex = labelAtt.getLabels().indexOf(cl.getOptionValue(MLPlanCLI.O_POS_CLreplaced_NAME));
        if (positiveClreplacedIndex < 0) {
            throw new UnsupportedModuleConfigurationException("The provided name of the positive clreplaced is not contained in the list of clreplaced labels");
        }
    }
    String performanceMeasure = cl.getOptionValue(MLPlanCLI.O_LOSS, L_ERRORRATE);
    if (BINARY_ONLY_MEASURES.contains(performanceMeasure) && labelAtt.getLabels().size() > 2) {
        throw new UnsupportedModuleConfigurationException("Cannot use binary performance measure for non-binary clreplacedification dataset.");
    }
    switch(performanceMeasure) {
        case L_ERRORRATE:
            builder.withPerformanceMeasure(EClreplacedificationPerformanceMeasure.ERRORRATE);
            break;
        case L_LOGLOSS:
            builder.withPerformanceMeasure(new AveragedInstanceLoss(new LogLoss()));
            break;
        case L_AUC:
            builder.withPerformanceMeasure(new AreaUnderROCCurve(positiveClreplacedIndex));
            break;
        case L_F1:
            builder.withPerformanceMeasure(new F1Measure(positiveClreplacedIndex));
            break;
        case L_PRECISION:
            builder.withPerformanceMeasure(new Precision(positiveClreplacedIndex));
            break;
        case L_RECALL:
            builder.withPerformanceMeasure(new Recall(positiveClreplacedIndex));
            break;
        default:
            throw new UnsupportedModuleConfigurationException("Unsupported measure " + performanceMeasure);
    }
}

19 Source : MLPlanCLI.java
with GNU Affero General Public License v3.0
from starlibs

public static void main(final String[] args) throws Exception {
    System.out.println("Called ML-Plan CLI with the following params: >" + Arrays.toString(args) + "<");
    final Options options = generateOptions();
    if (args.length == 0) {
        printUsage(options);
    } else {
        CommandLine commandLine = generateCommandLine(options, args);
        if (commandLine != null) {
            if (commandLine.hasOption(O_HELP)) {
                printHelp(options);
            } else {
                runMLPlan(commandLine);
            }
        }
    }
}

19 Source : AbstractSshOptionsEvaluator.java
with GNU Lesser General Public License v3.0
from sshtools

protected static void parseMacs(CommandLine commandLine, SshClientArguments arguments) {
    if (commandLine.hasOption(MacSpec.MAC_SPEC_OPTION)) {
        String[] macSpecParts = commandLine.getOptionValues(MacSpec.MAC_SPEC_OPTION);
        String[] finalValues = CommandUtil.toStringFromCsvs(macSpecParts);
        arguments.setHmacs(finalValues);
    }
}

19 Source : AbstractSshOptionsEvaluator.java
with GNU Lesser General Public License v3.0
from sshtools

protected static void parseLoginName(CommandLine commandLine, SshClientArguments arguments) {
    if (commandLine.hasOption(LoginName.LOGIN_NAME_OPTION)) {
        arguments.setLoginName(commandLine.getOptionValue(LoginName.LOGIN_NAME_OPTION));
    }
}

19 Source : AbstractSshOptionsEvaluator.java
with GNU Lesser General Public License v3.0
from sshtools

protected static void parseSecurityLevel(CommandLine commandLine, SshClientArguments arguments) {
    if (commandLine.hasOption(SecurityLevel.SECURITY_LEVEL_OPTION)) {
        String securityLevel = commandLine.getOptionValue(SecurityLevel.SECURITY_LEVEL_OPTION);
        arguments.setSecurityLevel(securityLevel);
    }
}

19 Source : AbstractSshOptionsEvaluator.java
with GNU Lesser General Public License v3.0
from sshtools

protected static void parseCiphers(CommandLine commandLine, SshClientArguments arguments) {
    if (commandLine.hasOption(CipherSpec.CIPHER_SPEC_OPTION)) {
        String[] cipherSpecParts = commandLine.getOptionValues(CipherSpec.CIPHER_SPEC_OPTION);
        String[] finalValues = CommandUtil.toStringFromCsvs(cipherSpecParts);
        arguments.setCiphers(finalValues);
    }
}

19 Source : AbstractSshOptionsEvaluator.java
with GNU Lesser General Public License v3.0
from sshtools

protected static void parsePort(CommandLine commandLine, SshClientArguments arguments) {
    int port = 22;
    if (commandLine.hasOption(Port.PORT_OPTION)) {
        String portValue = commandLine.getOptionValue(Port.PORT_OPTION);
        try {
            port = Integer.parseInt(portValue);
        } catch (Exception e) {
            port = 22;
        }
    }
    arguments.setPort(port);
}

19 Source : AbstractSshOptionsEvaluator.java
with GNU Lesser General Public License v3.0
from sshtools

protected static void parseCompression(CommandLine commandLine, SshClientArguments arguments) {
    if (commandLine.hasOption(Compression.COMPRESSION_OPTION)) {
        arguments.setCompression(true);
    }
}

19 Source : FrameworkOptions.java
with Apache License 2.0
from srasthofer

public void parse(String[] args) {
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h") || cmd.hasOption("help"))
            showHelpMessage();
        // mandatory options
        apkPath = cmd.getOptionValue("apk");
        androidJarPath = cmd.getOptionValue("androidJar");
        packageName = cmd.getOptionValue("packageName");
        resultDir = cmd.getOptionValue("resultDir");
        frameworkDir = cmd.getOptionValue("frameworkDir");
        devicePort = cmd.getOptionValue("devicePort");
        int devicePortInt = Integer.parseInt(devicePort);
        if (devicePortInt < 5554 || devicePortInt > 5680)
            throw new RuntimeException("port number has to be an integer number between 5554 and 5680");
        if (devicePortInt % 2 != 0)
            throw new RuntimeException("port number has to be an even integer number");
        apkMD5 = generateMD5OfFile(apkPath);
        // optional options
        if (cmd.hasOption("KEYSTORE_PATH")) {
            KEYSTORE_PATH = cmd.getOptionValue("KEYSTORE_PATH");
        }
        if (cmd.hasOption("KEYSTORE_NAME")) {
            KEYSTORE_NAME = cmd.getOptionValue("KEYSTORE_NAME");
        }
        if (cmd.hasOption("KEYSTORE_PreplacedWORD")) {
            KEYSTORE_PreplacedWORD = cmd.getOptionValue("KEYSTORE_PreplacedWORD");
        }
        if (cmd.hasOption("BUILD_TOOLS")) {
            BUILD_TOOLS = cmd.getOptionValue("BUILD_TOOLS");
        }
        if (cmd.hasOption("KEYSTORE_PATH") && cmd.hasOption("KEYSTORE_NAME") && cmd.hasOption("KEYSTORE_PreplacedWORD") && cmd.hasOption("BUILD_TOOLS"))
            deployApp = true;
        if (cmd.hasOption("PLATFORM_TOOLS")) {
            PLATFORM_TOOLS = cmd.getOptionValue("PLATFORM_TOOLS");
        }
        if (cmd.hasOption("Z3SCRIPT_LOCATION")) {
            Z3SCRIPT_LOCATION = cmd.getOptionValue("Z3SCRIPT_LOCATION");
        }
        if (cmd.hasOption("TEST_SERVER")) {
            testServer = true;
        }
        if (cmd.hasOption("RECORD_PATH_EXECUTION")) {
            recordPathExecution = true;
        }
        if (cmd.hasOption("MERGE_DATAFLOWS")) {
            mergeDataFlows = true;
        }
        if (cmd.hasOption("ORIGINAL_APK_PATH")) {
            apkPathOriginalAPK = cmd.getOptionValue("ORIGINAL_APK_PATH");
        }
        if (cmd.hasOption("nbSeeds")) {
            nbSeeds = Integer.parseInt(cmd.getOptionValue("nbSeeds"));
        }
        if (cmd.hasOption("inactivityTimeout")) {
            inactivityTimeout = Integer.parseInt(cmd.getOptionValue("inactivityTimeout"));
        }
        if (cmd.hasOption("maxRestarts")) {
            maxRestarts = Integer.parseInt(cmd.getOptionValue("maxRestarts"));
        }
        if (cmd.hasOption("enableLogcatViewer")) {
            enableLogcatViewer = true;
        }
        if (cmd.hasOption("traceConstructionMode")) {
            traceConstructionMode = TraceConstructionMode.valueOf(cmd.getOptionValue("traceConstructionMode"));
        }
        if (cmd.hasOption("evaluationJustStartApp")) {
            evaluationJustStartApp = true;
            evaluationOnly = true;
        }
        if (cmd.hasOption("evaluationStartAppAndSimpleEvent")) {
            evaluationStartAppAndSimpleEvent = true;
            evaluationOnly = true;
        }
    } catch (Exception e) {
        LoggerHelper.logEvent(MyLevel.EXCEPTION_replacedYSIS, e.getMessage());
        e.printStackTrace();
        showHelpMessage();
        System.exit(1);
    }
}

19 Source : SQFLint.java
with MIT License
from SkaceKamen

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Options options = new Options();
    CommandLineParser cmdParser = new DefaultParser();
    CommandLine cmd;
    options.addOption("j", "json", false, "output json");
    options.addOption("v", "variables", false, "output variables info (only in json mode)");
    options.addOption("e", "error", false, "stop on error");
    options.addOption("nw", "no-warning", false, "skip warnings");
    options.addOption("we", "warning-as-error", false, "output warnings as errors");
    options.addOption("oc", "output-code", false, "output ERR return code when any error is encountered");
    options.addOption("cp", "check-paths", false, "check for path existence for exevm and preprocessfile");
    options.addOption("r", "root", true, "root for path checking (path to file is used if file is specified)");
    options.addOption("h", "help", false, "");
    options.addOption("iv", "ignore-variables", true, "ignored variables are treated as internal command");
    options.addOption("s", "server", false, "run as server");
    options.addOption("ip", "include-prefix", true, "adds include prefix override, format: prefix,path_to_use");
    options.addOption("ncs", "no-context-separation", true, "disable context separation");
    options.addOption("bl", "bench-logs", false, "output benchlog to stderr");
    try {
        cmd = cmdParser.parse(options, args);
    } catch (org.apache.commons.cli.ParseException ex) {
        Logger.getLogger(SQFLint.clreplaced.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    if (cmd.hasOption("h") || cmd.getArgs().length > 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sqflint [OPTIONS] [FILE]", "Scans SQF file for errors and potential problems.", options, "Spaghetti");
        return;
    }
    String root = null;
    String[] ignoredVariables = new String[0];
    if (cmd.hasOption("r")) {
        root = cmd.getOptionValue("r");
    }
    if (cmd.hasOption("iv")) {
        ignoredVariables = cmd.getOptionValues("iv");
    }
    cz.zipek.sqflint.linter.Options linterOptions;
    try {
        linterOptions = new cz.zipek.sqflint.linter.Options();
    } catch (IOException ex) {
        Logger.getLogger(SQFLint.clreplaced.getName()).log(Level.SEVERE, null, ex);
        return;
    }
    if (cmd.hasOption("ip")) {
        for (String value : cmd.getOptionValues("ip")) {
            String[] split = value.split(",");
            if (split.length != 2) {
                System.out.println("Invalid include prefix : " + value);
                System.out.println("Include prefix format is: prefix,include_path");
                return;
            }
            linterOptions.getIncludePaths().put(split[0], split[1]);
        }
    }
    linterOptions.setBenchLogs(cmd.hasOption("bl"));
    linterOptions.setRootPath(root);
    linterOptions.addIgnoredVariables(ignoredVariables);
    if (cmd.hasOption("j")) {
        linterOptions.setOutputFormatter(new JSONOutput());
    }
    linterOptions.setStopOnError(cmd.hasOption("e"));
    linterOptions.setSkipWarnings(cmd.hasOption("nw"));
    linterOptions.setOutputVariables(cmd.hasOption("v"));
    linterOptions.setExitCodeEnabled(cmd.hasOption("oc"));
    linterOptions.setWarningAsError(cmd.hasOption("we"));
    linterOptions.setCheckPaths(cmd.hasOption("cp"));
    if (!cmd.hasOption("s")) {
        InputStream contents = null;
        String filename = null;
        if (cmd.getArgs().length == 0) {
            try {
                if (root != null) {
                    filename = Paths.get(root).resolve("file.sqf").toString();
                }
                contents = System.in;
            } catch (Exception ex) {
                Logger.getLogger(SQFLint.clreplaced.getName()).log(Level.SEVERE, null, ex);
                return;
            }
        } else if (cmd.getArgs().length == 1) {
            filename = cmd.getArgs()[0];
            if (root == null) {
                root = Paths.get(filename).toAbsolutePath().getParent().toString();
            }
            try {
                contents = new FileInputStream(filename);
            } catch (FileNotFoundException e) {
                Logger.getLogger(SQFLint.clreplaced.getName()).log(Level.SEVERE, filename + " not found", e);
                System.exit(1);
            }
        }
        linterOptions.setRootPath(root);
        SqfFile sqfFile = new SqfFile(linterOptions, StreamUtil.streamToString(contents), filename);
        System.exit(sqfFile.process());
    } else {
        SQFLintServer server = new SQFLintServer(linterOptions);
        server.start();
    }
}

19 Source : StlPerfTest.java
with Apache License 2.0
from ServiceNow

private static void parseCommandLine(String[] args) {
    Options options = new Options();
    Option input = new Option("n", "timed-iterations", true, "number of iterations of timing loop");
    input.setRequired(false);
    options.addOption(input);
    Option output = new Option("w", "warmup-iterations", true, "number of warm-up iterations before timing loop");
    output.setRequired(false);
    options.addOption(output);
    Option hourly = new Option("h", "hourly", false, "whether to use hourly data");
    hourly.setRequired(false);
    options.addOption(hourly);
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("StlPerfTest", options);
        System.exit(1);
        return;
    }
    if (cmd.hasOption("hourly")) {
        System.out.println("Running hourly stress test");
        fRunCo2 = false;
        fTimedIterations = 200;
        fWarmupIterations = 30;
    } else {
        System.out.println("Running CO2 test");
        fTimedIterations = 2000;
        fWarmupIterations = 30;
    }
    String nStr = cmd.getOptionValue("number");
    if (nStr != null)
        fTimedIterations = Integer.parseInt(nStr);
    String wStr = cmd.getOptionValue("warmup-iterations");
    if (wStr != null)
        fWarmupIterations = Integer.parseInt(wStr);
}

19 Source : RemoveWatchesCommand.java
with Apache License 2.0
from sereca

@Override
public boolean exec() throws KeeperException, InterruptedException {
    String path = args[1];
    WatcherType wtype = WatcherType.Any;
    // if no matching option -c or -d or -a is specified, we remove
    // the watches of the given node by choosing WatcherType.Any
    if (cl.hasOption("c")) {
        wtype = WatcherType.Children;
    } else if (cl.hasOption("d")) {
        wtype = WatcherType.Data;
    } else if (cl.hasOption("a")) {
        wtype = WatcherType.Any;
    }
    // whether to remove the watches locally
    boolean local = cl.hasOption("l");
    try {
        zk.removeAllWatches(path, wtype, local);
    } catch (KeeperException.NoWatcherException ex) {
        err.println(ex.getMessage());
        return false;
    }
    return true;
}

19 Source : Application.java
with Apache License 2.0
from SAP

/**
 * Checks command-line options and throws an exception if something is wrong.
 *
 * @param commandLine The command-line options.
 * @throws IllegalArgumentException If the options are invalid.
 */
private static void checkOptionsIn(CommandLine commandLine) {
    if (commandLine.hasOption("h")) {
        return;
    }
    if (!commandLine.hasOption("url") && !commandLine.hasOption("config") && !commandLine.hasOption("gav")) {
        throw new IllegalArgumentException("You have to give me either --url, --gav or --config option!");
    }
    if (commandLine.hasOption("report-type") && !commandLine.hasOption("report-file")) {
        throw new IllegalArgumentException("The option --report-type has to be used with --report-file");
    }
    if (commandLine.hasOption("report-type") && !Arrays.asList("text", "markdown").contains(commandLine.getOptionValue("report-type"))) {
        throw new IllegalArgumentException(String.format("Unknown report type: %s", commandLine.getOptionValue("report-type")));
    }
}

19 Source : Main.java
with Apache License 2.0
from s3curitybug

/**
 * Parses the introduced arguments to a map from ArgsOptions to String[] of introduced values.
 *
 * @param options Prepared options.
 * @param args Introduced arguments.
 * @return Map from ArgsOptions to String[] of introduced values.
 * @throws ParseException If an error occurs parsing any of the options or the introduced
 *         arguments do not fit any of them.
 */
private static Map<ArgsOptions, String[]> parseOptions(Options options, String[] args) throws ParseException {
    CommandLine cmd = new DefaultParser().parse(options, args);
    Map<ArgsOptions, String[]> parsedOptions = new HashMap<>(ArgsOptions.values().length);
    for (ArgsOptions argsOption : ArgsOptions.values()) {
        if (cmd.hasOption(argsOption.longOption)) {
            String[] optionValues = cmd.getOptionValues(argsOption.longOption);
            if (optionValues == null) {
                optionValues = new String[0];
            }
            if (argsOption.minArgs > 0 && optionValues.length == 0) {
                throw new ParseException(String.format("Missing %s for option: %s.", argsOption.maxArgs < 0 || argsOption.maxArgs > 1 ? "arguments" : "argument", argsOption.display()));
            }
            if (argsOption.maxArgs == 0 && optionValues.length > 0) {
                throw new ParseException(String.format("Option %s takes no arguments.", argsOption.display()));
            }
            if (argsOption.minArgs > 0 && optionValues.length < argsOption.minArgs) {
                throw new ParseException(String.format("Too few arguments for option: %s.", argsOption.display()));
            }
            if (argsOption.maxArgs > 0 && optionValues.length > argsOption.maxArgs) {
                throw new ParseException(String.format("Too many arguments for option: %s.", argsOption.display()));
            }
            parsedOptions.put(argsOption, optionValues);
        } else {
            if (argsOption.required) {
                throw new ParseException(String.format("Missing required option: %s.", argsOption.display()));
            }
        }
    }
    return parsedOptions;
}

19 Source : SignerCLI.java
with MIT License
from ria-ee

// ------------------------------------------------------------------------
/**
 * Program entry point.
 * @param args arguments
 * @throws Exception if an error occurs
 */
public static void main(String[] args) throws Exception {
    CommandLine cmd = getCommandLine(args);
    if (cmd.hasOption("verbose")) {
        verbose = true;
    }
    if (cmd.hasOption("help")) {
        processCommandAndExit("?list");
        return;
    }
    ActorSystem actorSystem = ActorSystem.create("SignerConsole", ConfigFactory.load().getConfig("signer-console").withFallback(ConfigFactory.load()));
    try {
        SignerClient.init(actorSystem);
        String[] arguments = cmd.getArgs();
        if (arguments.length > 0) {
            processCommandAndExit(StringUtils.join(arguments, " "));
        } else {
            startCommandLoop();
        }
    } finally {
        Await.ready(actorSystem.terminate(), Duration.Inf());
    }
}

19 Source : OperationalDataRecordsGenerator.java
with MIT License
from ria-ee

/**
 * Main function.
 * @param args args
 * @throws Exception if something goes wrong.
 */
public static void main(String[] args) throws Exception {
    CommandLine cmd = parseCommandLine(args);
    if (cmd.hasOption("help")) {
        usage();
        System.exit(0);
    }
    long startTimestamp = cmd.getOptionValue("timestamp") != null ? Long.parseLong(cmd.getOptionValue("timestamp")) : DEFAULT_FIRST_TIMESTAMP;
    int batchSize = cmd.getOptionValue("batch-size") != null ? Integer.parseInt(cmd.getOptionValue("batch-size")) : DEFAULT_BATCH_SIZE;
    int batchCount = cmd.getOptionValue("batch-count") != null ? Integer.parseInt(cmd.getOptionValue("batch-count")) : DEFAULT_BATCH_COUNT;
    String longString = cmd.getOptionValue("long-string-length") != null ? getDummyStr(Integer.parseInt(cmd.getOptionValue("long-string-length"))) : getDummyStr(DEFAULT_LONG_STRING_LENGTH);
    String shortString = cmd.getOptionValue("short-string-length") != null ? getDummyStr(Integer.parseInt(cmd.getOptionValue("short-string-length"))) : getDummyStr(DEFAULT_SHORT_LONG_STRING_LENGTH);
    log.info("first timestamp: {}, batch-size: {}, batch-count: {}", startTimestamp, batchSize, batchCount);
    for (int i = 0; i < batchCount; ++i) {
        storeRecords(batchSize, startTimestamp++, longString, shortString);
    }
    log.info("{} records generated", batchCount * batchSize);
}

19 Source : ConfProxyUtilDelSigningKey.java
with MIT License
from ria-ee

@Override
final void execute(final CommandLine commandLine) throws Exception {
    ensureProxyExists(commandLine);
    final ConfProxyProperties conf = loadConf(commandLine);
    if (commandLine.hasOption("key-id")) {
        String keyId = commandLine.getOptionValue("k");
        if (keyId.equals(conf.getActiveSigningKey())) {
            fail("Not allowed to delete an active signing key!", null);
        }
        if (!conf.removeKeyId(keyId)) {
            fail("The key ID '" + keyId + "' could not be found in '" + CONF_INI + "'.", null);
        }
        System.out.println("Deleted key from '" + CONF_INI + "'.");
        conf.deleteCert(keyId);
        System.out.println("Deleted self-signed certificate 'cert_" + keyId + ".pem'");
        SignerClient.execute(new DeleteKey(keyId, true));
        System.out.println("Deleted key from signer");
    } else {
        printHelp();
    }
}

19 Source : ConfProxyUtilAddSigningKey.java
with MIT License
from ria-ee

@Override
final void execute(final CommandLine commandLine) throws Exception {
    ensureProxyExists(commandLine);
    final ConfProxyProperties conf = loadConf(commandLine);
    if (commandLine.hasOption("key-id")) {
        String keyId = commandLine.getOptionValue("k");
        addSigningKey(conf, keyId);
    } else if (commandLine.hasOption("token-id")) {
        String tokenId = commandLine.getOptionValue("t");
        KeyInfo keyInfo = SignerClient.execute(new GenerateKey(tokenId, "key-" + System.currentTimeMillis()));
        System.out.println("Generated key with ID " + keyInfo.getId());
        addSigningKey(conf, keyInfo.getId());
    } else {
        printHelp();
    }
}

19 Source : ConfProxyUtil.java
with MIT License
from ria-ee

/**
 * Loads configuration proxy properties based on the instance provided
 * through the commandline.
 * @param commandLine holds arguments for the utility program
 * @return configuration proxy properties instance
 */
protected final ConfProxyProperties loadConf(final CommandLine commandLine) {
    if (commandLine.hasOption(PROXY_INSTANCE.getLongOpt())) {
        String instance = commandLine.getOptionValue(PROXY_INSTANCE.getOpt());
        try {
            return new ConfProxyProperties(instance);
        } catch (Exception e) {
            fail("Could not load configuration for '" + instance, e);
        }
    } else {
        printHelp();
        System.exit(0);
    }
    return null;
}

19 Source : ConfigurationClientMain.java
with MIT License
from ria-ee

private static ParamsValidator getParamsValidator(CommandLine cmd) {
    if (cmd.hasOption(OPTION_VERIFY_PRIVATE_PARAMS_EXISTS)) {
        return new ParamsValidator(CONTENT_ID_PRIVATE_PARAMETERS, ERROR_CODE_MISSING_PRIVATE_PARAMS);
    } else if (cmd.hasOption(OPTION_VERIFY_ANCHOR_FOR_EXTERNAL_SOURCE)) {
        return new SharedParamsValidator(CONTENT_ID_SHARED_PARAMETERS, ERROR_CODE_ANCHOR_NOT_FOR_EXTERNAL_SOURCE);
    } else {
        return new ParamsValidator(null, 0);
    }
}

19 Source : TplCLI.java
with Apache License 2.0
from reddr

private static boolean checkOptionalUse(CommandLine cmd, String option, LibScoutConfig.OpMode... modes) {
    if (!Arrays.asList(modes).contains(LibScoutConfig.opmode))
        return false;
    return cmd.hasOption(option);
}

19 Source : BootstrapMavenOptionsParser.java
with Apache License 2.0
from quarkusio

private static void putBoolean(CommandLine cmdLine, Map<String, Object> map, String name) {
    if (cmdLine.hasOption(name)) {
        map.put(name, Boolean.TRUE.toString());
    }
}

19 Source : BootstrapMavenOptionsParser.java
with Apache License 2.0
from quarkusio

private static void putBoolean(CommandLine cmdLine, Map<String, Object> map, char name) {
    if (cmdLine.hasOption(name)) {
        map.put(String.valueOf(name), Boolean.TRUE.toString());
    }
}

19 Source : ToolOptions.java
with Mozilla Public License 2.0
from powsybl

/**
 * Return true if the option is defined.
 * @param option The option name
 * @return       {@code true} if the option is defined.
 */
public boolean hasOption(String option) {
    return line.hasOption(option);
}

19 Source : CommandLineUtil.java
with Mozilla Public License 2.0
from powsybl

public static <T extends Enum<T>> T getOptionValue(CommandLine line, String option, Clreplaced<T> clazz, T defaultValue) {
    Objects.requireNonNull(line);
    Objects.requireNonNull(option);
    Objects.requireNonNull(clazz);
    if (line.hasOption(option)) {
        return Enum.valueOf(clazz, line.getOptionValue(option));
    } else {
        return defaultValue;
    }
}

19 Source : ActionSimulatorToolTest.java
with Mozilla Public License 2.0
from powsybl

@Test
public void notsupportOptionsInParallelMode() throws Exception {
    when(commandLine.hasOption("task-count")).thenReturn(true);
    when(commandLine.hasOption("output-file")).thenReturn(true);
    when(commandLine.hasOption("output-case-folder")).thenReturn(true);
    thrown.expect(IllegalArgumentException.clreplaced);
    thrown.expectMessage("Not supported in parallel mode yet.");
    tool.run(commandLine, runningContext);
}

19 Source : ActionSimulatorToolTest.java
with Mozilla Public License 2.0
from powsybl

@Test
public void missingOutputFileInParallelMode() throws Exception {
    when(commandLine.hasOption("task-count")).thenReturn(true);
    when(commandLine.hasOption("output-file")).thenReturn(false);
    thrown.expect(IllegalArgumentException.clreplaced);
    thrown.expectMessage("Missing required option: output-file in parallel mode");
    tool.run(commandLine, runningContext);
}

19 Source : AbstractWebServiceClient.java
with Apache License 2.0
from Pardus-Engerek

protected String getPreplacedwordType() {
    if (commandLine.hasOption('P')) {
        String optionValue = commandLine.getOptionValue('P');
        if ("text".equals(optionValue)) {
            return WSConstants.PW_TEXT;
        } else if ("digest".equals(optionValue)) {
            return WSConstants.PW_DIGEST;
        } else {
            throw new IllegalArgumentException("Unknown preplacedword type " + optionValue);
        }
    } else {
        return WSConstants.PW_TEXT;
    }
}

19 Source : AbstractWebServiceClient.java
with Apache License 2.0
from Pardus-Engerek

private void parseCommandLine(String[] args) throws ParseException {
    CommandLineParser cliParser = new GnuParser();
    commandLine = cliParser.parse(options, args, true);
    if (commandLine.hasOption('h')) {
        printHelp();
        System.exit(0);
    }
    if (commandLine.hasOption('v')) {
        verbose = true;
    }
}

See More Examples