下面列出了org.junit.jupiter.params.provider.NullSource#com.beust.jcommander.ParameterException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static PMDParameters extractParameters(PMDParameters arguments, String[] args, String progName) {
JCommander jcommander = new JCommander(arguments);
jcommander.setProgramName(progName);
try {
jcommander.parse(args);
if (arguments.isHelp()) {
jcommander.usage();
System.out.println(buildUsageText(jcommander));
setStatusCodeOrExit(ERROR_STATUS);
}
} catch (ParameterException e) {
jcommander.usage();
System.out.println(buildUsageText(jcommander));
System.err.println(e.getMessage());
setStatusCodeOrExit(ERROR_STATUS);
}
return arguments;
}
private List<Map<String, Object>> configuredTopics(Map<String, Object> cmdConfig) {
// both 'topicsFile' & 'topics' YAMLs are a list of maps
TypeReference<List<Map<String, Object>>> listOfMaps =
new TypeReference<List<Map<String, Object>>>() {};
if (cmdConfig.containsKey("topics")) {
return MAPPER.convertValue(cmdConfig.get("topics"), listOfMaps);
} else {
try {
return MAPPER.readValue(
new FileInputStream((String) cmdConfig.get("topicsFile")), listOfMaps);
} catch (IOException e) {
throw new ParameterException(
"Could not load topics from file " + cmdConfig.get("topicsFile"), e);
}
}
}
static LcovMergerFlags parseFlags(String[] args) {
LcovMergerFlags flags = new LcovMergerFlags();
JCommander jCommander = new JCommander(flags);
jCommander.setAllowParameterOverwriting(true);
jCommander.setAcceptUnknownOptions(true);
try {
jCommander.parse(args);
} catch (ParameterException e) {
throw new IllegalArgumentException("Error parsing args", e);
}
if (flags.coverageDir == null && flags.reportsFile == null) {
throw new IllegalArgumentException(
"At least one of coverage_dir or reports_file should be specified.");
}
if (flags.coverageDir != null && flags.reportsFile != null) {
logger.warning("Overriding --coverage_dir value in favor of --reports_file");
}
if (flags.outputFile == null) {
throw new IllegalArgumentException("output_file was not specified.");
}
return flags;
}
public static void main(String[] args) throws Exception {
DispatchSample sample = new DispatchSample();
JCommander jc = new JCommander(sample);
jc.setProgramName("DispatchSample");
try {
jc.parse(args);
} catch (ParameterException e) {
System.err.println(e.getMessage());
jc.usage();
System.exit(ExitCodes.OK);
}
System.exit(sample.run());
}
@Override
public String computeResults(final OperationParams params) throws Exception {
if (parameters.size() != 1) {
throw new ParameterException("Requires argument: <layer name>");
}
layerName = parameters.get(0);
final Response setLayerStyleResponse = geoserverClient.setLayerStyle(layerName, styleName);
if (setLayerStyleResponse.getStatus() == Status.OK.getStatusCode()) {
final String style = IOUtils.toString((InputStream) setLayerStyleResponse.getEntity());
return "Set style for GeoServer layer '" + layerName + ": OK" + style;
}
final String errorMessage =
"Error setting style for GeoServer layer '"
+ layerName
+ "': "
+ setLayerStyleResponse.readEntity(String.class)
+ "\nGeoServer Response Code = "
+ setLayerStyleResponse.getStatus();
return handleError(setLayerStyleResponse, errorMessage);
}
@Override
public Volume convert(String raw) {
String[] split = raw.split(":");
if (split.length != 3) {
throw new ParameterException(
getErrorString(raw, "must be in the format of 'host:container:mode'"));
}
Mode mode;
try {
mode = Mode.valueOf(split[2].toUpperCase());
} catch (IllegalArgumentException e) {
throw new ParameterException(
getErrorString(raw, "Read/Write spec must be in " + Joiner.on(", ").join(Mode.values())),
e);
}
return new Volume(split[1], split[0], mode);
}
@Test
public void testFailure_nonIntegerBillingId() {
assertThrows(
ParameterException.class,
() ->
runCommandForced(
"--name=blobio",
"--password=some_password",
"--registrar_type=REAL",
"--iana_id=8",
"--billing_id=ABC12345",
"--passcode=01234",
"[email protected].test",
"--street=\"123 Fake St\"",
"--city Fakington",
"--state MA",
"--zip 00351",
"--cc US",
"clientz"));
}
public static void main(final String[] args) throws Exception {
// Runtime parameters
final Parameters params = new Parameters();
final JCommander jc = new JCommander(params);
try {
jc.parse(args);
// Mine project
System.out.println("Processing " + FilenameUtils.getBaseName(params.arffFile) + "...");
mineAPICallSequences(params.arffFile, params.outFolder, 0.2, 0.2, params.minSupp);
} catch (final ParameterException e) {
System.out.println(e.getMessage());
jc.usage();
}
}
@Override
public List<HugeType> convert(String value) {
E.checkArgument(value != null && !value.isEmpty(),
"HugeType can't be null or empty");
String[] types = value.split(",");
if (types.length == 1 && types[0].equalsIgnoreCase("all")) {
return ALL_TYPES;
}
List<HugeType> hugeTypes = new ArrayList<>();
for (String type : types) {
try {
hugeTypes.add(HugeType.valueOf(type.toUpperCase()));
} catch (IllegalArgumentException e) {
throw new ParameterException(String.format(
"Invalid --type '%s', valid value is 'all' or " +
"combination of 'vertex,edge,vertex_label," +
"edge_label,property_key,index_label'", type));
}
}
return hugeTypes;
}
@Override
public ReportTemplate convert(String fileName) {
try {
File file = new File(fileName);
CharSource charSource = ResourceLocator.ofFile(file).getCharSource();
IniFile ini = IniFile.of(charSource);
return ReportTemplate.load(ini);
} catch (RuntimeException ex) {
if (ex.getCause() instanceof FileNotFoundException) {
throw new ParameterException(Messages.format("File not found: {}", fileName));
}
throw new ParameterException(
Messages.format("Invalid report template file: {}" +
System.lineSeparator() + "Exception: {}", fileName, ex.getMessage()));
}
}
@Override
public TimeAmount convert(String raw) {
Matcher matcher = AMOUNT_PATTERN.matcher(raw);
if (!matcher.matches()) {
throw new ParameterException(getErrorString(raw, "must be of the format 1ns, 2secs, etc."));
}
Optional<Time> unit = Stream.of(Time.values())
.filter(value -> value.toString().equals(matcher.group(2)))
.findFirst();
if (unit.isPresent()) {
return new TimeAmount(Long.parseLong(matcher.group(1)), unit.get());
} else {
throw new ParameterException(
getErrorString(raw, "one of " + ImmutableList.copyOf(Time.values())));
}
}
@Override
public void run(JCommander jc) {
setup();
if (subcommands.size() == 0) {
dumpCommands(jc);
} else if (subcommands.size() > 1) {
LOG.error("You can only see help for 1 command at a time");
dumpCommands(jc);
} else {
String subcommand = getSubcommand();
LOG.info("Detailed help for: " + subcommand);
try {
jc.usage(subcommand);
} catch (ParameterException e) {
LOG.error("ERROR: invalid command name: " + subcommand);
dumpCommands(jc);
}
}
}
public void parseArgs(String programName, String[] args, Object... others) {
JCommander commander = new JCommander();
commander.addObject(this);
for (Object other : others)
commander.addObject(other);
commander.setProgramName(programName);
try {
commander.parse(args);
} catch (ParameterException ex) {
commander.usage();
exitWithError(ex.getMessage(), 1);
}
if (help) {
commander.usage();
exit(0);
}
}
@Override
public String computeResults(final OperationParams params) {
if (parameters.size() < 1) {
throw new ParameterException("Must specify store name");
}
final String inputStoreName = parameters.get(0);
// Attempt to load store.
final File configFile = getGeoWaveConfigFile(params);
// Attempt to load input store.
final StoreLoader inputStoreLoader = new StoreLoader(inputStoreName);
if (!inputStoreLoader.loadFromConfig(configFile, params.getConsole())) {
throw new ParameterException("Cannot find store name: " + inputStoreLoader.getStoreName());
}
inputStoreOptions = inputStoreLoader.getDataStorePlugin();
final String[] typeNames = inputStoreOptions.createInternalAdapterStore().getTypeNames();
final StringBuffer buffer = new StringBuffer();
for (final String typeName : typeNames) {
buffer.append(typeName).append(' ');
}
return buffer.toString();
}
public static void main(String[] args) throws Exception {
ResizeClusterSample sample = new ResizeClusterSample();
JCommander jc = new JCommander(sample);
jc.setProgramName("ResizeClusterSample");
try {
jc.parse(args);
} catch (ParameterException e) {
System.err.println(e.getMessage());
jc.usage();
System.exit(ExitCodes.PARAMETER_EXCEPTION);
}
System.exit(sample.run());
}
@Override
public Properties convert(String value) {
int indexOfSeparator = value.indexOf(SEPARATOR);
if (indexOfSeparator < 0) {
throw new ParameterException(
"Property name must be separated with an = sign from it value: name=value.");
}
String propertyName = value.substring(0, indexOfSeparator);
String propertyValue = value.substring(indexOfSeparator + 1);
Properties properties = new Properties();
properties.put(propertyName, propertyValue);
return properties;
}
public static void main(String[] args) throws Exception {
CommandMaster commandMaster = new CommandMaster();
CommandSlave commandSlave = new CommandSlave();
JCommander jCommander = JCommander.newBuilder()
.addCommand(MasterSystem.MASTER_ROLE, commandMaster)
.addCommand(SlaveSystem.SLAVE_ROLE, commandSlave)
.build();
try {
jCommander.parse(args);
if (jCommander.getParsedCommand() == null)
throw new ParameterException("No command given.");
switch (jCommander.getParsedCommand()) {
case MasterSystem.MASTER_ROLE:
ConfigurationSingleton.get().update(commandMaster);
MasterSystem.start();
break;
case SlaveSystem.SLAVE_ROLE:
ConfigurationSingleton.get().update(commandSlave);
SlaveSystem.start();
break;
default:
throw new AssertionError();
}
} catch (ParameterException e) {
System.out.printf("Could not parse args: %s\n", e.getMessage());
if (jCommander.getParsedCommand() == null) {
jCommander.usage();
} else {
jCommander.usage(jCommander.getParsedCommand());
}
System.exit(1);
}
}
@Override
public Map<String, Object> convert(String file) {
try {
return convert(new FileInputStream(file));
} catch (IOException e) {
throw new ParameterException("Could not load config from file " + file, e);
}
}
private DataStorePluginOptions getStorePluginOptions(final OperationParams params) {
final File configFile = (File) params.getContext().get(ConfigOptions.PROPERTIES_FILE_CONTEXT);
final StoreLoader inputStoreLoader = new StoreLoader("memorystore");
if (!inputStoreLoader.loadFromConfig(configFile, params.getConsole())) {
throw new ParameterException("Cannot find store name: " + inputStoreLoader.getStoreName());
}
return inputStoreLoader.getDataStorePlugin();
}
@Override
public void validatePluginOptions(final Properties properties, final Console console)
throws ParameterException {
// Set the directory to be absolute
dir = new File(dir).getAbsolutePath();
super.validatePluginOptions(properties, console);
}
@Override
String process(final String value) {
if ((value != null) && !"".equals(value.trim())) {
if (value.indexOf(SEPARATOR) != -1) {
String propertyFilePath = value.split(SEPARATOR)[0];
String propertyKey = value.split(SEPARATOR)[1];
if ((propertyFilePath != null) && !"".equals(propertyFilePath.trim())) {
propertyFilePath = propertyFilePath.trim();
final File propsFile = new File(propertyFilePath);
if ((propsFile != null) && propsFile.exists()) {
final Properties properties = PropertiesUtils.fromFile(propsFile);
if ((propertyKey != null) && !"".equals(propertyKey.trim())) {
propertyKey = propertyKey.trim();
}
if ((properties != null) && properties.containsKey(propertyKey)) {
return properties.getProperty(propertyKey);
}
} else {
try {
throw new ParameterException(
new FileNotFoundException(
propsFile != null
? "Properties file not found at path: " + propsFile.getCanonicalPath()
: "No properties file specified"));
} catch (final IOException e) {
throw new ParameterException(e);
}
}
} else {
throw new ParameterException("No properties file path specified");
}
} else {
throw new ParameterException(
"Property File values are expected in input format <property file path>::<property key>");
}
} else {
throw new ParameterException(new Exception("No properties file specified"));
}
return value;
}
CommandLine(String progName, String[] args) throws ParameterException {
this.jc = new JCommander(this, args); // Parses args and uses them to initialize *this*.
jc.setProgramName(progName); // Displayed in the usage information.
// Set the ordering of of parameters in the usage information.
jc.setParameterDescriptionComparator(new ParameterDescriptionComparator());
}
@Override
public String computeResults(final OperationParams params) throws Exception {
final File propFile = getGeoWaveConfigFile(params);
final Properties existingProps = ConfigOptions.loadProperties(propFile);
// Ensure that a name is chosen.
if (parameters.size() != 1) {
throw new ParameterException("Must specify store name");
}
// Make sure we're not already in the index.
final DataStorePluginOptions existingOptions = new DataStorePluginOptions();
if (existingOptions.load(existingProps, getNamespace())) {
throw new DuplicateEntryException("That store already exists: " + getPluginName());
}
// Save the store options.
pluginOptions.save(existingProps, getNamespace());
// Make default?
if (Boolean.TRUE.equals(makeDefault)) {
existingProps.setProperty(DataStorePluginOptions.DEFAULT_PROPERTY_NAMESPACE, getPluginName());
}
// Write properties file
ConfigOptions.writeProperties(propFile, existingProps, params.getConsole());
final StringBuilder builder = new StringBuilder();
for (final Object key : existingProps.keySet()) {
final String[] split = key.toString().split("\\.");
if (split.length > 1) {
if (split[1].equals(parameters.get(0))) {
builder.append(key.toString() + "=" + existingProps.getProperty(key.toString()) + "\n");
}
}
}
return builder.toString();
}
@Test
public void parseWrongJobsNumeric() {
thrown.expect(ParameterException.class);
thrown.expectMessage("Parameter -j should be a positive integer (found -345)");
Clean.Options args = new Clean.Options();
JCommander jc = JCommander.newBuilder().addObject(args).build();
jc.parse(new String[] { "-j", "-345" } );
}
public static void main(String[] args) {
MasterCommand masterCommand = new MasterCommand();
SlaveCommand slaveCommand = new SlaveCommand();
JCommander jCommander = JCommander.newBuilder()
.addCommand(OctopusMaster.MASTER_ROLE, masterCommand)
.addCommand(OctopusSlave.SLAVE_ROLE, slaveCommand)
.build();
try {
jCommander.parse(args);
if (jCommander.getParsedCommand() == null) {
throw new ParameterException("No command given.");
}
switch (jCommander.getParsedCommand()) {
case OctopusMaster.MASTER_ROLE:
OctopusMaster.start(ACTOR_SYSTEM_NAME, masterCommand.workers, masterCommand.host, masterCommand.port);
break;
case OctopusSlave.SLAVE_ROLE:
OctopusSlave.start(ACTOR_SYSTEM_NAME, slaveCommand.workers, slaveCommand.host, slaveCommand.port, slaveCommand.masterhost, slaveCommand.masterport);
break;
default:
throw new AssertionError();
}
} catch (ParameterException e) {
System.out.printf("Could not parse args: %s\n", e.getMessage());
if (jCommander.getParsedCommand() == null) {
jCommander.usage();
} else {
jCommander.usage(jCommander.getParsedCommand());
}
System.exit(1);
}
}
@ParameterizedTest
@ValueSource(strings = {"", "JSON"})
public void testValidateOutputFormat_withInvalidFormat(String format) {
assertThrows(ParameterException.class, () -> {
new OutputFormatValidator().validate(null, format);
});
}
public Integer convert(String value) {
try {
return Integer.parseInt(value);
} catch(NumberFormatException ex) {
throw new ParameterException(getErrorString(value, "an integer"));
}
}
@Override
public void validate(String name, String value) {
if (value == null || !FORMATS.contains(value)) {
throw new ParameterException(
String.format("Invalid output format: value:%s: supported formats:%s", value, FORMATS));
}
}
@Test
public void testFailure_missingDomainName() {
assertThrows(
ParameterException.class,
() ->
runCommandForced(
"--client=NewRegistrar",
"--superuser",
"--reason=anchor-tenant-test",
"--contact=jd1234",
"foo"));
}
public static void main(String... args) throws Exception {
TrainModel instance = new TrainModel();
JCommander jcmdr = new JCommander(instance);
try {
jcmdr.parse(args);
} catch (ParameterException e) {
System.out.println(e);
jcmdr.usage();
System.exit(1);
}
instance.train();
}