org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException Java Examples

The following examples show how to use org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException. 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: KafkaDeadLetterBatchErrorHandler.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Exception thrownException, ConsumerRecords<?, ?> data) {
    thrownException.printStackTrace();
    log.error(handleLogMessage(thrownException));
    if (thrownException.getCause() instanceof MethodArgumentNotValidException) {
        return;
    }
    Set<TopicPartition> topicPartitions = data.partitions();
    log.error("send failed message to dead letter");
    for (TopicPartition topicPartition : topicPartitions) {
        List<? extends ConsumerRecord<?, ?>> list = data.records(topicPartition);
        for (ConsumerRecord<?, ?> consumerRecord : list) {
            deadLetterPublishingRecoverer.accept(consumerRecord, thrownException);
        }
    }
    log.error("send failed message to dead letter successful");
}
 
Example #2
Source File: KafkaLoggingErrorHandler.java    From faster-framework-project with Apache License 2.0 6 votes vote down vote up
default String handleLogMessage(Exception thrownException) {
    StringBuilder errorMsg = new StringBuilder();
    if (thrownException.getCause() instanceof MethodArgumentNotValidException) {
        errorMsg.append("kafka listener arguments not valid:");
        MethodArgumentNotValidException methodArgumentNotValidException = ((MethodArgumentNotValidException) thrownException.getCause());
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        if (bindingResult == null) {
            errorMsg.append(methodArgumentNotValidException.getLocalizedMessage());
        } else {
            errorMsg.append(BindingResultErrorUtils.resolveErrorMessage(bindingResult));
        }
    } else {
        errorMsg.append("kafka listener exception:").append(thrownException.getLocalizedMessage());
    }
    return errorMsg.toString();
}
 
Example #3
Source File: StreamListenerAnnotatedMethodArgumentsTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidAnnotationAtMethodParameterWithPojoThatFailsValidation() {
	ConfigurableApplicationContext context = SpringApplication.run(
			TestPojoWithValidAnnotationThatPassesValidation.class, "--server.port=0");

	Sink sink = context.getBean(Sink.class);
	try {
		sink.input().send(MessageBuilder.withPayload("{\"foo\":\"\"}")
				.setHeader("contentType", MimeType.valueOf("application/json"))
				.build());
		fail("Exception expected: MethodArgumentNotValidException!");
	}
	catch (MethodArgumentNotValidException e) {
		assertThat(e.getMessage()).contains(
				"default message [foo]]; default message [must not be blank]]");
	}
	context.close();
}
 
Example #4
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
	if (this.validator == null) {
		return null;
	}
	for (Annotation ann : parameter.getParameterAnnotations()) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			String name = Conventions.getVariableNameForParameter(parameter);
			return target -> {
				BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name);
				if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
					((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
				}
				else {
					this.validator.validate(target, bindingResult);
				}
				if (bindingResult.hasErrors()) {
					throw new MethodArgumentNotValidException(message, parameter, bindingResult);
				}
			};
		}
	}
	return null;
}
 
Example #5
Source File: PayloadMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void validateStringMono() {
	TestValidator validator = new TestValidator();
	ResolvableType type = ResolvableType.forClassWithGenerics(Mono.class, String.class);
	MethodParameter param = this.testMethod.arg(type);
	Mono<Object> mono = resolveValue(param, Mono.just(toDataBuffer("12345")), validator);

	StepVerifier.create(mono).expectNextCount(0)
			.expectError(MethodArgumentNotValidException.class).verify();
}
 
Example #6
Source File: PayloadMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void validateStringFlux() {
	TestValidator validator = new TestValidator();
	ResolvableType type = ResolvableType.forClassWithGenerics(Flux.class, String.class);
	MethodParameter param = this.testMethod.arg(type);
	Flux<DataBuffer> content = Flux.just(toDataBuffer("12345678"), toDataBuffer("12345"));
	Flux<Object> flux = resolveValue(param, content, validator);

	StepVerifier.create(flux)
			.expectNext("12345678")
			.expectError(MethodArgumentNotValidException.class)
			.verify();
}
 
Example #7
Source File: EnableJmsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Test
public void jmsHandlerMethodFactoryConfiguration() throws JMSException {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			EnableJmsHandlerMethodFactoryConfig.class, ValidationBean.class);

	assertThatExceptionOfType(ListenerExecutionFailedException.class).isThrownBy(() ->
			testJmsHandlerMethodFactoryConfiguration(context))
		.withCauseInstanceOf(MethodArgumentNotValidException.class);
}
 
Example #8
Source File: AnnotationDrivenNamespaceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
@Test
public void jmsHandlerMethodFactoryConfiguration() throws JMSException {
	ApplicationContext context = new ClassPathXmlApplicationContext(
			"annotation-driven-custom-handler-method-factory.xml", getClass());

	assertThatExceptionOfType(ListenerExecutionFailedException.class).isThrownBy(() ->
			testJmsHandlerMethodFactoryConfiguration(context))
		.withCauseInstanceOf(MethodArgumentNotValidException.class);
}
 
