Java 类org.apache.commons.cli.UnrecognizedOptionException 实例源码

项目:security-karate    文件:CliLoader.java   
/**
 * Parses the command line arguments and returns a Configuration according to the given
 * switches.
 * @param args the command line arguments given to main
 * @return the configuration
 * @throws ParseException
 */
public Configuration parseArgs(String[] args) throws ParseException {
    CommandLine cl = null;
    try {
        cl = parser.parse(options, args);
    } catch (UnrecognizedOptionException uoe){
        logger.error("unrecognized option: {}",uoe.getOption());
        printHelp();
        System.exit(1);
    }

    Configuration config = new Configuration();
    if(!cl.hasOption('c')){
        config.setTargetCount(1);
    } else {
        config.setTargetCount(Long.parseLong(cl.getOptionValue('c')));
    }
    if(!cl.hasOption('p')){
        config.setUserNamePrefix("user");
    } else {
        config.setUserNamePrefix(cl.getOptionValue('p'));
    }

    return config;
}
项目:rug-cli    文件:ParseExceptionProcessor.java   
@SuppressWarnings("unchecked")
public static String process(ParseException e) {
    if (e instanceof MissingOptionException) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> options = ((MissingOptionException) e).getMissingOptions().iterator();
        while (options.hasNext()) {
            sb.append(options.next());
            if (options.hasNext()) {
                sb.append(", ");
            }
        }
        return String.format("Missing required option(s) %s.", sb.toString());
    }
    else if (e instanceof MissingArgumentException) {
        return String.format("%s is missing a required argument.",
                ((MissingArgumentException) e).getOption());
    }
    else if (e instanceof UnrecognizedOptionException) {
        return String.format("%s is not a valid option.",
                ((UnrecognizedOptionException) e).getOption());
    }
    else {
        return String.format("%s.", e.getMessage());
    }
}
项目:build-management    文件:CMnCmdLineTool.java   
/**
 * Parse the command line arguments.
 */
