@JsonCreator private static @Nonnull AllowedValue create( @JsonProperty(PROP_NAME) String name, @JsonProperty(PROP_DESCRIPTION) String description) { checkArgument(name != null, String.format("%s is required", PROP_NAME)); return new AllowedValue(name, description); }
/** * This method calls {@link Client#validateType(JsonNode, Variable)} to check that the contents * encoded in {@code value} match the requirement specified in {@code variable}. Also, this method * validates the input {@code value} is allowed according to {@link Variable#_values values} * specified in {@code variable}. * * @throws BatfishException if the content type encoded in input {@code value} does not satisfy * the type requirements specified in {@code variable}, or the input {@code value} is not an * allowed value for {@code variable}. */ static void validateNode(JsonNode value, Variable variable, String parameterName) throws BatfishException { try { validateType(value, variable); } catch (BatfishException e) { String errorMessage = String.format("Invalid value for parameter %s: %s", parameterName, value); throw new BatfishException(errorMessage, e); } if (!variable.getValues().isEmpty() && variable.getValues().stream() .noneMatch(allowedValue -> allowedValue.getName().equals(value.asText()))) { throw new BatfishException( String.format( "Invalid value: %s, allowed values are: %s", value.asText(), variable.getValues())); } }
@JsonProperty(BfConsts.PROP_ALLOWED_VALUES) @Deprecated public void setAllowedValues(SortedSet<String> allowedValues) { if (_values.isEmpty()) { _values = allowedValues.stream() .map(v -> new AllowedValue(v, null)) .collect(ImmutableList.toImmutableList()); } }
@Test public void testValidateValidNode() throws IOException { String parameterName = "boolean"; JsonNode invalidNode = _mapper.readTree("false"); Variable variable = new Variable(); variable.setType(BOOLEAN); List<AllowedValue> allowedValues = ImmutableList.of(new AllowedValue("false", "description")); variable.setValues(allowedValues); Client.validateNode(invalidNode, variable, parameterName); }
@Test public void testValidateNodeNotAllowedValue() throws IOException { String parameterName = "boolean"; JsonNode invalidNode = _mapper.readTree("false"); Variable variable = new Variable(); variable.setType(BOOLEAN); List<AllowedValue> allowedValues = ImmutableList.of(new AllowedValue("true", "description")); variable.setValues(allowedValues); _thrown.expect(BatfishException.class); _thrown.expectMessage( String.format("Invalid value: false, allowed values are: %s", allowedValues)); Client.validateNode(invalidNode, variable, parameterName); }