javax.validation.ConstraintViolationException Java Examples
The following examples show how to use
javax.validation.ConstraintViolationException.
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: WaggleDance.java From waggle-dance with Apache License 2.0 | 7 votes |
public static void main(String[] args) throws Exception { // below is output *before* logging is configured so will appear on console logVersionInfo(); int exitCode = -1; try { SpringApplication application = new SpringApplicationBuilder(WaggleDance.class) .properties("spring.config.location:${server-config:null},${federation-config:null}") .properties("server.port:${endpoint.port:18000}") .registerShutdownHook(true) .build(); exitCode = SpringApplication.exit(registerListeners(application).run(args)); } catch (BeanCreationException e) { Throwable mostSpecificCause = e.getMostSpecificCause(); if (mostSpecificCause instanceof BindException) { printHelp(((BindException) mostSpecificCause).getAllErrors()); } if (mostSpecificCause instanceof ConstraintViolationException) { logConstraintErrors(((ConstraintViolationException) mostSpecificCause)); } throw e; } if (exitCode != 0) { throw new Exception("Waggle Dance didn't exit properly see logs for errors, exitCode=" + exitCode); } }
Example #2
Source File: ControllerManagementTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Test @Description("Tries to register a target with an invalid controller id") public void findOrRegisterTargetIfItDoesNotExistThrowsExceptionForInvalidControllerIdParam() { assertThatExceptionOfType(ConstraintViolationException.class) .as("register target with null as controllerId should fail") .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist(null, LOCALHOST)); assertThatExceptionOfType(ConstraintViolationException.class) .as("register target with empty controllerId should fail") .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist("", LOCALHOST)); assertThatExceptionOfType(ConstraintViolationException.class) .as("register target with empty controllerId should fail") .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist(" ", LOCALHOST)); assertThatExceptionOfType(ConstraintViolationException.class) .as("register target with too long controllerId should fail") .isThrownBy(() -> controllerManagement.findOrRegisterTargetIfItDoesNotExist( RandomStringUtils.randomAlphabetic(Target.CONTROLLER_ID_MAX_SIZE + 1), LOCALHOST)); }
Example #3
Source File: ValidationUtils.java From sundrio with Apache License 2.0 | 6 votes |
public static <T> void validate(T item, Validator v) { if (v == null) { v = getValidator(); } if (v == null) { return; } Set<ConstraintViolation<T>> violations = v.validate(item); if (!violations.isEmpty()) { StringBuilder sb = new StringBuilder("Constraint Validations: "); boolean first = true; for (ConstraintViolation violation : violations) { if (first) { first = false; } else { sb.append(", "); } Object leafBean = violation.getLeafBean(); sb.append(violation.getPropertyPath() + " " + violation.getMessage() + " on bean: " + leafBean); } throw new ConstraintViolationException(sb.toString(), violations); } }
Example #4
Source File: WebErrorHandlersIT.java From errors-spring-boot-starter with Apache License 2.0 | 6 votes |
@Test @Parameters(method = "provideValidationParams") public void constraintViolationException_ShouldBeHandledProperly(Object pojo, Locale locale, CodedMessage... codedMessages) { contextRunner.run(ctx -> { HttpError error; WebErrorHandlers errorHandlers = ctx.getBean(WebErrorHandlers.class); javax.validation.Validator validator = ctx.getBean(javax.validation.Validator.class); ConstraintViolationException exception = new ConstraintViolationException(validator.validate(pojo)); error = errorHandlers.handle(exception, null, locale); assertThat(error.getHttpStatus()).isEqualTo(HttpStatus.BAD_REQUEST); assertThat(error.getErrors()).containsOnly(codedMessages); verifyPostProcessorsHasBeenCalled(ctx); }); }
Example #5
Source File: ValidationEndToEndTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void testRelationProperty() { Task task = new Task(); task.setId(1L); task.setName("test"); taskRepo.create(task); task.setName(ComplexValidator.INVALID_NAME); Project project = new Project(); project.setName("test"); project.setTask(task); 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("task", violation.getPropertyPath().toString()); Assert.assertEquals("/data/relationships/task", violation.getErrorData().getSourcePointer()); } }
Example #6
Source File: JdbcOperatorTest.java From examples with Apache License 2.0 | 6 votes |
@Test public void testApplication() throws Exception { try { LocalMode lma = LocalMode.newInstance(); Configuration conf = new Configuration(false); conf.addResource(this.getClass().getResourceAsStream("/META-INF/properties.xml")); lma.prepareDAG(new JdbcToJdbcApp(), conf); LocalMode.Controller lc = lma.getController(); lc.runAsync(); // wait for records to be added to table Thread.sleep(5000); Assert.assertEquals("Events in store", 10, getNumOfEventsInStore()); cleanTable(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }
Example #7
Source File: OiOStreamTest.java From attic-apex-core with Apache License 2.0 | 6 votes |
@Test public void validatePositiveOiOiOExtendeddiamond() { logger.info("Checking the logic for sanity checking of OiO"); LogicalPlan plan = new LogicalPlan(); ThreadIdValidatingInputOperator inputOperator = plan.addOperator("inputOperator", new ThreadIdValidatingInputOperator()); ThreadIdValidatingGenericIntermediateOperator intermediateOperator1 = plan.addOperator("intermediateOperator1", new ThreadIdValidatingGenericIntermediateOperator()); ThreadIdValidatingGenericIntermediateOperator intermediateOperator2 = plan.addOperator("intermediateOperator2", new ThreadIdValidatingGenericIntermediateOperator()); ThreadIdValidatingGenericIntermediateOperator intermediateOperator3 = plan.addOperator("intermediateOperator3", new ThreadIdValidatingGenericIntermediateOperator()); ThreadIdValidatingGenericIntermediateOperator intermediateOperator4 = plan.addOperator("intermediateOperator4", new ThreadIdValidatingGenericIntermediateOperator()); ThreadIdValidatingGenericOperatorWithTwoInputPorts outputOperator = plan.addOperator("outputOperator", new ThreadIdValidatingGenericOperatorWithTwoInputPorts()); plan.addStream("OiOin", inputOperator.output, intermediateOperator1.input, intermediateOperator3.input).setLocality(Locality.THREAD_LOCAL); plan.addStream("OiOIntermediate1", intermediateOperator1.output, intermediateOperator2.input).setLocality(Locality.THREAD_LOCAL); plan.addStream("OiOIntermediate2", intermediateOperator3.output, intermediateOperator4.input).setLocality(Locality.THREAD_LOCAL); plan.addStream("OiOout1", intermediateOperator2.output, outputOperator.input).setLocality(Locality.THREAD_LOCAL); plan.addStream("OiOout2", intermediateOperator4.output, outputOperator.input2).setLocality(Locality.THREAD_LOCAL); try { plan.validate(); Assert.assertTrue("OiOiO extended diamond validation", true); } catch (ConstraintViolationException ex) { Assert.fail("OIOIO extended diamond validation"); } }
Example #8
Source File: RpsServicoTest.java From nfse with MIT License | 6 votes |
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirCodCnaeTamanhoInvalido() throws Exception { try { new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01") .comDiscriminacao("Descricao Teste") .comCodigoCnae("") .comCodigoMunicipio("3106200") .build(); } catch (final ConstraintViolationException e) { new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01") .comDiscriminacao("Descricao Teste") .comCodigoCnae("00000000") .comCodigoMunicipio("3106200") .build(); } }
Example #9
Source File: DefaultRuntimeContextFactoryTest.java From tessera with Apache License 2.0 | 6 votes |
@Test public void validationFailireThrowsException() { Config confg = mock(Config.class); EncryptorConfig encryptorConfig = mock(EncryptorConfig.class); when(encryptorConfig.getType()).thenReturn(EncryptorType.NACL); when(confg.getEncryptor()).thenReturn(encryptorConfig); KeyConfiguration keyConfiguration = mock(KeyConfiguration.class); when(confg.getKeys()).thenReturn(keyConfiguration); ConstraintViolation<?> violation = mock(ConstraintViolation.class); MockKeyVaultConfigValidations.addConstraintViolation(violation); try { runtimeContextFactory.create(confg); failBecauseExceptionWasNotThrown(ConstraintViolationException.class); } catch (ConstraintViolationException ex) { assertThat(ex.getConstraintViolations()).containsExactly(violation); } }
Example #10
Source File: TargetTagManagementTest.java From hawkbit with Eclipse Public License 1.0 | 6 votes |
@Step private void createAndUpdateTagWithInvalidDescription(final Tag tag) { assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> targetTagManagement.create( entityFactory.tag().create().name("a").description(RandomStringUtils.randomAlphanumeric(513)))) .as("tag with too long description should not be created"); assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy( () -> targetTagManagement.create(entityFactory.tag().create().name("a").description(INVALID_TEXT_HTML))) .as("tag with invalid description should not be created"); assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> targetTagManagement.update( entityFactory.tag().update(tag.getId()).description(RandomStringUtils.randomAlphanumeric(513)))) .as("tag with too long description should not be updated"); assertThatExceptionOfType(ConstraintViolationException.class) .isThrownBy(() -> targetTagManagement .update(entityFactory.tag().update(tag.getId()).description(INVALID_TEXT_HTML))) .as("tag with invalid description should not be updated"); }
Example #11
Source File: ServiceInterceptor.java From conductor with Apache License 2.0 | 6 votes |
/** * * @param invocation * @return * @throws ConstraintViolationException incase of any constraints * defined on method parameters are violated. */ @Override public Object invoke(MethodInvocation invocation) throws Throwable { if (skipMethod(invocation)) { return invocation.proceed(); } ExecutableValidator executableValidator = validatorProvider.get().forExecutables(); Set<ConstraintViolation<Object>> result = executableValidator.validateParameters( invocation.getThis(), invocation.getMethod(), invocation.getArguments()); if (!result.isEmpty()) { throw new ConstraintViolationException(result); } return invocation.proceed(); }
Example #12
Source File: ProductMilestoneTest.java From pnc with Apache License 2.0 | 6 votes |
@Test public void shouldNotCreateProductMilestoneWithMalformedVersion() { // given ProductMilestone productMilestone = ProductMilestone.Builder.newBuilder() .version("1.0.0-CD1") .productVersion(productVersion) .build(); // when-then try { em.getTransaction().begin(); em.persist(productMilestone); em.getTransaction().commit(); } catch (RollbackException ex) { if (!(ex.getCause() instanceof ConstraintViolationException)) fail("Creation of ProductMilestones with malformed version should not be allowed"); } }
Example #13
Source File: ApplicationTest.java From examples with Apache License 2.0 | 6 votes |
@Test public void testApplication() throws IOException, Exception { try { // create file in monitored HDFS directory createFile(); // run app asynchronously; terminate after results are checked LocalMode.Controller lc = asyncRun(); // get messages from Kafka topic and compare with input chkOutput(); lc.shutdown(); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }
Example #14
Source File: ValidationEndToEndTest.java From crnk-framework with Apache License 2.0 | 6 votes |
@Test public void testPropertyOnRelation() { Task task = new Task(); task.setId(1L); task.setName("test"); taskRepo.create(task); task.setName(null); Project project = new Project(); project.setId(2L); project.setName("test"); project.getTasks().add(task); 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("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("tasks[0]", violation.getPropertyPath().toString()); Assert.assertEquals("/data/relationships/tasks/0", violation.getErrorData().getSourcePointer()); } }
Example #15
Source File: TagService.java From blog-spring with MIT License | 6 votes |
public Tag findOrCreateByName(String name) { Tag tag = tagRepository.findByName(name); if (tag == null) { try { tag = new Tag(); tag.setName(name); tag.setPostCount(0); tagRepository.save(tag); } catch (ConstraintViolationException exception) { ConstraintViolation<?> violation = exception.getConstraintViolations().iterator().next(); throw new InvalidTagException( "Invalid tag " + violation.getPropertyPath() + ": " + violation.getMessage()); } } return tag; }
Example #16
Source File: GroupsTest.java From guice-validator with MIT License | 5 votes |
@Test public void testNoContext() throws Exception { // ok service.noContext(new Model(null, null, "sample")); Assert.assertTrue(service.lastCallGroups.length == 0); try { // default group service.noContext(new Model(null, null, null)); } catch (ConstraintViolationException ex) { Set<String> props = PropFunction.convert(ex.getConstraintViolations()); Assert.assertEquals(1, props.size()); Assert.assertEquals(Sets.newHashSet("def"), props); } }
Example #17
Source File: App.java From Java-EE-8-and-Angular with MIT License | 5 votes |
private void trySaveInvalid() { Task theTask = new Task(); theTask.setName("A longer name than allowed"); try { em.persist(theTask); } catch (ConstraintViolationException violation) { violation.getConstraintViolations().forEach( v -> System.out.println("violation " + v) ); } }
Example #18
Source File: AddressValidationTest.java From sundrio with Apache License 2.0 | 5 votes |
@Test(expected = ConstraintViolationException.class) public void testWithAlphanumericZipCode() { Address address = new AddressBuilder().withStreet("Sesame") .withNumber(1) .withZipCode("abcd") .build(); }
Example #19
Source File: BaseController.java From seata-demo with Apache License 2.0 | 5 votes |
@ExceptionHandler({ConstraintViolationException.class}) public @ResponseBody StandResponse exception(ConstraintViolationException e, HttpServletRequest request, HttpServletResponse response) { e.printStackTrace(); logger.error("#######ERROR#######", e); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "OPTIONS,GET,POST"); return StandResponseBuilder.result(StandResponse.BUSINESS_EXCEPTION, ((ConstraintViolation) (e.getConstraintViolations().toArray()[0])).getMessage()); }
Example #20
Source File: ErrorHandlingControllerAdvice.java From code-examples with MIT License | 5 votes |
@ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody ValidationErrorResponse onConstraintValidationException(ConstraintViolationException e) { ValidationErrorResponse error = new ValidationErrorResponse(); for (ConstraintViolation violation : e.getConstraintViolations()) { error.getViolations().add(new Violation(violation.getPropertyPath().toString(), violation.getMessage())); } return error; }
Example #21
Source File: ConstraintViolationExceptionHandler.java From tutorials with MIT License | 5 votes |
@ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<String> handle(ConstraintViolationException constraintViolationException) { Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations(); String errorMessage = ""; if (!violations.isEmpty()) { StringBuilder builder = new StringBuilder(); violations.forEach(violation -> builder.append("\n" + violation.getMessage())); errorMessage = builder.toString(); } else { errorMessage = "ConstraintViolationException occured."; } logger.error(errorMessage); return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); }
Example #22
Source File: RpsTomadorTest.java From nfse with MIT License | 5 votes |
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirInscricaoMunicipalComTamanhoInvalido() throws Exception { try { new TomadorBuilder("12345678909") .comInscricaoMunicipal("").build(); } catch (final ConstraintViolationException e) { new TomadorBuilder("12345678909") .comInscricaoMunicipal("0000000000000000").build(); } }
Example #23
Source File: LocServiceAdviceTrait.java From loc-framework with MIT License | 5 votes |
@API(status = API.Status.INTERNAL) @ExceptionHandler(value = ConstraintViolationException.class) default ResponseEntity<Problem> handleConstraintViolationException( final ConstraintViolationException constraintViolationException, final NativeWebRequest request) { return this.create(constraintViolationException, ProblemUtil.createProblem( constraintViolationException.getConstraintViolations().stream() .map(ConstraintViolation::getMessage).collect(Collectors.joining(",")), CONSTRAINT_VIOLATION_ERROR_CODE), request); }
Example #24
Source File: AppBaseController.java From Shop-for-JavaWeb with MIT License | 5 votes |
/** * 服务端参数有效性验证 * @param object 验证的实体对象 * @param groups 验证组 * @return 验证成功:返回true;严重失败:将错误信息添加到 message 中 */ protected boolean beanValidator(Model model, Object object, Class<?>... groups) { try{ BeanValidators.validateWithException(validator, object, groups); }catch(ConstraintViolationException ex){ List<String> list = BeanValidators.extractPropertyAndMessageAsList(ex, ": "); list.add(0, "数据验证失败:"); addMessage(model, list.toArray(new String[]{})); return false; } return true; }
Example #25
Source File: RpsServicoTest.java From nfse with MIT License | 5 votes |
@Test(expected = ConstraintViolationException.class) public void naoDevePermitirServicoSemDiscriminacao() throws Exception { new ServicoBuilder(FabricaDeObjetosFake.getRpsValores(), "01.01") .comCodigoCnae("0000000") .comCodigoTributacaoMunicipio("00000000000000000000") .comCodigoMunicipio("3106200") .build(); }
Example #26
Source File: BeanValidationTest.java From tomee with Apache License 2.0 | 5 votes |
@Test public void notValid() { try { persistManager.persistNotValid(); fail(); } catch (final EJBException ejbException) { assertTrue(ejbException.getCause() instanceof ConstraintViolationException); final ConstraintViolationException constraintViolationException = (ConstraintViolationException) ejbException.getCause(); assertEquals(1, constraintViolationException.getConstraintViolations().size()); } }
Example #27
Source File: ConstraintViolationExceptionMapper.java From browserup-proxy with Apache License 2.0 | 5 votes |
private ConstraintsErrors createConstraintErrors(ConstraintViolationException exception) { ConstraintsErrors errors = new ConstraintsErrors(); exception.getConstraintViolations().stream() .filter(v -> StringUtils.isNotEmpty(v.getMessage())) .forEach(violation -> errors.addError(getArgumentName(violation), violation.getMessage())); return errors; }
Example #28
Source File: ProgrammaticallyValidatingServiceTest.java From code-examples with MIT License | 5 votes |
@Test void whenInputIsInvalid_thenThrowsException(){ Input input = new Input(); input.setNumberBetweenOneAndTen(0); input.setIpAddress("invalid"); assertThrows(ConstraintViolationException.class, () -> { service.validateInput(input); }); }
Example #29
Source File: ControllerManagementTest.java From hawkbit with Eclipse Public License 1.0 | 5 votes |
@Test @Description("Verify that a null externalRef cannot be assigned to an action") public void externalRefCannotBeNull() { assertThatExceptionOfType(ConstraintViolationException.class) .as("No ConstraintViolationException thrown when a null externalRef was set on an action") .isThrownBy(() -> controllerManagement.updateActionExternalRef(1L, null)); }
Example #30
Source File: ApiValidationExceptionMapper.java From redpipe with Apache License 2.0 | 5 votes |
@Override public Response toResponse(ConstraintViolationException exception) { JsonObject response = new JsonObject(); response .put("success", false) .put("error", "Bad request payload"); return Response.status(Status.BAD_REQUEST).entity(response).build(); }