protected static CommandLine parseArgs(String[] args) {
    CommandLine cl = null;
    try {
        cl = argParser.parse(cmdOptions, args);
    } catch (AlreadySelectedException dupex) {
        displayHelp();
        display("\nDuplicate option: " + dupex.getMessage());
    } catch (MissingOptionException opex) {
        displayHelp();
        display("\nMissing command line option: " + opex.getMessage());
    } catch (UnrecognizedOptionException uex) {
        displayHelp();
        display(uex.getMessage());
    } catch (ParseException pe) {
        display("Unable to parse the command line arguments: " + pe);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return cl;
}
项目:vcloud-client    文件:Configuration.java   
public static CommandLine parseCli(ModeType mode, String[] args) {
    CommandLine cli = null;
    Options opt = ConfigModes.getMode(mode);
    try {
        cli = new IgnorePosixParser(true).parse(opt, args);
    } catch (MissingArgumentException me) {
        Formatter.usageError(me.getLocalizedMessage(), mode);
        System.exit(-1);
    } catch (MissingOptionException mo) {
        Formatter.usageError(mo.getLocalizedMessage(), mode);
        System.exit(-1);
    } catch (AlreadySelectedException ase) {
        Formatter.usageError(ase.getLocalizedMessage(), mode);
    } catch (UnrecognizedOptionException uoe) {
        Formatter.usageError(uoe.getLocalizedMessage(), mode);
    } catch (ParseException e) {
        Formatter.printStackTrace(e);
        System.exit(-1);
    }

    return cli;
}
项目:security-karate    文件:CliLoader.java   
/**
 * Parses the command line arguments and returns a Configuration according to the given
 * switches.
 * @param args the command line arguments given to main
 * @return the configuration
 * @throws ParseException
 */
public Configuration parseArgs(String[] args) throws ParseException {
    CommandLine cl = null;
    try {
        cl = parser.parse(options, args);
    } catch (UnrecognizedOptionException uoe){
        logger.error("unrecognized option: {}",uoe.getOption());
        printHelp();
        System.exit(1);
    }
    Configuration config = new Configuration();
    config.setLoginUrl(cl.getOptionValue('t'));

    if(!cl.hasOption('l')){
        config.setLoops(1);
    } else {
        config.setLoops(Long.parseLong(cl.getOptionValue('l')));
    }

    if(!cl.hasOption('r')){
        config.setRequestsPerMinute(-1);
    } else {
        config.setRequestsPerMinute(Long.parseLong(cl.getOptionValue('r')));
    }

    if(!cl.hasOption('i')){
        config.setOriginIpAddress(null);
    } else {
        config.setOriginIpAddress(cl.getOptionValue('i'));
    }

    config.setCredentials(getCredentials(cl.getOptionValue('f'), cl.getOptionValues('c')));
    if (!ConfigurationValidator.isValid(config)){
        printHelp();
    }
    return config;
}
项目:keyword-optimizer    文件:CommandLineTest.java   
/**
 * Checks if the specifying some random argument work throws an exception.
 */
@Test
public void checkRandomArgDoesNotWork() throws KeywordOptimizerException {
  thrown.expect(KeywordOptimizerException.class);
  thrown.expectCause(isA(UnrecognizedOptionException.class));
  KeywordOptimizer.run("-x");
}
项目:herd    文件:ArgumentParserTest.java   
@Test(expected = UnrecognizedOptionException.class)
public void testParseArgumentsUnrecognizedOptionException() throws ParseException
{
    ArgumentParser argParser = new ArgumentParser("");
    argParser.addArgument("a", "configured_option", false, "Some flag parameter", false);
    argParser.parseArguments(new String[] {"-b", "unrecognized_option"});
}
项目:mara    文件:PosixParserRequiredProps.java   
/**
 * Verifies that the properties don't contain undefined options which will
 * cause the base parser to blowup.
 *
 * @param options                       the options config
 * @param properties                    overriding properties
 * @throws UnrecognizedOptionException  if a property exists that isn't
 *                                      configured in the options.
 */
protected void validateProperties(Options options, Properties properties)
        throws UnrecognizedOptionException {
    if (properties != null) {
        for (Entry<Object, Object> e : properties.entrySet()) {
            String arg = (String) e.getKey();
            boolean hasOption = options.hasOption(arg);
            if (!hasOption) {
                throw new UnrecognizedOptionException(
                        "Unrecognized option: " + arg, arg);
            }
        }
    }
}
项目:anonimatron    文件:Anonimatron.java   
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OPT_CONFIGFILE, true,
            "The XML Configuration file describing what to anonymize.");
    options.addOption(OPT_SYNONYMFILE, true,
            "The XML file to read/write synonyms to. "
                    + "If the file does not exist it will be created.");
    options.addOption("configexample", false,
            "Prints out a demo/template configuration file.");
    options.addOption(OPT_DRYRUN, false, "Do not make changes to the database.");

    BasicParser parser = new BasicParser();

    try {
        CommandLine commandline = parser.parse(options, args);
        String configfileName = commandline.getOptionValue(OPT_CONFIGFILE);
        String synonymfileName = commandline.getOptionValue(OPT_SYNONYMFILE);
        boolean dryrun = commandline.hasOption(OPT_DRYRUN);

        if (configfileName != null) {
            anonymize(configfileName, synonymfileName, dryrun);
        } else if (commandline.hasOption("configexample")) {
            printDemoConfiguration();
        } else {
            printHelp(options);
        }
    } catch (UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        printHelp(options);
    }
}
项目:hops    文件:ClientRMService.java   
private ReservationACL getReservationACLFromAuditConstant(
        String auditConstant) throws YarnException{
  if (auditConstant.equals(AuditConstants.SUBMIT_RESERVATION_REQUEST)) {
    return ReservationACL.SUBMIT_RESERVATIONS;
  } else if (auditConstant.equals(AuditConstants.LIST_RESERVATION_REQUEST)) {
    return ReservationACL.LIST_RESERVATIONS;
  } else if (auditConstant.equals(AuditConstants.DELETE_RESERVATION_REQUEST)
        || auditConstant.equals(AuditConstants.UPDATE_RESERVATION_REQUEST)) {
    return ReservationACL.ADMINISTER_RESERVATIONS;
  } else {
    String error = "Audit Constant " + auditConstant + " is not recognized.";
    LOG.error(error);
    throw RPCUtil.getRemoteException(new UnrecognizedOptionException(error));
  }
}
项目:parquet-mr    文件:ArgsOnlyCommand.java   
@Override
public void execute(CommandLine options) throws Exception {
  String[] args = options.getArgs();
  if (args.length < min) {
    throw new MissingArgumentException("missing required arguments");
  }

  if (args.length > max) {
    throw new UnrecognizedOptionException("unknown extra argument \"" + args[max] + "\"");
  }
}
项目:ngcalsync    文件:StartApplicationTest.java   
/**
 * Invalid arguments on the command line result in an exception.
 *
 * @throws Exception
 */
@Test
public void testParseCommandLine_InvalidArguments_ThrowsException() throws Exception {
    // Setup
    final StartApplication main = new StartApplication();

    thrown.expect(UnrecognizedOptionException.class);
    thrown.expectMessage("Unrecognized option: -foo");

    // Run
    main.parseCommandLine(new String[] { "-foo" });
}
项目:parquet-tools    文件:ArgsOnlyCommand.java   
@Override
public void execute(CommandLine options) throws Exception {
  String[] args = options.getArgs();
  if (args.length < min) {
    throw new MissingArgumentException("missing required arguments");
  }

  if (args.length > max) {
    throw new UnrecognizedOptionException("unknown extra argument \"" + args[max] + "\"");
  }
}
项目:nifi-config    文件:MainTest.java   
@Test(expected = UnrecognizedOptionException.class)
public void mainPrintUsage5Test() throws Exception {
    Main.main(new String[]{"-nifi","http://localhost:8080/nifi-api", "-branch","\"root>N2\"","-conf","adr","-m","undeploy", "-userErr","user"});
}
项目:flink-operator-library    文件:StreamingAppRuntimeTest.java   
/**
 * Test case for {@link StreamingAppRuntime#parseCommandLine(String[])} being
 * provided an array showing unknown settings
 */
