javax.validation.ConstraintViolationException源码实例Demo

org.springframework.web.bind.annotation.ExceptionHandler#javax.validation.ConstraintViolationException源码实例Demo

下面列出了org.springframework.web.bind.annotation.ExceptionHandler#javax.validation.ConstraintViolationException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: crnk-framework   文件: ValidationEndToEndTest.java
@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());
	}
}
 
源代码2 项目: examples   文件: JdbcOperatorTest.java
@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());
  }
}
 
源代码3 项目: sundrio   文件: ValidationUtils.java
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);
    }
}
 
源代码4 项目: waggle-dance   文件: WaggleDance.java
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);
  }
}
 
源代码5 项目: crnk-framework   文件: ValidationEndToEndTest.java
@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());
	}
}
 
源代码6 项目: blog-spring   文件: TagService.java
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;
}
 
源代码7 项目: examples   文件: ApplicationTest.java
@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());
  }
}
 
源代码8 项目: pnc   文件: ProductMilestoneTest.java
@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");
    }
}
 
源代码9 项目: conductor   文件: ServiceInterceptor.java
/**
 *
 * @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();
}
 
源代码10 项目: hawkbit   文件: TargetTagManagementTest.java
@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");
}
 
源代码11 项目: tessera   文件: DefaultRuntimeContextFactoryTest.java
@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);
    }
}
 
源代码12 项目: nfse   文件: RpsServicoTest.java
@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();
  }
}
 
源代码13 项目: hawkbit   文件: ControllerManagementTest.java
@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));
}
 
@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);
    });
}
 
源代码15 项目: attic-apex-core   文件: OiOStreamTest.java
@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");
  }
}
 
@Test
void whenInputIsInvalid_thenThrowsException(){
  Input input = new Input();
  input.setNumberBetweenOneAndTen(0);
  input.setIpAddress("invalid");

  assertThrows(ConstraintViolationException.class, () -> {
    service.validateInput(input);
  });
}
 
源代码17 项目: nexus-public   文件: ValidationResponse.java
public ValidationResponse(final ConstraintViolationException cause) {
  super(false, new ArrayList<>());
  //noinspection ThrowableResultOfMethodCallIgnored
  checkNotNull(cause);
  Set<ConstraintViolation<?>> violations = cause.getConstraintViolations();
  if (violations != null && !violations.isEmpty()) {
    for (ConstraintViolation<?> violation : violations) {
      List<String> entries = new ArrayList<>();
      // iterate path to get the full path
      Iterator<Node> it = violation.getPropertyPath().iterator();
      while (it.hasNext()) {
        Node node = it.next();
        if (ElementKind.PROPERTY == node.getKind() || (ElementKind.PARAMETER == node.getKind() && !it.hasNext())) {
          if (node.getKey() != null) {
            entries.add(node.getKey().toString());
          }
          entries.add(node.getName());
        }
      }
      if (entries.isEmpty()) {
        if (messages == null) {
          messages = new ArrayList<>();
        }
        messages.add(violation.getMessage());
      }
      else {
        if (errors == null) {
          errors = new HashMap<>();
        }
        errors.put(Joiner.on('.').join(entries), violation.getMessage());
      }
    }
  }
  else if (cause.getMessage() != null) {
    messages = new ArrayList<>();
    messages.add(cause.getMessage());
  }
}
 
@Override
public Response toResponse(ConstraintViolationException exception) {
    // start with the overall message which will be something like "Cannot create xyz"
    final StringBuilder errorMessage = new StringBuilder(exception.getMessage()).append(" - ");

    boolean first = true;
    for (final ConstraintViolation violation : exception.getConstraintViolations()) {
        if (!first) {
            errorMessage.append(", ");
        }
        first = false;

        // lastNode should end up as the field that failed validation
        Path.Node lastNode = null;
        for (final Path.Node node : violation.getPropertyPath()) {
            lastNode = node;
        }

        // append something like "xyz must not be..."
        errorMessage.append(lastNode.getName()).append(" ").append(violation.getMessage());
    }

    logger.info(String.format("%s. Returning %s response.", errorMessage, Response.Status.BAD_REQUEST));
    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage.toString()).type("text/plain").build();
}
 
private void validateInstance(Object instance) {
    if (!ValidationMode.NONE.equals(xoUnit.getValidationMode())) {
        Set<ConstraintViolation<Object>> constraintViolations = sessionContext.getInstanceValidationService().validate(instance);
        if (!constraintViolations.isEmpty()) {
            throw new ConstraintViolationException(constraintViolations);
        }
    }
}
 
@Test
void whenInputIsInvalidForUpdate_thenThrowsException() {
  InputWithCustomValidator input = validInput();
  input.setId(null);
  assertThrows(ConstraintViolationException.class, () -> {
    service.validateForUpdate(input);
  });
}
 
源代码21 项目: nfse   文件: RpsTomadorCpfCnpjTest.java
@Test(expected = ConstraintViolationException.class)
public void naoDevePermitirDocumentoComTamanhoInvalido() throws Exception {
  try {
    new TomadorCpfCnpjBuilder().comDocumento("1234567890").build();
  } catch (final ConstraintViolationException e) {
    new TomadorCpfCnpjBuilder().comDocumento("123456789090").build();
  }
}
 
源代码22 项目: mamute   文件: InternalErrorInterceptor.java
@Override
public void intercept(InterceptorStack stack, ControllerMethod method,
		Object instance) throws InterceptionException {
	try {
		stack.next(method, instance);
	}catch (Exception e) {
		
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		
		Throwable cause = e.getCause();
		if(cause != null){
			if (cause instanceof ConstraintViolationException) {
				Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) cause).getConstraintViolations();
				pw.printf("\nConstraint Violations: \n");
				for (ConstraintViolation<?> constraintViolation : constraintViolations) {
					pw.printf("\t" +constraintViolation.getConstraintDescriptor().getAnnotation()+"\n");
				}
				pw.printf("\n");
				log.error(sw.toString());
			}
			cause.printStackTrace(pw);
		}else{
			e.printStackTrace(pw);
		}
		
		pw.close();
		result.include("stacktrace", sw.toString());
		throw e;
	}
}
 
源代码23 项目: dcos-commons   文件: WriteOnceLinkedHashMap.java
@Override
public V put(K key, V value) {
  if (super.containsKey(key)) {
    HashSet<ConstraintViolation<String>> violations = new HashSet<>();
    violations.add(new DuplicateKeyConstraintViolation(key + ""));
    throw new ConstraintViolationException("Duplicate key: " + key, violations);
  }
  return super.put(key, value);
}
 
源代码24 项目: jweb-cms   文件: ValidationExceptionMapper.java
@Override
public Response toResponse(ValidationException exception) {
    ValidationExceptionResponse response = new ValidationExceptionResponse();
    if (exception instanceof ConstraintViolationException) {
        ConstraintViolation<?> violation = ((ConstraintViolationException) exception).getConstraintViolations().iterator().next();
        response.path = violation.getPropertyPath().toString();
        response.errorMessage = violation.getMessage();
    } else {
        response.errorMessage = exception.getMessage();
    }
    return Response.status(400).entity(response)
        .type(MediaType.APPLICATION_JSON).build();
}
 
@AroundInvoke
@Override
public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
    try {
        return super.validateMethodInvocation(ctx);
    } catch (ConstraintViolationException e) {
        throw new ResteasyViolationExceptionImpl(e.getConstraintViolations(), getAccept(ctx.getMethod()));
    }
}
 
源代码26 项目: spring-boot-jpa   文件: PatientRepositoryTests.java
@Test
public void test_PatientRepository_SaveWithEmpty_ExpectException() throws Exception {
    ConstraintViolationException exception =
assertThrows(ConstraintViolationException.class,
		() -> patientRepository.saveAndFlush(new Patient()));

    assertThat(exception).hasMessageContaining("'must not be blank'");
}
 
源代码27 项目: dubbo-2.6.5   文件: RpcExceptionMapper.java
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 现在只执行xml输出
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(report).type(ContentType.TEXT_XML_UTF_8).build();
}
 
源代码28 项目: activiti6-boot2   文件: UsersResource.java
/**
 * POST  /rest/users -> create a new user.
 */
