javax.validation.ConstraintViolation Java Examples
The following examples show how to use
javax.validation.ConstraintViolation.
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: IPv4Test.java From sinavi-jfw with Apache License 2.0 | 6 votes |
@Theory public void default_message_test(String invalid) { Assume.assumeThat(Arrays.asList(INVALIDS), hasItem(invalid)); class IPv4TargetBean { @IPv4 public String value; } IPv4TargetBean target = new IPv4TargetBean(); target.value = invalid; Set<ConstraintViolation<IPv4TargetBean>> errors = VALIDATOR.validate(target); assertThat(errors, notNullValue()); assertThat(errors.size(), is(1)); assertEqualsErrorMessages(errors, "IPv4の形式で入力してください。"); }
Example #2
Source File: ExtensionHandler.java From syndesis with Apache License 2.0 | 6 votes |
private Set<Violation> doValidate(Extension extension) { ListResult<Extension> result = getDataManager().fetchAll(Extension.class); ExtensionWithDomain target = new ExtensionWithDomain(extension, result.getItems()); final Set<ConstraintViolation<ExtensionWithDomain>> constraintViolations = getValidator().validate(target, Default.class, AllValidations.class); if (!constraintViolations.isEmpty()) { throw new ConstraintViolationException(constraintViolations); } Set<ConstraintViolation<ExtensionWithDomain>> warnings = getValidator().validate(target, NonBlockingValidations.class); return warnings.stream() .map(Violation.Builder::fromConstraintViolation) .collect(Collectors.toSet()); }
Example #3
Source File: SpringValidatorAdapterTests.java From java-technology-stack with MIT License | 6 votes |
@Test // SPR-13406 public void testApplyMessageSourceResolvableToStringArgumentValueWithUnresolvedLogicalFieldName() { TestBean testBean = new TestBean(); testBean.setEmail("[email protected]"); testBean.setConfirmEmail("[email protected]"); BeanPropertyBindingResult errors = new BeanPropertyBindingResult(testBean, "testBean"); validatorAdapter.validate(testBean, errors); assertThat(errors.getFieldErrorCount("email"), is(1)); assertThat(errors.getFieldValue("email"), is("[email protected]")); assertThat(errors.getFieldErrorCount("confirmEmail"), is(1)); FieldError error1 = errors.getFieldError("email"); FieldError error2 = errors.getFieldError("confirmEmail"); assertNotNull(error1); assertNotNull(error2); assertThat(messageSource.getMessage(error1, Locale.ENGLISH), is("email must be same value as confirmEmail")); assertThat(messageSource.getMessage(error2, Locale.ENGLISH), is("Email required")); assertTrue(error1.contains(ConstraintViolation.class)); assertThat(error1.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("email")); assertTrue(error2.contains(ConstraintViolation.class)); assertThat(error2.unwrap(ConstraintViolation.class).getPropertyPath().toString(), is("confirmEmail")); }
Example #4
Source File: MinLengthTest.java From sinavi-jfw with Apache License 2.0 | 6 votes |
@Theory public void override_message_test(String invalid) { Assume.assumeThat(Arrays.asList(INVALIDS), hasItem(invalid)); class MinLengthTargetBean { @MinLength(value = 5, message = "{value}文字を超える値のみ入力可能です。${validatedValue}") public String value; } MinLengthTargetBean target = new MinLengthTargetBean(); target.value = invalid; Set<ConstraintViolation<MinLengthTargetBean>> errors = VALIDATOR.validate(target); assertThat(errors, notNullValue()); assertThat(errors.size(), is(1)); assertEqualsErrorMessages(errors, "5文字を超える値のみ入力可能です。" + invalid); }
Example #5
Source File: RestApiUtil.java From carbon-apimgt with Apache License 2.0 | 6 votes |
public static <T> ErrorDTO getConstraintViolationErrorDTO(Set<ConstraintViolation<T>> violations) { ErrorDTO errorDTO = new ErrorDTO(); errorDTO.setDescription("Validation Error"); errorDTO.setMessage("Bad Request"); errorDTO.setCode(400l); errorDTO.setMoreInfo(""); List<ErrorListItemDTO> errorListItemDTOs = new ArrayList<>(); for (ConstraintViolation violation : violations) { ErrorListItemDTO errorListItemDTO = new ErrorListItemDTO(); errorListItemDTO.setCode(400 + "_" + violation.getPropertyPath()); errorListItemDTO.setMessage(violation.getPropertyPath() + ": " + violation.getMessage()); errorListItemDTOs.add(errorListItemDTO); } errorDTO.setError(errorListItemDTOs); return errorDTO; }
Example #6
Source File: GlobalControllerAdvice.java From springdoc-openapi with Apache License 2.0 | 6 votes |
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(code = HttpStatus.BAD_REQUEST) public ResponseEntity<ErrorMessage> handleConstraintViolatedException(ConstraintViolationException ex ) { Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); List<String> errors = new ArrayList<>(constraintViolations.size()); String error; for (ConstraintViolation constraintViolation : constraintViolations) { error = constraintViolation.getMessage(); errors.add(error); } ErrorMessage errorMessage = new ErrorMessage(errors); return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST); }
Example #7
Source File: SpringValidatorAdapter.java From spring-analysis-note with MIT License | 6 votes |
/** * Determine a field for the given constraint violation. * <p>The default implementation returns the stringified property path. * @param violation the current JSR-303 ConstraintViolation * @return the Spring-reported field (for use with {@link Errors}) * @since 4.2 * @see javax.validation.ConstraintViolation#getPropertyPath() * @see org.springframework.validation.FieldError#getField() */ protected String determineField(ConstraintViolation<Object> violation) { Path path = violation.getPropertyPath(); StringBuilder sb = new StringBuilder(); boolean first = true; for (Path.Node node : path) { if (node.isInIterable()) { sb.append('['); Object index = node.getIndex(); if (index == null) { index = node.getKey(); } if (index != null) { sb.append(index); } sb.append(']'); } String name = node.getName(); if (name != null && node.getKind() == ElementKind.PROPERTY && !name.startsWith("<")) { if (!first) { sb.append('.'); } first = false; sb.append(name); } } return sb.toString(); }
Example #8
Source File: AbstractResourceUpdateHandler.java From syndesis with Apache License 2.0 | 6 votes |
protected <V> List<LeveledMessage> computeValidatorMessages(Supplier<LeveledMessage.Builder> supplier, V target) { final List<LeveledMessage> messages = new ArrayList<>(); final Set<ConstraintViolation<V>> constraintViolations = validator.validate(target, AllValidations.class); for (ConstraintViolation<V> violation : constraintViolations) { messages.add( supplier.get() .code(LeveledMessage.Code.SYNDESIS008) .level(LeveledMessage.Level.ERROR) .message(violation.getMessage()) .build() ); } return messages; }
Example #9
Source File: GlobalControllerAdvice.java From springdoc-openapi with Apache License 2.0 | 6 votes |
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(code = HttpStatus.BAD_REQUEST) public ResponseEntity<ErrorMessage> handleConstraintViolatedException(ConstraintViolationException ex ) { Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations(); List<String> errors = new ArrayList<>(constraintViolations.size()); String error; for (ConstraintViolation constraintViolation : constraintViolations) { error = constraintViolation.getMessage(); errors.add(error); } ErrorMessage errorMessage = new ErrorMessage(errors); return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST); }
Example #10
Source File: ValidationEndToEndTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void testResourceObjectValidation() { Project project = new Project(); project.setId(1L); project.setName(ComplexValidator.INVALID_NAME); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{complex.message}", violation.getMessageTemplate()); Assert.assertEquals("", violation.getPropertyPath().toString()); Assert.assertEquals("", violation.getErrorData().getSourcePointer()); } }
Example #11
Source File: DecimalTest.java From sinavi-jfw with Apache License 2.0 | 6 votes |
@Theory public void validWithSigned(String sign, String precision, String scale) { Assume.assumeThat(Arrays.asList(SIGN), hasItem(sign)); Assume.assumeThat(Arrays.asList(PRECISION), hasItem(precision)); Assume.assumeThat(Arrays.asList(SCALE), hasItem(scale)); class DecimalTargetBean { @Decimal(precision = 7, scale = 3, signed = true) public String value; } DecimalTargetBean target = new DecimalTargetBean(); target.value = sign + precision + scale; Set<ConstraintViolation<DecimalTargetBean>> errors = VALIDATOR.validate(target); assertThat(errors, notNullValue()); assertThat(errors.size(), is(0)); }
Example #12
Source File: ClientChoiceTest.java From Java-EE-8-Sampler with MIT License | 6 votes |
@Test public void givenMapWithConstraints_shouldValidate() { ClientChoice clientChoice = new ClientChoice(); clientChoice.addClientChoices("John", new ArrayList<Choice>() {{ add(new Choice(1, "Roast Lamb")); add(new Choice(1, "Ice Cream")); add(new Choice(1, "Apple")); }}); clientChoice.addClientChoices("May", new ArrayList<Choice>() {{ add(new Choice(1, "Grapes")); add(new Choice(1, "Beef Stake")); add(new Choice(1, "Pizza")); }}); Set<ConstraintViolation<ClientChoice>> constraintViolations = validator.validate(clientChoice); assertThat(constraintViolations.size()).isEqualTo(0); }
Example #13
Source File: ConstraintViolations.java From krazo with Apache License 2.0 | 6 votes |
private static Annotation[] getPropertyAnnotations(ConstraintViolation<?> violation, Path.PropertyNode node) { Class<?> leafBeanClass = violation.getLeafBean().getClass(); Set<Annotation> allAnnotations = new HashSet<>(); try { Field field = leafBeanClass.getDeclaredField(node.getName()); allAnnotations.addAll(Arrays.asList(field.getAnnotations())); } catch (NoSuchFieldException e) { // ignore for now } allAnnotations.addAll(readAndWriteMethodAnnotationsForField(leafBeanClass, node.getName())); return allAnnotations.toArray(new Annotation[0]); }
Example #14
Source File: JformOrderMain2Controller.java From jeecg with Apache License 2.0 | 6 votes |
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody @ApiOperation(value="创建订单主信息") public ResponseMessage<?> create(@ApiParam(name="订单主信息对象")@RequestBody JformOrderMain2Page jformOrderMain2Page, UriComponentsBuilder uriBuilder) { //调用JSR303 Bean Validator进行校验,如果出错返回含400错误码及json格式的错误信息. Set<ConstraintViolation<JformOrderMain2Page>> failures = validator.validate(jformOrderMain2Page); if (!failures.isEmpty()) { return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures))); } //保存 List<JformOrderTicket2Entity> jformOrderTicket2List = jformOrderMain2Page.getJformOrderTicket2List(); List<JformOrderCustomer2Entity> jformOrderCustomer2List = jformOrderMain2Page.getJformOrderCustomer2List(); JformOrderMain2Entity jformOrderMain2 = new JformOrderMain2Entity(); try{ MyBeanUtils.copyBeanNotNull2Bean(jformOrderMain2Page,jformOrderMain2); }catch(Exception e){ logger.info(e.getMessage()); return Result.error("保存订单主信息失败"); } jformOrderMain2Service.addMain(jformOrderMain2, jformOrderTicket2List,jformOrderCustomer2List); return Result.success(jformOrderMain2); }
Example #15
Source File: CertificateSetRequestTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void whenTheValueIsValid_doesNotRequireTheCertificate() { final String setJson = JSONObject.toJSONString( ImmutableMap.<String, String>builder() .put("ca", TEST_CA) .put("private_key", TEST_PRIVATE_KEY) .build()); final String json = "{" + "\"name\": \"/example/certificate\"," + "\"type\": \"certificate\"," + "\"value\": " + setJson + "}"; final Set<ConstraintViolation<CertificateSetRequest>> violations = deserializeAndValidate(json, CertificateSetRequest.class); assertThat(violations.size(), equalTo(0)); final CertificateSetRequest certificateSetRequest = deserialize(json, CertificateSetRequest.class); assertNull(certificateSetRequest.getCertificateValue().getCertificate()); }
Example #16
Source File: T212MapVerifyTest.java From hj-t212-parser with Apache License 2.0 | 5 votes |
@Test public void testDataLevel(){ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T212Map>> e2005 = validator.validate(dataLevel,Default.class, T212MapLevelGroup.DataLevel.class, VersionGroup.V2005.class); assertTrue(e2005.isEmpty()); Set<ConstraintViolation<T212Map>> e2017 = validator.validate(dataLevel,Default.class, T212MapLevelGroup.DataLevel.class, VersionGroup.V2017.class); assertTrue(e2017.isEmpty()); }
Example #17
Source File: ConstraintViolationExceptionMapper.java From browserup-proxy with Apache License 2.0 | 5 votes |
private String getArgumentName(ConstraintViolation<?> violation) { String argumentIdentifier; Object paramName = violation.getConstraintDescriptor().getAttributes().get(PARAMETER_NAME_ATTRIBUTE); if (paramName instanceof String && paramName.toString().length() > 0) { argumentIdentifier = (String) paramName; } else { argumentIdentifier = StringUtils.substringAfterLast(violation.getPropertyPath().toString(), "."); } return argumentIdentifier; }
Example #18
Source File: RpcExceptionMapper.java From dubbox with Apache License 2.0 | 5 votes |
protected Response handleConstraintViolationException(ConstraintViolationException cve) { ViolationReport report = new ViolationReport(); for (ConstraintViolation cv : cve.getConstraintViolations()) { report.addConstraintViolation(new RestConstraintViolation( cv.getPropertyPath().toString(), cv.getMessage(), cv.getInvalidValue() == null ? "null" : cv.getInvalidValue().toString())); } // TODO for now just do xml output return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build(); }
Example #19
Source File: SpELClassValidatorTest.java From titus-control-plane with Apache License 2.0 | 5 votes |
@Test public void testSpELCondition() { Validator validator = TestValidator.testStrictValidator(); Root root = new Root( "root1", new Child("child1", 0, 2), new NullableChild("child2") ); Set<ConstraintViolation<Root>> violations = validator.validate(root); System.out.println(violations); assertThat(violations).hasSize(1); }
Example #20
Source File: BeanValidation.java From open-Autoscaler with Apache License 2.0 | 5 votes |
public static JsonNode parseMetrics(String jsonString, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{ List<String> violation_message = new ArrayList<String>(); ObjectNode result = new_mapper.createObjectNode(); result.put("valid", false); //JavaType javaType = getCollectionType(ArrayList.class, HistoryData.class); //new_mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); logger.info("Received metrics: " + jsonString); Metrics metrics = new_mapper.readValue(jsonString, Metrics.class); ValidatorFactory vf = Validation.buildDefaultValidatorFactory(); Locale locale = LocaleUtil.getLocale(httpServletRequest); MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale); Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator(); Set<ConstraintViolation<Metrics>> set = validator.validate(metrics); if (set.size() > 0 ){ for (ConstraintViolation<Metrics> constraintViolation : set) { violation_message.add(constraintViolation.getMessage()); } result.set("violation_message", new_mapper.valueToTree(violation_message)); return result; } //additional data manipulation String new_json = metrics.transformOutput(); result.put("valid", true); result.put("new_json", new_json); return result; }
Example #21
Source File: ContentFacetSupport.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
private ConstraintViolation<?> validateBlobStoreNotInGroup(final String blobStoreName) { return dependencies.blobStoreManager.getParent(blobStoreName) .map(groupName -> dependencies.constraintViolationFactory. createViolation(format("%s.blobStoreName", STORAGE), format("Blob Store '%s' is a member of Blob Store Group '%s' and cannot be set as storage", blobStoreName, groupName))) .orElse(null); }
Example #22
Source File: TraverseGraphByObjectSearchRequestTest.java From act-platform with ISC License | 5 votes |
@Test public void testRequestValidationFailsOnNullSearchAndTraverse() { Set<ConstraintViolation<TraverseGraphByObjectSearchRequest>> violations = getValidator() .validate(new TraverseGraphByObjectSearchRequest()); assertEquals(2, violations.size()); assertPropertyInvalid(violations, "search"); assertPropertyInvalid(violations, "traverse"); }
Example #23
Source File: DataSetEditorWorkflowTest.java From dashbuilder with Apache License 2.0 | 5 votes |
@Test public void testAddViolations() { presenter.violations.clear(); ConstraintViolationImpl v1 = mock(ConstraintViolationImpl.class); List<ConstraintViolation> _violations = new ArrayList<ConstraintViolation>(); _violations.add(v1); presenter.addViolations(_violations); assertTrue(presenter.hasErrors()); verify(view, times(0)).clearButtons(); verify(view, times(0)).addButton(anyString(), anyString(), anyBoolean(), any(Command.class)); verify(view, times(0)).add(any(IsWidget.class)); verify(view, times(0)).init(presenter); verify(view, times(0)).clearView(); }
Example #24
Source File: UpdateFactTypeRequestTest.java From act-platform with ISC License | 5 votes |
@Test public void testRequestValidationFailsOnMin() { Set<ConstraintViolation<UpdateFactTypeRequest>> violations = getValidator().validate(new UpdateFactTypeRequest() .setId(UUID.randomUUID()) .setDefaultConfidence(-0.1f)); assertEquals(1, violations.size()); assertPropertyInvalid(violations, "defaultConfidence"); }
Example #25
Source File: AttributeNamePrefixedWithServiceNameValidatorTest.java From cm_ext with Apache License 2.0 | 5 votes |
@Test public void testInvaidServiceNameNotSmallCapsPrefixed() { MetricEntityAttributeDescriptor attribute = mockAttribute("FOOBARAttribute"); List<ConstraintViolation<Object>> validations = validator.validate(context, attribute, root); assertFalse(validations.isEmpty()); ConstraintViolation<Object> validation = Iterables.getOnlyElement( validations); assertTrue(validation.toString(), validation.getMessage().contains( "Attribute 'FOOBARAttribute' does not start with the " + "service name ('foobar')")); String path = validation.getPropertyPath().toString(); assertEquals(String.format("%s.name", SERVICE_NAME), path); }
Example #26
Source File: FavouriteTest.java From Java-EE-8-Sampler with MIT License | 5 votes |
@Test public void givenListWithConstraints_shouldNotValidate() { ClientFavourites clientFavourites = new ClientFavourites(); clientFavourites.addFavourites(new Favourite(1, "Cheese")); clientFavourites.addFavourites(new Favourite(2, "Ham")); clientFavourites.addFavourites(new Favourite(3, "Egg")); Set<ConstraintViolation<ClientFavourites>> constraintViolations = validator.validate(clientFavourites); assertThat(constraintViolations.size()).isEqualTo(2); }
Example #27
Source File: OpenAPIUtils.java From openapi-generator with Apache License 2.0 | 5 votes |
public static <T> void validate(T obj) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj); if (constraintViolations.size() > 0) { StringBuilder errors = new StringBuilder(); for (ConstraintViolation<T> contraintes : constraintViolations) { errors.append(String.format("%s.%s %s\n", contraintes.getRootBeanClass().getSimpleName(), contraintes.getPropertyPath(), contraintes.getMessage())); } throw new RuntimeException("Bean validation : " + errors); } }
Example #28
Source File: ValidationIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void whenValidationWithValidConstructorReturnValue_thenZeroVoilations() throws NoSuchMethodException { Constructor<Reservation> constructor = Reservation.class.getConstructor(LocalDate.class, LocalDate.class, Customer.class, int.class); Reservation createdObject = new Reservation(LocalDate.now() .plusDays(1), LocalDate.now() .plusDays(2), new Customer("William", "Smith"), 1); Set<ConstraintViolation<Reservation>> violations = executableValidator.validateConstructorReturnValue(constructor, createdObject); assertEquals(0, violations.size()); }
Example #29
Source File: GroupResource.java From bouncr with Eclipse Public License 1.0 | 5 votes |
@Decision(value = MALFORMED, method = "PUT") public Problem vaidateCreateRequest(GroupCreateRequest updateRequest, RestContext context) { if (updateRequest == null) { return builder(Problem.valueOf(400, "request is empty")) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); } Set<ConstraintViolation<GroupCreateRequest>> violations = validator.validate(updateRequest); if (violations.isEmpty()) { context.putValue(updateRequest); } return violations.isEmpty() ? null : builder(Problem.fromViolations(violations)) .set(Problem::setType, BouncrProblem.MALFORMED.problemUri()) .build(); }
Example #30
Source File: FieldValidator.java From hj-t212-parser with Apache License 2.0 | 5 votes |
public static void create_format_exception2(Set<? extends ConstraintViolation> constraintViolationSet) throws T212FormatException { Map<String, List<ConstraintViolation>> typeCVs = constraintViolationSet .stream() .collect(Collectors.groupingBy( ConstraintViolation::getMessage, Collectors.toList()) ); Map<String, String> typePropertys = typeCVs.entrySet() .stream() .map(kv -> { String pps = kv.getValue() .stream() .map(cv -> "'" + cv.getPropertyPath() + "'") .collect(Collectors.joining(",")); return new AbstractMap.SimpleEntry<>(kv.getKey(),pps); }) .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); String msg = typePropertys.entrySet() .stream() .map(kv -> "\t" + kv.getKey() + " -> " + kv.getValue()) .collect(Collectors.joining("\n")); throw new T212FormatException("Validate error\n" + msg); }