All Downloads are FREE. Search and download functionalities are using the official Maven repository.

win.doyto.query.web.component.JsonResponseAdvice Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
// Generated by delombok at Sat Apr 04 14:54:36 CST 2020
package win.doyto.query.web.component;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import win.doyto.query.web.response.ErrorCode;
import win.doyto.query.web.response.JsonBody;
import win.doyto.query.web.response.JsonResponse;
import java.lang.reflect.Method;

/**
 * RestResponseAdvice
 *
 * @author f0rb on 2017-01-15.
 */
@ControllerAdvice
class JsonResponseAdvice implements ResponseBodyAdvice {
    @java.lang.SuppressWarnings("all")
    @lombok.Generated
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(JsonResponseAdvice.class);

    private static ErrorCode wrap(Object body) {
        if (body instanceof JsonResponse) {
            return (JsonResponse) body;
        } else {
            return ErrorCode.build(body);
        }
    }

    @Override
    public boolean supports(MethodParameter returnType, Class> converterType) {
        Method method = returnType.getMethod();
        Class declaringClass = method.getDeclaringClass();
        if (AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType) && (declaringClass.isAnnotationPresent(JsonBody.class) || method.isAnnotationPresent(JsonBody.class))) {
            log.debug("JsonResponse: {}.{}", declaringClass.getName(), method.getName());
            return true;
        }
        return false;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return wrap(body);
    }
}