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

The following examples show how to use org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException. These examples are extracted from open source projects. 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
@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
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
@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
@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
@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
@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 Project: spring-analysis-note   Source File: EnableJmsTests.java    License: 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
@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 Project: java-technology-stack   Source File: EnableJmsTests.java    License: 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 10
@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 11
@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 12
Source Project: spring4-understanding   Source File: EnableJmsTests.java    License: 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 13
@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 14
@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 15
@MessageExceptionHandler(MethodArgumentNotValidException.class)
public void handleValidationException() {
	this.method = "handleValidationException";
}
 
Example 16
@MessageExceptionHandler(MethodArgumentNotValidException.class)
public void handleValidationException() {
	this.method = "handleValidationException";
}
 
Example 17
@MessageExceptionHandler(MethodArgumentNotValidException.class)
public void handleValidationException() {
	this.method = "handleValidationException";
}
 
Example 18
@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 19
@Override
Class<MethodArgumentNotValidException> getExceptionType() {
    return MethodArgumentNotValidException.class;
}