@RequestMapping(value = "/rest/users", method = RequestMethod.POST)
@ResponseStatus(value = HttpStatus.NO_CONTENT)
public void createUser(@RequestBody UserRepresentation userRepresentation) {
    log.debug("REST request to create a User : {}");

        // all users are admins
    userRepresentation.setIsAdmin(true);

    if (userRepresentation.getLogin() == null) {
        throw new BadRequestException("user login is required");
    }
    
    if (userRepresentation.getPassword() == null) {
        throw new BadRequestException("a password is required");
    }
    
    try {
        User result = userService.createUser(userRepresentation);
        if(result == null) {
            throw new ConflictException("User with login '" + userRepresentation.getLogin() + "' already exists.");
        }
    } catch (IllegalArgumentException iae) {
        throw new BadRequestException(iae.getMessage());
    } catch (ConstraintViolationException cv) {
        String message = "Invalid user details";
        if (cv.getConstraintViolations().size() > 0) {
            message = cv.getConstraintViolations().iterator().next().getMessage();
        }
        throw new BadRequestException(message);
    }
    
}
 
@Test
public void shouldValidateDeviceId() {
  // given
  final Installation installation = new Installation();
  installation.setDeviceToken("invalid");

  final iOSVariant variant = new iOSVariant();
  variant.setName("iOS Variant Name");
  variant.setPassphrase("12");
  variant.setProduction(false);
  variant.setCertificate("12".getBytes());
  entityManager.persist(variant);
  installation.setVariant(variant);

  // when
  installationDao.create(installation);
  try {
    entityManager.flush();
    fail("ConstraintViolationException should have been thrown");
  } catch (ConstraintViolationException violationException) {
    // then
    final Set<ConstraintViolation<?>> constraintViolations = violationException
        .getConstraintViolations();
    assertThat(constraintViolations).isNotEmpty();
    assertThat(constraintViolations.size()).isEqualTo(1);

    assertThat(constraintViolations.iterator().next().getMessage()).isEqualTo(
        "Device token is not valid for this device type");
  }
}
 
源代码30 项目: genie   文件: BaseEntityTest.java
/**
 * Test to make sure validation works and throws exception when no name entered.
 */
@Test
void testValidateNoVersion() {
    this.b.setVersion("");
    Assertions
        .assertThatExceptionOfType(ConstraintViolationException.class)
        .isThrownBy(() -> this.validate(this.b));
}