package eu.eudat.controllers.controllerhandler; import eu.eudat.commons.validation.Validator; import eu.eudat.commons.validation.ValidatorFactory; import eu.eudat.commons.validation.ValidationFilterAnnotation; import gr.cite.tools.exception.MyApplicationException; import org.springframework.core.MethodParameter; import org.springframework.http.HttpInputMessage; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice; import java.io.IOException; import java.lang.reflect.Type; import java.util.Objects; @ControllerAdvice @RestControllerAdvice public class ValidatorRequestBodyAdvice implements RequestBodyAdvice { private final ValidatorFactory validatorFactory; public ValidatorRequestBodyAdvice(ValidatorFactory validatorFactory) { this.validatorFactory = validatorFactory; } @Override public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { if (parameter.getMethod() != null) { ValidationFilterAnnotation[] annotations = parameter.getMethod().getAnnotationsByType((ValidationFilterAnnotation.class)); if (annotations == null) return body; for (ValidationFilterAnnotation annotation : annotations){ if (!Objects.equals(parameter.getParameterName(), annotation.argumentName())) continue; Validator validator = validatorFactory.validator(annotation.validator()); if (validator == null) throw new MyApplicationException("validator not provided"); validator.validateForce(body); } } return body; } @Override public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) { return body; } @Override public boolean supports(MethodParameter parameter, Type targetType, Class> converterType) { return parameter.getMethod() != null && parameter.getMethod().isAnnotationPresent((ValidationFilterAnnotation.class)); } @Override public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class> converterType) throws IOException { return inputMessage; } }