Example #9
Source File: MethodArgumentNotValidExceptionMapper.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
protected Object getEntity(MethodArgumentNotValidException exception) {
    ValidationResult result = new ValidationResult();
    for (FieldError err : exception.getBindingResult().getFieldErrors()) {
        result.addValidationError(err.getField(), err.getDefaultMessage());
    }
    return result;
}
 
Example #10
Source File: EnableJmsTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Test
public void jmsHandlerMethodFactoryConfiguration() throws JMSException {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			EnableJmsHandlerMethodFactoryConfig.class, ValidationBean.class);

	thrown.expect(ListenerExecutionFailedException.class);
	thrown.expectCause(Is.<MethodArgumentNotValidException>isA(MethodArgumentNotValidException.class));
	testJmsHandlerMethodFactoryConfiguration(context);
}
 
Example #11
Source File: AnnotationDrivenNamespaceTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
@Test
public void jmsHandlerMethodFactoryConfiguration() throws JMSException {
	ApplicationContext context = new ClassPathXmlApplicationContext(
			"annotation-driven-custom-handler-method-factory.xml", getClass());

	thrown.expect(ListenerExecutionFailedException.class);
	thrown.expectCause(Is.<MethodArgumentNotValidException>isA(MethodArgumentNotValidException.class));
	testJmsHandlerMethodFactoryConfiguration(context);
}
 
Example #12
Source File: KafkaDeadLetterErrorHandler.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Exception thrownException, ConsumerRecord<?, ?> data) {
    thrownException.printStackTrace();
    log.error(handleLogMessage(thrownException));
    if (thrownException.getCause() instanceof MethodArgumentNotValidException) {
        return;
    }
    log.error("send failed message to dead letter");
    deadLetterPublishingRecoverer.accept(data, thrownException);
    log.error("send failed message to dead letter successful");
}
 
Example #13
Source File: EnableJmsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@Test
public void jmsHandlerMethodFactoryConfiguration() throws JMSException {
	ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
			EnableJmsHandlerMethodFactoryConfig.class, ValidationBean.class);

	thrown.expect(ListenerExecutionFailedException.class);
	thrown.expectCause(Is.<MethodArgumentNotValidException>isA(MethodArgumentNotValidException.class));
	testJmsHandlerMethodFactoryConfiguration(context);
}
 
Example #14
Source File: AnnotationDrivenNamespaceTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
@Test
public void jmsHandlerMethodFactoryConfiguration() throws JMSException {
	ApplicationContext context = new ClassPathXmlApplicationContext(
			"annotation-driven-custom-handler-method-factory.xml", getClass());

	thrown.expect(ListenerExecutionFailedException.class);
	thrown.expectCause(Is.<MethodArgumentNotValidException>isA(MethodArgumentNotValidException.class));
	testJmsHandlerMethodFactoryConfiguration(context);
}
 
Example #15
Source File: MethodArgumentNotValidExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
Class<MethodArgumentNotValidException> getExceptionType() {
    return MethodArgumentNotValidException.class;
}
 
Example #16
Source File: SmartPayloadArgumentResolver.java    From spring-cloud-stream with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, Message<?> message)
		throws Exception {
	Payload ann = parameter.getParameterAnnotation(Payload.class);
	if (ann != null && StringUtils.hasText(ann.expression())) {
		throw new IllegalStateException(
				"@Payload SpEL expressions not supported by this resolver");
	}

	Object payload = message.getPayload();
	if (isEmptyPayload(payload)) {
		if (ann == null || ann.required()) {
			String paramName = getParameterName(parameter);
			BindingResult bindingResult = new BeanPropertyBindingResult(payload,
					paramName);
			bindingResult.addError(
					new ObjectError(paramName, "Payload value must not be empty"));
			throw new MethodArgumentNotValidException(message, parameter,
					bindingResult);
		}
		else {
			return null;
		}
	}

	Class<?> targetClass = parameter.getParameterType();
	Class<?> payloadClass = payload.getClass();
	if (conversionNotRequired(payloadClass, targetClass)) {
		validate(message, parameter, payload);
		return payload;
	}
	else {
		if (this.messageConverter instanceof SmartMessageConverter) {
			SmartMessageConverter smartConverter = (SmartMessageConverter) this.messageConverter;
			payload = smartConverter.fromMessage(message, targetClass, parameter);
		}
		else {
			payload = this.messageConverter.fromMessage(message, targetClass);
		}
		if (payload == null) {
			throw new MessageConversionException(message,
					"Cannot convert from [" + payloadClass.getName() + "] to ["
							+ targetClass.getName() + "] for " + message);
		}
		validate(message, parameter, payload);
		return payload;
	}
}
 
Example #17
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@MessageExceptionHandler(MethodArgumentNotValidException.class)
public void handleValidationException() {
	this.method = "handleValidationException";
}
 
Example #18
Source File: SimpAnnotationMethodMessageHandlerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@MessageExceptionHandler(MethodArgumentNotValidException.class)
public void handleValidationException() {
	this.method = "handleValidationException";
}
 
Example #19
Source File: SimpAnnotationMethodMessageHandlerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@MessageExceptionHandler(MethodArgumentNotValidException.class)
public void handleValidationException() {
	this.method = "handleValidationException";
}