System.out.println(e.getMessage()); CommandLine.usage(options, System.out); return;
private int applyValuesToMapField(ArgSpec argSpec, LookBehind lookBehind, Range arity, Stack<String> args, Set<ArgSpec> initialized, String argDescription) throws Exception { Class<?>[] classes = argSpec.auxiliaryTypes(); if (classes.length < 2) { throw new ParameterException(CommandLine.this, argSpec.toString() + " needs two types (one for the map key, one for the value) but only has " + classes.length + " types configured.",argSpec, null); } ITypeConverter<?> keyConverter = getTypeConverter(classes[0], argSpec, 0); ITypeConverter<?> valueConverter = getTypeConverter(classes[1], argSpec, 1); @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) argSpec.getValue(); if (map == null || (!map.isEmpty() && !initialized.contains(argSpec))) { tracer.debug("Initializing binding for %s with empty %s%n", optionDescription("", argSpec, 0), argSpec.type().getSimpleName()); map = createMap(argSpec.type()); // map class argSpec.setValue(map); } initialized.add(argSpec); int originalSize = map.size(); consumeMapArguments(argSpec, lookBehind, arity, args, classes, keyConverter, valueConverter, map, argDescription); parseResult.add(argSpec, position); argSpec.setValue(map); return map.size() - originalSize; }
System.err.println(ex.getMessage()); ex.getCommandLine().usage(System.err);
throw new ParameterException( new CommandLine(this), "--network option and --genesis-file option can't be used at the same time. Please " .orElse(EthNetworkConfig.getNetworkConfig(MAINNET).getNetworkId())); } catch (final DecodeException e) { throw new ParameterException( new CommandLine(this), String.format("Unable to parse genesis file %s.", genesisFile),
throw new ParameterException( new CommandLine(this), "Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled)"
pantheonHome = Paths.get(pantheonHomeProperty); } catch (final InvalidPathException e) { throw new CommandLine.ParameterException( new CommandLine(command), String.format( pantheonHome = Paths.get(path); } catch (final IOException e) { throw new CommandLine.ParameterException( new CommandLine(command), "Unable to create default data directory."); } catch (final FileAlreadyExistsException e) { throw new CommandLine.ParameterException( new CommandLine(command), String.format( e); } catch (final Exception e) { throw new CommandLine.ParameterException( new CommandLine(command), String.format("Error creating directory %s.", pantheonHome.toAbsolutePath()),
parse("sub1 -x abc".split(" ")); } catch (ParameterException ex) { assertTrue(ex.getCommandLine().getCommand() instanceof Top); parse("-o OPT sub1 -wrong ABC".split(" ")); } catch (ParameterException ex) { assertTrue(ex.getCommandLine().getCommand() instanceof Sub1); parse("-o OPT sub2 -wrong ABC".split(" ")); } catch (ParameterException ex) { assertTrue(ex.getCommandLine().getCommand() instanceof Sub2);
MetricsConfiguration metricsConfiguration() { if (isMetricsEnabled && isMetricsPushEnabled) { throw new ParameterException( new CommandLine(this), "--metrics-enabled option and --metrics-push-enabled option can't be used at the same "
@Test public void testIssue207ParameterExceptionProvidesAccessToFailedCommand_Declarative() { @Command(subcommands = {Sub207A.class, Sub207B.class}) class Top { @Option(names = "-o", required = true) String option; } try { new CommandLine(new Top()).parse("sub207A -x abc".split(" ")); } catch (ParameterException ex) { assertTrue(ex.getCommandLine().getCommand() instanceof Top); } try { new CommandLine(new Top()).parse("-o OPT sub207A -wrong ABC".split(" ")); } catch (ParameterException ex) { assertTrue(ex.getCommandLine().getCommand() instanceof Sub207A); } try { new CommandLine(new Top()).parse("-o OPT sub207B -wrong ABC".split(" ")); } catch (ParameterException ex) { assertTrue(ex.getCommandLine().getCommand() instanceof Sub207B); } List<CommandLine> parsed = new CommandLine(new Top()). parse("-o OPT sub207A -x ABC".split(" ")); assertEquals(2, parsed.size()); assertEquals("OPT", ((Top) parsed.get(0).getCommand()).option); assertEquals("ABC", ((Sub207A) parsed.get(1).getCommand()).x); }
private void loadConfigurationFromFile() { if (result == null) { try { final TomlParseResult result = Toml.parse(configFile.toPath()); if (result.hasErrors()) { final String errors = result .errors() .stream() .map(TomlParseError::toString) .collect(Collectors.joining("%n")); ; throw new ParameterException( commandLine, String.format("Invalid TOML configuration : %s", errors)); } this.result = result; } catch (final IOException e) { throw new ParameterException( commandLine, "Unable to read TOML configuration, file not found."); } } checkConfigurationValidity(); } }
private int applyValuesToMapField(ArgSpec argSpec, LookBehind lookBehind, Range arity, Stack<String> args, Set<ArgSpec> initialized, String argDescription) throws Exception { Class<?>[] classes = argSpec.auxiliaryTypes(); if (classes.length < 2) { throw new ParameterException(CommandLine.this, argSpec.toString() + " needs two types (one for the map key, one for the value) but only has " + classes.length + " types configured.",argSpec, null); } ITypeConverter<?> keyConverter = getTypeConverter(classes[0], argSpec, 0); ITypeConverter<?> valueConverter = getTypeConverter(classes[1], argSpec, 1); @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) argSpec.getValue(); if (map == null || (!map.isEmpty() && !initialized.contains(argSpec))) { tracer.debug("Initializing binding for %s with empty %s%n", optionDescription("", argSpec, 0), argSpec.type().getSimpleName()); map = createMap(argSpec.type()); // map class argSpec.setValue(map); } initialized.add(argSpec); int originalSize = map.size(); consumeMapArguments(argSpec, lookBehind, arity, args, classes, keyConverter, valueConverter, map, argDescription); parseResult.add(argSpec, position); argSpec.setValue(map); return map.size() - originalSize; }
@Option( names = {"--rpc-ws-refresh-delay"}, paramLabel = "<refresh delay>", arity = "1", description = "Refresh delay of websocket subscription sync in milliseconds. " + "default: ${DEFAULT-VALUE}", defaultValue = "" + DEFAULT_WEBSOCKET_REFRESH_DELAY ) private Long configureRefreshDelay(final Long refreshDelay) { if (refreshDelay < DEFAULT_MIN_REFRESH_DELAY || refreshDelay > DEFAULT_MAX_REFRESH_DELAY) { throw new ParameterException( new CommandLine(this), String.format( "Refresh delay must be a positive integer between %s and %s", String.valueOf(DEFAULT_MIN_REFRESH_DELAY), String.valueOf(DEFAULT_MAX_REFRESH_DELAY))); } this.rpcWsRefreshDelay = refreshDelay; return refreshDelay; }
/** * TokenTypes.properties generator entry point. * @param args the command line arguments * @throws CheckstyleException if parser or lexer failed or if there is an IO problem **/ public static void main(String... args) throws CheckstyleException { final CliOptions cliOptions = new CliOptions(); final CommandLine cmd = new CommandLine(cliOptions).setUsageHelpWidth(USAGE_HELP_WIDTH); try { final ParseResult parseResult = cmd.parseArgs(args); if (parseResult.isUsageHelpRequested()) { cmd.usage(System.out); } else { writePropertiesFile(cliOptions); } } catch (ParameterException ex) { System.err.println(ex.getMessage()); ex.getCommandLine().usage(System.err); } }
@Test public void testExceptionHandlingCreatesCommandLineIfNecessary() throws Exception { Method setX = ModelMethodBindingBean.class.getDeclaredMethod("setX", int.class); setX.setAccessible(true); CommandSpec spec = CommandSpec.create(); assertNull(spec.commandLine()); MethodBinding binding = new MethodBinding(null, setX, spec); try { binding.set(41); fail("Expect exception"); } catch (Exception ex) { assertNotNull(spec.commandLine()); // has been set ParameterException pex = (ParameterException) ex; assertSame(pex.getCommandLine(), spec.commandLine()); assertSame(spec, pex.getCommandLine().getCommandSpec()); } } }
@Test public void testIssue402() { class AppWithEnum { @Parameters(type = Choices.class) private Choices choice; } AppWithEnum app; try { app = CommandLine.populateCommand(new AppWithEnum(), "CHOICE3"); } catch (ParameterException e) { assertEquals("<choice>", e.getArgSpec().paramLabel()); assertEquals(2, e.getArgSpec().type().getEnumConstants().length); assertEquals(Choices.CHOICE1, e.getArgSpec().type().getEnumConstants()[0]); assertEquals(Choices.CHOICE2, e.getArgSpec().type().getEnumConstants()[1]); assertEquals("CHOICE3", e.getValue()); } } @Test
@Test public void testSetInvokesMethod_FailsForGetterMethod() throws Exception { Method getX = ModelMethodBindingBean.class.getDeclaredMethod("getX"); getX.setAccessible(true); ModelMethodBindingBean bean = new ModelMethodBindingBean(); CommandSpec spec = CommandSpec.create(); MethodBinding binding = new MethodBinding(bean, getX, spec); try { binding.set(41); fail("Expect exception"); } catch (Exception ex) { ParameterException pex = (ParameterException) ex; assertSame(spec, pex.getCommandLine().getCommandSpec()); assertThat(pex.getCause().getClass().toString(), pex.getCause() instanceof IllegalArgumentException); assertEquals("wrong number of arguments", pex.getCause().getMessage()); } }
/** * If a ParameterException occurs during {@link #parseScriptArguments(CommandLine, String[])} * then this method gets called to report the problem. * The default behavior is to show the exception message using {@link #printErrorMessage(String)}, * then call {@link #printHelpMessage(CommandLine)}. * The return value becomes the return value for the Script.run which will be the exit code * if we've been called from the command line. * * @param pe The ParameterException that occurred * @param args The argument array * @return The value that Script.run should return. This implementation returns 1, subclasses may override. */ public Object handleParameterException(ParameterException pe, String[] args) { printErrorMessage(String.format("args: %s%n%s", Arrays.toString(args), pe.getMessage())); printHelpMessage(pe.getCommandLine()); return 1; }
@Test public void testPicocliExceptionFromMethod() { class App { @Option(names = "--pico") public void picocliException(String value) { throw new PicocliException("Pico!"); } } CommandLine parser = new CommandLine(new App()); try { parser.parse("--pico", "abc"); fail("Expected exception"); } catch (ParameterException ex) { assertNotNull(ex.getCause()); assertTrue(ex.getCause() instanceof PicocliException); assertEquals("Pico!", ex.getCause().getMessage()); assertEquals("PicocliException: Pico! while processing argument at or before arg[1] 'abc' in [--pico, abc]: picocli.CommandLine$PicocliException: Pico!", ex.getMessage()); } } }
@Test public void testExceptionHandlingUsesCommandLineIfAvailable() throws Exception { Method setX = ModelMethodBindingBean.class.getDeclaredMethod("setX", int.class); setX.setAccessible(true); CommandSpec spec = CommandSpec.create(); CommandLine cmd = new CommandLine(spec); spec.commandLine(cmd); MethodBinding binding = new MethodBinding(null, setX, spec); try { binding.set(41); fail("Expect exception"); } catch (Exception ex) { ParameterException pex = (ParameterException) ex; assertSame(cmd, pex.getCommandLine()); } }
@Test public void testExceptionFromMethod() { class App { @Option(names = "--jvm") public void jvmException(String value) { throw new IllegalArgumentException("Boo!"); } } CommandLine parser = new CommandLine(new App()); try { parser.parse("--jvm", "abc"); fail("Expected exception"); } catch (ParameterException ex) { assertNotNull(ex.getCause()); assertTrue(ex.getCause() instanceof IllegalArgumentException); assertEquals("Boo!", ex.getCause().getMessage()); assertEquals("Could not invoke public void picocli.CommandLineAnnotatedMethodImplTest$1App.jvmException(java.lang.String) with abc", ex.getMessage()); } }