下面列出了怎么用javax.validation.ValidationException的API类实例代码及写法,或者点击链接到github查看源代码。
@SuppressWarnings("unused") // called by reflection
static void activateBeanValidation(final Set<BapiInterceptor> bapiInterceptors,
final SessionManagerConfig sessionManagerConfig) {
try {
ValidatorFactory factory = validatorFactoryFactory.buildValidatorFactory();
bapiInterceptors.add(new BeanValidationInterceptor(factory));
} catch (ValidationException e) {
ValidationMode validationMode = sessionManagerConfig.getValidationMode();
if (validationMode == ValidationMode.AUTO) {
LOGGER.warn("Bean Validation will not be used: Bean Validation API is in the classpath, " +
"but default ValidatorFactory can not be built. " +
"ValidationMode is AUTO, so startup will be continued.", e);
} else {
throw new HibersapException("Unable to build the default ValidatorFactory, ValidationMode is " +
validationMode, e);
}
}
}
@Override
public ResponseEntity<MgmtAction> updateAction(@PathVariable("targetId") final String targetId,
@PathVariable("actionId") final Long actionId, @RequestBody final MgmtActionRequestBodyPut actionUpdate) {
Action action = deploymentManagement.findAction(actionId)
.orElseThrow(() -> new EntityNotFoundException(Action.class, actionId));
if (!action.getTarget().getControllerId().equals(targetId)) {
LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId);
return ResponseEntity.notFound().build();
}
if (MgmtActionType.FORCED != actionUpdate.getActionType()) {
throw new ValidationException("Resource supports only switch to FORCED.");
}
action = deploymentManagement.forceTargetAction(actionId);
return ResponseEntity.ok(MgmtTargetMapper.toResponseWithLinks(targetId, action));
}
@Override
public Response toResponse(ValidationException exception) {
logException(exception);
Response.ResponseBuilder responseBuilder;
if (exception instanceof ConstraintViolationException) {
responseBuilder = Response.status(Response.Status.BAD_REQUEST);
} else {
responseBuilder = Response.serverError();
Monitors.error("error", "error");
}
Map<String, Object> entityMap = new HashMap<>();
entityMap.put("instance", host);
responseBuilder.type(MediaType.APPLICATION_JSON_TYPE);
responseBuilder.entity(toErrorResponse(exception));
return responseBuilder.build();
}
@Test
public void testClear() {
Treatment t1, t2;
try {
t1 = new Treatment("control");
t2 = new Treatment("other");
} catch (ValidationException e) {
// this should never happen
t1 = null;
t2 = null;
}
final Allocations allocations = new Allocations(Lists.newArrayList(
new Allocation(t1, 0, 5),
new Allocation(t2, 5, 5)
));
assertEquals(2, allocations.getAllocations().size());
assertEquals(10, allocations.getSize());
allocations.clear();
assertEquals(0, allocations.getAllocations().size());
assertEquals(0, allocations.getSize());
}
@Test
public void testClearTreatments() throws ValidationException {
final Experiment experiment =
new Experiment(null, "foo")
.addTreatment("bar")
.allocate("bar", 10)
.addOverride("override", "bar", "true");
assertEquals(1, experiment.getTreatments().size());
assertEquals(1, experiment.getAllocations().size());
assertEquals(1, experiment.getOverrides().size());
experiment.clearTreatments();
assertEquals(0, experiment.getTreatments().size());
assertEquals(0, experiment.getAllocations().size());
assertEquals(0, experiment.getOverrides().size());
}
@Test
public void testCopyOf() throws ValidationException {
assertNull(Experiment.copyOf(null));
final Experiment original =
new Experiment(null, "experiment")
.activate()
.addTreatment("foo")
.addOverride("override", "foo", "true")
.allocate("foo", 10);
final Experiment copy = Experiment.copyOf(original);
assertFalse(original == copy);
assertFalse(original.getTreatments().get(0) == copy.getTreatments().get(0));
assertFalse(original.getAllocations().get(0) == copy.getAllocations().get(0));
assertFalse(original.getOverrides().get(0) == copy.getOverrides().get(0));
assertTrue(copy.getAllocations().get(0).getTreatment() == copy.getTreatments().get(0));
assertTrue(copy.getOverrides().get(0).getTreatment() == copy.getTreatments().get(0));
}
@Override
public void setup(DAGSetupPlugin.Context context)
{
this.dag = context.getDAG();
try {
this.path = context.getConfiguration().get("propertyVisitor.Path");
Properties properties = new Properties();
properties.load(this.getClass().getResourceAsStream(path));
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
propertyMap.put(entry.getKey().toString(), entry.getValue().toString());
}
} catch (IOException ex) {
throw new ValidationException("Not able to load input file " + path);
}
context.register(PRE_VALIDATE_DAG, this);
}
@Test
public void testSetOperatorProperty()
{
GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
OperatorMeta o1Meta = dag.getMeta(o1);
TestPlanContext ctx = new TestPlanContext();
dag.setAttribute(OperatorContext.STORAGE_AGENT, ctx);
PhysicalPlan plan = new PhysicalPlan(dag, ctx);
ctx.deploy.clear();
ctx.undeploy.clear();
PlanModifier pm = new PlanModifier(plan);
try {
pm.setOperatorProperty(o1Meta.getName(), "myStringProperty", "propertyValue");
Assert.fail("validation error exepected");
} catch (javax.validation.ValidationException e) {
Assert.assertTrue(e.getMessage().contains(o1Meta.toString()));
}
GenericTestOperator newOperator = new GenericTestOperator();
pm.addOperator("newOperator", newOperator);
pm.setOperatorProperty("newOperator", "myStringProperty", "propertyValue");
Assert.assertEquals("", "propertyValue", newOperator.getMyStringProperty());
}
@Nullable
public Object getTypedValue(@Nullable InputSpec inputSpec) {
if (inputSpec != null) {
try {
return inputSpec.convertToObject(getValues());
} catch (ValidationException e) {
String displayValue;
if (type.equals(FieldSpec.SECRET))
displayValue = SecretInput.MASK;
else
displayValue = "" + getValues();
logger.error("Error converting field value (field: {}, value: {}, error: {})",
getName(), displayValue, e.getMessage());
return null;
}
} else {
return null;
}
}
protected void validateUnique(@Nullable final CapabilityIdentity id, final Map<String, String> properties)
{
CapabilityReferenceFilter filter = duplicatesFilter(id, properties);
log.trace("Validating that unique capability of type {} and properties {}", type(), filter.getProperties());
Collection<? extends CapabilityReference> references = capabilityRegistry.get().get(filter);
if (!references.isEmpty()) {
StringBuilder message = new StringBuilder().append("Only one capability of type '").append(name()).append("'");
for (Entry<String, String> entry : filter.getProperties().entrySet()) {
message.append(", ").append(propertyName(entry.getKey()).toLowerCase()).append(" '").append(entry.getValue())
.append("'");
}
message.append(" can be created");
throw new ValidationException(message.toString());
}
}
@Override
public Response toResponse(ValidationException exception) {
if (exception instanceof ConstraintDefinitionException) {
return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
}
if (exception instanceof ConstraintDeclarationException) {
return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
}
if (exception instanceof GroupDefinitionException) {
return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
}
if (exception instanceof ResteasyViolationException) {
ResteasyViolationException resteasyViolationException = ResteasyViolationException.class.cast(exception);
Exception e = resteasyViolationException.getException();
if (e != null) {
return buildResponse(unwrapException(e), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
} else if (resteasyViolationException.getReturnValueViolations().size() == 0) {
return buildViolationReportResponse(resteasyViolationException, Status.BAD_REQUEST);
} else {
return buildViolationReportResponse(resteasyViolationException, Status.INTERNAL_SERVER_ERROR);
}
}
return buildResponse(unwrapException(exception), MediaType.TEXT_PLAIN, Status.INTERNAL_SERVER_ERROR);
}
/**
* Add stream to logical plan. If a stream with same name and source already
* exists, the new downstream operator will be attached to it.
*
* @param streamName
* @param sourceOperName
* @param sourcePortName
* @param targetOperName
* @param targetPortName
*/
public void addStream(String streamName, String sourceOperName, String sourcePortName, String targetOperName, String targetPortName)
{
OperatorMeta om = logicalPlan.getOperatorMeta(sourceOperName);
if (om == null) {
throw new ValidationException("Invalid operator name " + sourceOperName);
}
Operators.PortMappingDescriptor portMap = new Operators.PortMappingDescriptor();
Operators.describe(om.getOperator(), portMap);
PortContextPair<OutputPort<?>> sourcePort = portMap.outputPorts.get(sourcePortName);
if (sourcePort == null) {
throw new AssertionError(String.format("Invalid port %s (%s)", sourcePortName, om));
}
addStream(streamName, sourcePort.component, getInputPort(targetOperName, targetPortName));
}
@Test
public void testLocalityValidation()
{
TestGeneratorInputOperator input1 = dag.addOperator("input1", TestGeneratorInputOperator.class);
GenericTestOperator o1 = dag.addOperator("o1", GenericTestOperator.class);
StreamMeta s1 = dag.addStream("input1.outport", input1.outport, o1.inport1).setLocality(Locality.THREAD_LOCAL);
dag.validate();
TestGeneratorInputOperator input2 = dag.addOperator("input2", TestGeneratorInputOperator.class);
dag.addStream("input2.outport", input2.outport, o1.inport2);
try {
dag.validate();
Assert.fail("Exception expected for " + o1);
} catch (ValidationException ve) {
Assert.assertThat("", ve.getMessage(), RegexMatcher.matches("Locality THREAD_LOCAL invalid for operator .* with multiple input streams .*"));
}
s1.setLocality(null);
dag.validate();
}
private void validateFields(String formula, List<SimpleSelectionField> columns) {
String regex = REGEX_FIELDS_VALIDATION;
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(formula);
while (m.find()) {
boolean found = false;
for (SimpleSelectionField simpleSelectionField : columns) {
if (simpleSelectionField.getName().equals(m.group(0).replace("\"", ""))) {
found = true;
break;
}
}
if (!found)
throw new ValidationException();
}
}
/**
* Copied and modified from com.yammer.dropwizard.jersey.jackson#JacksonMessageBodyProvider.validate()
* Notes on Hibernate Validator:
* - when validating object graphs, null references are ignored.
* - from version 5 on, Hibernate Validator throws IllegalArgumentException instead of ValidationException
* for null parameter values:
* java.lang.IllegalArgumentException: HV000116: The object to be validated must not be null.
*/
private Object validate(Annotation[] annotations, Object value) {
final Class<?>[] classes = findValidationGroups(annotations);
if (classes != null) {
final Collection<String> errors = ConstraintViolations.format(
validator.validate(value, classes));
if (!errors.isEmpty()) {
String message = "\n";
for (String error : errors) {
message += " " + error + "\n";
}
throw new ValidationException(message);
}
}
return value;
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public String handleValidationException(ValidationException e, Model model) {
logger.error("参数验证失败", e);
String message = "【参数验证失败】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 400);
return viewName;
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public String handleValidationException(ValidationException e, Model model) {
logger.error("参数验证失败", e);
String message = "【参数验证失败】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 400);
return viewName;
}
/**
* Validates that operators in Affinity Rule are valid: Checks that operator names are part of the dag and adds them to map of rules
* @param affinitiesMap
* @param rule
* @param operators
*/
private void addToMap(HashMap<OperatorPair, AffinityRule> affinitiesMap, AffinityRule rule, OperatorPair operators)
{
OperatorMeta operator1 = getOperatorMeta(operators.first);
OperatorMeta operator2 = getOperatorMeta(operators.second);
if (operator1 == null || operator2 == null) {
if (operator1 == null && operator2 == null) {
throw new ValidationException(String.format("Operators %s & %s specified in affinity rule are not part of the dag", operators.first, operators.second));
}
throw new ValidationException(String.format("Operator %s specified in affinity rule is not part of the dag", operator1 == null ? operators.first : operators.second));
}
affinitiesMap.put(operators, rule);
}
private void checkAttributeValueSerializable(AttributeMap attributes, String context)
{
StringBuilder sb = new StringBuilder();
String delim = "";
// Check all attributes got operator are serializable
for (Entry<Attribute<?>, Object> entry : attributes.entrySet()) {
if (entry.getValue() != null && !(entry.getValue() instanceof Serializable)) {
sb.append(delim).append(entry.getKey().getSimpleName());
delim = ", ";
}
}
if (sb.length() > 0) {
throw new ValidationException("Attribute value(s) for " + sb.toString() + " in " + context + " are not serializable");
}
}
@Test
public void testGetActiveExperiments() throws ValidationException {
experiments
.create("foo")
.save();
assertFalse("should have no active experiments", experiments.getActiveExperiments().iterator().hasNext());
experiments
.get("foo")
.activate()
.save();
assertTrue("should have an active experiment", experiments.getActiveExperiments().iterator().hasNext());
}
/**
* 400 - Bad Request
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValidationException.class)
public String handleValidationException(ValidationException e, Model model) {
log.error("参数验证失败", e);
String message = "【参数验证失败】" + e.getMessage();
model.addAttribute("message", message);
model.addAttribute("code", 400);
return viewName;
}
@Test
public void invalidPattern() {
thrown.expect(ValidationException.class);
thrown.expectMessage(containsString("HV000032"));
class FixedAfterTargetBean {
@FixedAfter("2013-07-04")
public Date value;
}
FixedAfterTargetBean target = new FixedAfterTargetBean();
VALIDATOR.validate(target);
}
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(@Nullable Class<T> type) {
Assert.state(this.targetValidator != null, "No target Validator set");
try {
return (type != null ? this.targetValidator.unwrap(type) : (T) this.targetValidator);
}
catch (ValidationException ex) {
// ignore if just being asked for plain Validator
if (javax.validation.Validator.class == type) {
return (T) this.targetValidator;
}
throw ex;
}
}
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
e.printStackTrace();
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
@Test(expected = UnsupportedOperationException.class)
public void testUnmodifiableOverrides() throws ValidationException {
final Experiment experiment =
new Experiment(null, "experiment")
.addTreatment("foo")
.addOverride("override", "foo", "true");
experiment.getOverrides().add(mock(TreatmentOverride.class));
}
@Override
@SuppressWarnings("unchecked")
public <T> T unwrap(@Nullable Class<T> type) {
Assert.state(this.targetValidator != null, "No target Validator set");
try {
return (type != null ? this.targetValidator.unwrap(type) : (T) this.targetValidator);
}
catch (ValidationException ex) {
// ignore if just being asked for plain Validator
if (javax.validation.Validator.class == type) {
return (T) this.targetValidator;
}
throw ex;
}
}
@Override
public void afterPropertiesSet() {
try {
super.afterPropertiesSet();
}
catch (ValidationException ex) {
LogFactory.getLog(getClass()).debug("Failed to set up a Bean Validation provider", ex);
}
}
@Test
public void invocation_target_exception_test() {
thrown.expect(ValidationException.class);
thrown.expectMessage(containsString("HV000028"));
LessThanInvocationTargetExceptionBean target = new LessThanInvocationTargetExceptionBean();
VALIDATOR.validate(target);
}
@Override
public void validate(final Class clazz) throws ValidationException {
Set<String> overloads = new HashSet<>();
GenericChecker checker = new GenericChecker();
checker.checkMethods(clazz, NONE_STATIC_METHOD.and(method -> {
if (!overloads.add(method.getName())) {
onOverloadMethod(clazz, method);
return false;
} else {
return true;
}
}), new MyConsumer(checker, c -> standards.contains(c), noRecommendations));
}
@Test
public void testValidationForNonInputRootOperator()
{
NoInputPortOperator x = dag.addOperator("x", new NoInputPortOperator());
try {
dag.validate();
Assert.fail("should fail because root operator is not input operator");
} catch (ValidationException e) {
// expected
}
}