@Test(expected=UnrecognizedOptionException.class)
public void testParseCommandLine_withUnknownSettings() throws Exception {
    new DummyLogProcessingRuntime(new CountDownLatch(1)).parseCommandLine(new String[]{"-a","123"});
}
项目:flink-operator-library    文件:StreamingAppRuntimeTest.java   
/**
 * Test case for {@link StreamingAppRuntime#parseCommandLine(String[])} being
 * provided an array showing known and unknown settings
 */
@Test(expected=UnrecognizedOptionException.class)
public void testParseCommandLine_withKnownAndUnknownSettings() throws Exception {
    new DummyLogProcessingRuntime(new CountDownLatch(1)).parseCommandLine(new String[]{"-a","123", "-f", "/tmp/file.txt"});
}
项目:korat    文件:ConfigLoader.java   
/**
 * <p>Parses options from the given string array. </p>
 *  
 * The algorithm for handling options is as follows:
 * <ol>
 * <li>if <code>HELP</code> options is found - prints usage and exists</li>
 * <li>if the given options are cmd line options (not from config file) and 
 * if the <code>CONFIG_FILE</code> option is found, then first loads options from the
 * file specified through the <code>CONFIG_FILE</code> option.</li>
 * <li>loads options from cmd line</li>
 * <li>stores options to <code>ConfigManger</code> instance</li>
 * <li>checks for required options</li>
 * <li>initializes stuff according to the previously parsed options</li>
 * </ol> 
 * 
 * @param args 
 *           options to parse
 * @param fromFile 
 *           whether the given options are from file or from cmd line.
 * @see #loadFromFile(String)
 * @see #processConfigFile(InputStream)
 * @see #storeOptions()
 * @see #checkRequiredOptions()
 * @see #initStuffFromOptions()          
 */
private void parseArgs(String[] args, boolean fromFile) {
    try {

        CommandLine cl = new PosixParser().parse(koratOptions, args);
        if (fromFile) {
            fromFileCmdLine = cl;
        } else {
            cmdLine = cl;
        }
        if (cl.hasOption(HELP.getOpt())) {
            printUsage(koratOptions);
            System.exit(0);
        }
        if (!fromFile) {
            if (cl.hasOption(CONFIG_FILE.getOpt())) {
                String confFileName = cl.getOptionValue(CONFIG_FILE.getOpt());
                try {
                    args = loadFromFile(confFileName);
                    parseArgs(args, true);
                } catch (IOException e) {
                    System.err.println("Cannot load file: " + confFileName);
                }
            }
        }

        storeOptions();
        checkRequiredOptions();
        initStuffFromOptions();

    } catch (ParseException pe) {
        String msg = "";
        if (pe instanceof MissingOptionException)
            msg = "The following required options are missing: ";
        else if (pe instanceof UnrecognizedOptionException)
            msg = "The following options were not recognized: ";
        System.err.println(msg + pe.getMessage());
        System.err.println();
        System.exit(5);
    }
}
项目:netarchivesuite-svngit-migration    文件:CommandLineParser.java   
/**
 * Constructor.
 *
 * @param args Command-line arguments to process.
 * @param out PrintStream to write on.
 *
 * @throws ParseException Failed parse of command line.
 */
public CommandLineParser(String [] args, PrintWriter out)
throws ParseException {
    super();

    this.out = out;

    this.options = new Options();
    this.options.addOption(new Option("h","help", false,
            "Prints this message and exits."));

    Option opt = new Option("o","mode", true,
            "Index by URL, HASH or BOTH. Default: BOTH.");
    opt.setArgName("type");
    this.options.addOption(opt);

    this.options.addOption(new Option("s","equivalent", false,
            "Include a stripped URL in the index for equivalent URL " +
            "matches."));

    this.options.addOption(new Option("t","timestamp", false,
            "Include the time of fetch in the index."));

    this.options.addOption(new Option("e","etag", false,
    "Include etags in the index (if available in the source)."));

    opt = new Option("m","mime", true,
            "A filter on what mime types are added into the index " +
            "(blacklist). Default: ^text/.*");
    opt.setArgName("reg.expr.");
    this.options.addOption(opt);

    this.options.addOption(new Option("w","whitelist", false,
            "Make the --mime filter a whitelist instead of blacklist."));

    opt = new Option("i","iterator", true,
            "An iterator suitable for the source data (default iterator " +
            "works on Heritrix's crawl.log).");
    opt.setArgName("classname");
    this.options.addOption(opt);

    this.options.addOption(new Option("a","add", false,
        "Add source data to existing index."));

    opt = new Option("r","origin", true,
            "If set, the 'origin' of each URI will be added to the index." +
            " If no origin is provided by the source data then the " +
            "argument provided here will be used.");
    opt.setArgName("origin");
    this.options.addOption(opt);

    this.options.addOption(new Option("d","skip-duplicates", false,
            "If set, URIs marked as duplicates will not be added to the " +
            "index."));

    PosixParser parser = new PosixParser();
    try {
        this.commandLine = parser.parse(this.options, args, false);
    } catch (UnrecognizedOptionException e) {
        usage(e.getMessage(), 1);
    }
}