picocli.CommandLine.ParameterException Java Examples
The following examples show how to use
picocli.CommandLine.ParameterException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HopRun.java From hop with Apache License 2.0 | 6 votes |
/** * Configure the variables and parameters in the given configuration on the given variable space and named parameters * * @param cmd * @param configuration * @param namedParams */ private void configureParametersAndVariables( CommandLine cmd, IExecutionConfiguration configuration, IVariables variables, INamedParams namedParams ) { // Copy variables over to the pipeline or workflow metadata // variables.injectVariables( configuration.getVariablesMap() ); // Set the parameter values // for ( String key : configuration.getParametersMap().keySet() ) { String value = configuration.getParametersMap().get( key ); try { namedParams.setParameterValue( key, value ); } catch ( UnknownParamException e ) { throw new ParameterException( cmd, "Unable to set parameter '" + key + "'", e ); } } }
Example #2
Source File: PopulateHelpRequestedMain.java From picocli with Apache License 2.0 | 6 votes |
public static void main(String[] args) { // Create a new Options class, which holds our options. Options options = new Options(); try { // Populate the created class from the command line arguments. CommandLine.populateCommand(options, args); } catch (ParameterException e) { // The given command line arguments are invalid, for example there // are options specified which do not exist or one of the options // is malformed (missing a value, for example). System.out.println(e.getMessage()); CommandLine.usage(options, System.out); return; } // Print the state. if (options.isHelpRequested()) { CommandLine.usage(options, System.out); } else { System.out.println("No help requested, application can continue."); } }
Example #3
Source File: BlocksSubCommand.java From besu with Apache License 2.0 | 6 votes |
@Override public void run() { parentCommand.parentCommand.configureLogging(false); LOG.info("Export {} block data to file {}", format, blocksExportFile.toPath()); checkCommand(this, startBlock, endBlock); final Optional<MetricsService> metricsService = initMetrics(parentCommand); final BesuController controller = createBesuController(); try { if (format == BlockExportFormat.RLP) { exportRlpFormat(controller); } else { throw new ParameterException( spec.commandLine(), "Unsupported format: " + format.toString()); } } catch (final IOException e) { throw new ExecutionException( spec.commandLine(), "An error occurred while exporting blocks.", e); } finally { metricsService.ifPresent(MetricsService::stop); } }
Example #4
Source File: ModelMethodBindingTest.java From picocli with Apache License 2.0 | 6 votes |
@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(new ObjectScope(null), setX, spec); try { binding.set(41); fail("Expect exception"); } catch (Exception ex) { ParameterException pex = (ParameterException) ex; assertSame(cmd, pex.getCommandLine()); } }
Example #5
Source File: TomlConfigFileDefaultProvider.java From besu with Apache License 2.0 | 6 votes |
private void checkUnknownOptions(final TomlParseResult result) { final CommandSpec commandSpec = commandLine.getCommandSpec(); final Set<String> unknownOptionsList = result.keySet().stream() .filter(option -> !commandSpec.optionsMap().containsKey("--" + option)) .collect(Collectors.toSet()); if (!unknownOptionsList.isEmpty()) { final String options = unknownOptionsList.size() > 1 ? "options" : "option"; final String csvUnknownOptions = unknownOptionsList.stream().collect(Collectors.joining(", ")); throw new ParameterException( commandLine, String.format("Unknown %s in TOML configuration file: %s", options, csvUnknownOptions)); } }
Example #6
Source File: BesuCommand.java From besu with Apache License 2.0 | 6 votes |
@Option( names = {"--bootnodes"}, paramLabel = "<enode://id@host:port>", description = "Comma separated enode URLs for P2P discovery bootstrap. " + "Default is a predefined list.", split = ",", arity = "0..*") void setBootnodes(final List<String> values) { try { bootNodes = values.stream() .filter(value -> !value.isEmpty()) .map(EnodeURL::fromString) .collect(Collectors.toList()); DiscoveryConfiguration.assertValidBootnodes(bootNodes); } catch (final IllegalArgumentException e) { throw new ParameterException(commandLine, e.getMessage()); } }
Example #7
Source File: BesuCommand.java From besu with Apache License 2.0 | 6 votes |
@Option( names = {"--banned-node-ids", "--banned-node-id"}, paramLabel = MANDATORY_NODE_ID_FORMAT_HELP, description = "A list of node IDs to ban from the P2P network.", split = ",", arity = "1..*") void setBannedNodeIds(final List<String> values) { try { bannedNodeIds = values.stream() .filter(value -> !value.isEmpty()) .map(EnodeURL::parseNodeId) .collect(Collectors.toList()); } catch (final IllegalArgumentException e) { throw new ParameterException( commandLine, "Invalid ids supplied to '--banned-node-ids'. " + e.getMessage()); } }
Example #8
Source File: BesuCommand.java From besu with Apache License 2.0 | 6 votes |
@Override public void run() { try { configureLogging(true); configureNativeLibs(); logger.info("Starting Besu version: {}", BesuInfo.nodeName(identityString)); // Need to create vertx after cmdline has been parsed, such that metricsSystem is configurable vertx = createVertx(createVertxOptions(metricsSystem.get())); final BesuCommand controller = validateOptions().configure().controller(); preSynchronizationTaskRunner.runTasks(controller.besuController); controller.startPlugins().startSynchronization(); } catch (final Exception e) { throw new ParameterException(this.commandLine, e.getMessage(), e); } }
Example #9
Source File: RLPSubCommand.java From besu with Apache License 2.0 | 6 votes |
/** * write the encoded result to stdout or a file if the option is specified * * @param rlpEncodedOutput the RLP output to write to file or stdout */ private void writeOutput(final Bytes rlpEncodedOutput) { if (rlpTargetFile != null) { final Path targetPath = rlpTargetFile.toPath(); try (final BufferedWriter fileWriter = Files.newBufferedWriter(targetPath, UTF_8)) { fileWriter.write(rlpEncodedOutput.toString()); } catch (final IOException e) { throw new ParameterException( spec.commandLine(), "An error occurred while trying to write the RLP string. " + e.getMessage()); } } else { parentCommand.out.println(rlpEncodedOutput); } }
Example #10
Source File: Extract.java From DataDefender with Apache License 2.0 | 6 votes |
@Parameters(paramLabel = "columns", description = "Generate data for the specified table.columName(s)") public void setTableColumns(List<String> tableColumns) { for (String tableColumn : tableColumns) { int loc = tableColumn.indexOf("."); if (loc < 1 || loc >= tableColumn.length() - 1) { throw new ParameterException( spec.commandLine(), String.format( "Columns must be specified in the form [table].[columnName], found: %s", tableColumn ) ); } } this.tableColumns = tableColumns; }
Example #11
Source File: EthSignerBaseCommand.java From ethsigner with Apache License 2.0 | 6 votes |
@SuppressWarnings("FieldMayBeFinal") @Option( names = {"--downstream-http-path"}, description = "The path to which received requests are forwarded (default: ${DEFAULT-VALUE})", defaultValue = "/", paramLabel = MANDATORY_PATH_FORMAT_HELP, arity = "1") public void setDownstreamHttpPath(final String path) { try { final URI uri = new URI(path); if (!uri.getPath().equals(path)) { throw new ParameterException( spec.commandLine(), "Illegal characters detected in --downstream-http-path"); } } catch (final URISyntaxException e) { throw new ParameterException( spec.commandLine(), "Illegal characters detected in --downstream-http-path"); } this.downstreamHttpPath = path; }
Example #12
Source File: ExampleInterface.java From picocli with Apache License 2.0 | 6 votes |
private static int execute(String[] args) { final CommandLine cmd = new CommandLine(ExampleInterface.class); cmd.setExecutionStrategy(new IExecutionStrategy() { public int execute(ParseResult parseResult) throws ExecutionException, ParameterException { Integer result = CommandLine.executeHelpRequest(parseResult); if (result != null) { return result; } // invoke the business logic ExampleInterface exampleInterface = cmd.getCommand(); businessLogic(exampleInterface); return cmd.getCommandSpec().exitCodeOnSuccess(); } }); return cmd.execute(args); }
Example #13
Source File: ModelMethodBindingTest.java From picocli with Apache License 2.0 | 6 votes |
@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(new ObjectScope(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()); } }
Example #14
Source File: OptionMethodImplTest.java From picocli with Apache License 2.0 | 6 votes |
@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.parseArgs("--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.OptionMethodImplTest$1App.jvmException(java.lang.String) with abc (java.lang.IllegalArgumentException: Boo!)", ex.getMessage()); } }
Example #15
Source File: YamlConfigFileDefaultProvider.java From teku with Apache License 2.0 | 6 votes |
private void checkUnknownOptions(final Map<String, Object> result) { final CommandSpec commandSpec = commandLine.getCommandSpec(); final Set<String> unknownOptionsList = result.keySet().stream() .filter(option -> !commandSpec.optionsMap().containsKey("--" + option)) .collect(Collectors.toCollection(TreeSet::new)); if (!unknownOptionsList.isEmpty()) { final String options = unknownOptionsList.size() > 1 ? "options" : "option"; final String csvUnknownOptions = String.join(", ", unknownOptionsList); throw new ParameterException( commandLine, String.format("Unknown %s in yaml configuration file: %s", options, csvUnknownOptions)); } }
Example #16
Source File: OptionMethodImplTest.java From picocli with Apache License 2.0 | 6 votes |
@Test public void testParameterExceptionFromMethod() { class App { @Option(names = "--param") public void paramException(String value) { throw new ParameterException(new CommandLine(new App()), "Param!"); } } CommandLine parser = new CommandLine(new App()); try { parser.parseArgs("--param", "abc"); fail("Expected exception"); } catch (ParameterException ex) { assertNull(ex.getCause()); assertEquals("Param!", ex.getMessage()); } }
Example #17
Source File: DepositRegisterCommand.java From teku with Apache License 2.0 | 6 votes |
private BLSKeyPair getValidatorKey() { if (validatorKeyOptions.validatorKey != null) { return privateKeyToKeyPair(validatorKeyOptions.validatorKey); } try { final String keystorePassword = readPassword(); final KeyStoreData keyStoreData = KeyStoreLoader.loadFromFile( validatorKeyOptions.validatorKeyStoreOptions.validatorKeystoreFile.toPath()); final Bytes privateKey = KeyStore.decrypt(keystorePassword, keyStoreData); return privateKeyToKeyPair(privateKey); } catch (final KeyStoreValidationException e) { throw new ParameterException(spec.commandLine(), e.getMessage()); } }
Example #18
Source File: GenerateAction.java From teku with Apache License 2.0 | 6 votes |
private String askForPassword(final String option) { if (!consoleAdapter.isConsoleAvailable()) { throw new ParameterException( commandSpec.commandLine(), "Cannot read password from console: Console not available"); } final char[] firstInput = consoleAdapter.readPassword("Enter password for %s:", option); final char[] reconfirmedInput = consoleAdapter.readPassword("Re-Enter password for %s:", option); if (firstInput == null || reconfirmedInput == null) { throw new ParameterException(commandSpec.commandLine(), "Error: Password is blank"); } if (Arrays.equals(firstInput, reconfirmedInput)) { final String password = new String(firstInput); if (password.isBlank()) { throw new ParameterException(commandSpec.commandLine(), "Error: Password is blank"); } return password; } throw new ParameterException(commandSpec.commandLine(), "Error: Password mismatched"); }
Example #19
Source File: OptionMethodImplTest.java From picocli with Apache License 2.0 | 6 votes |
@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.parseArgs("--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()); } }
Example #20
Source File: User.java From picocli with Apache License 2.0 | 6 votes |
private void validate() { System.out.println(spec.commandLine().getParseResult().originalArgs()); System.out.println(this); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<User>> violations = validator.validate(this); if (!violations.isEmpty()) { String errorMsg = ""; for (ConstraintViolation<User> violation : violations) { errorMsg += "ERROR: " + violation.getMessage() + "\n"; } throw new ParameterException(spec.commandLine(), errorMsg); } }
Example #21
Source File: TomlConfigFileDefaultProviderTest.java From besu with Apache License 2.0 | 6 votes |
@Test public void invalidConfigContentMustThrow() throws IOException { exceptionRule.expect(ParameterException.class); exceptionRule.expectMessage( "Invalid TOML configuration: Unexpected '=', expected ', \", ''', " + "\"\"\", a number, a boolean, a date/time, an array, or a table (line 1, column 19)"); final File tempConfigFile = temp.newFile("config.toml"); try (final BufferedWriter fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) { fileWriter.write("an-invalid-syntax=======...."); fileWriter.flush(); final TomlConfigFileDefaultProvider providerUnderTest = new TomlConfigFileDefaultProvider(mockCommandLine, tempConfigFile); providerUnderTest.defaultValue(OptionSpec.builder("an-option").type(String.class).build()); } }
Example #22
Source File: TomlConfigFileDefaultProviderTest.java From besu with Apache License 2.0 | 6 votes |
@Test public void unknownOptionMustThrow() throws IOException { exceptionRule.expect(ParameterException.class); exceptionRule.expectMessage("Unknown option in TOML configuration file: invalid_option"); when(mockCommandLine.getCommandSpec()).thenReturn(mockCommandSpec); Map<String, OptionSpec> validOptionsMap = new HashMap<>(); when(mockCommandSpec.optionsMap()).thenReturn(validOptionsMap); final File tempConfigFile = temp.newFile("config.toml"); try (final BufferedWriter fileWriter = Files.newBufferedWriter(tempConfigFile.toPath(), UTF_8)) { fileWriter.write("invalid_option=true"); fileWriter.flush(); final TomlConfigFileDefaultProvider providerUnderTest = new TomlConfigFileDefaultProvider(mockCommandLine, tempConfigFile); providerUnderTest.defaultValue(OptionSpec.builder("an-option").type(String.class).build()); } }
Example #23
Source File: TypeConversionTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testShortFieldsAreDecimal() { try { CommandLine.populateCommand(new SupportedTypes(), "-short", "0xFF", "-Short", "0x6FFE"); fail("Should fail on hex input"); } catch (CommandLine.ParameterException expected) { assertEquals("Invalid value for option '-short': '0xFF' is not a short", expected.getMessage()); } }
Example #24
Source File: TypeConversionTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testTimeFormatHHmmssSSSSInvalidError() throws ParseException { try { CommandLine.populateCommand(new SupportedTypes(), "-Time", "23:59:58.1234"); fail("Invalid format was accepted"); } catch (CommandLine.ParameterException expected) { assertEquals("Invalid value for option '-Time': '23:59:58.1234' is not a HH:mm[:ss[.SSS]] time", expected.getMessage()); } }
Example #25
Source File: TypeConversionTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testByteFieldsAreDecimal() { try { CommandLine.populateCommand(new SupportedTypes(), "-byte", "0x1F", "-Byte", "0x0F"); fail("Should fail on hex input"); } catch (CommandLine.ParameterException expected) { assertEquals("Invalid value for option '-byte': '0x1F' is not a byte", expected.getMessage()); } }
Example #26
Source File: Example.java From picocli with Apache License 2.0 | 5 votes |
@Parameters(index = "1..*", description = "Positional parameters from index 1..* are captured in this annotated @Parameters method. It can be used to validate the values. Any specified value must be an existing file.") public void setOtherFiles(List<File> otherFiles) { for (File f : otherFiles) { if (!f.exists()) { throw new ParameterException(spec.commandLine(), "File " + f.getAbsolutePath() + " must exist"); } } this.otherFiles = otherFiles; }
Example #27
Source File: Example.java From picocli with Apache License 2.0 | 5 votes |
@Option(names = "--minimum", description = "This option demonstrates an @Option-annotated method. It can be used to validate the option value.") public void setMinimum(int min) { if (min < 0) { throw new ParameterException(spec.commandLine(), "Minimum must be a positive integer"); } minimum = min; }
Example #28
Source File: GroovyMain.java From groovy with Apache License 2.0 | 5 votes |
static void processArgs(String[] args, final PrintStream out, final PrintStream err) { GroovyCommand groovyCommand = new GroovyCommand(); CommandLine parser = new CommandLine(groovyCommand) .setOut(new PrintWriter(out)) .setErr(new PrintWriter(err)) .setUnmatchedArgumentsAllowed(true) .setStopAtUnmatched(true); try { ParseResult result = parser.parseArgs(args); if (CommandLine.printHelpIfRequested(result)) { return; } // TODO: pass printstream(s) down through process if (!groovyCommand.process(parser)) { // If we fail, then exit with an error so scripting frameworks can catch it. System.exit(1); } } catch (ParameterException ex) { // command line arguments could not be parsed err.println(ex.getMessage()); ex.getCommandLine().usage(err); } catch (IOException ioe) { err.println("error: " + ioe.getMessage()); } }
Example #29
Source File: TypeConversionTest.java From picocli with Apache License 2.0 | 5 votes |
@Test public void testTimeFormatHHmmssSSSInvalidError() throws ParseException { try { CommandLine.populateCommand(new SupportedTypes(), "-Time", "23:59:58;123"); fail("Invalid format was accepted"); } catch (CommandLine.ParameterException expected) { assertEquals("Invalid value for option '-Time': '23:59:58;123' is not a HH:mm[:ss[.SSS]] time", expected.getMessage()); } }
Example #30
Source File: PopulatePositionalParametersMain.java From picocli with Apache License 2.0 | 5 votes |
public static void main(String[] args) { // Create a new Options class, which holds our options. Options options = new Options(); try { // Populate the created class from the command line arguments. CommandLine.populateCommand(options, args); } catch (ParameterException e) { // The given command line arguments are invalid, for example there // are options specified which do not exist or one of the options // is malformed (missing a value, for example). System.out.println(e.getMessage()); CommandLine.usage(options, System.out); return; } // Print the state. System.out.println("Arguments:"); System.out.print(" "); for (String arg : args) { System.out.print("\"" + arg + "\" "); } System.out.println(); System.out.println(); System.out.println("Options:"); System.out.println(" name: " + options.getName()); if (options.getProperties() != null) { System.out.print(" properties: "); for (String property : options.getProperties()) { System.out.print("\"" + property + "\" "); } System.out.println(); } else { System.out.println(" properties:"); } }