79440419

Date: 2025-02-14 19:42:48
Score: 0.5
Natty:
Report link

What I ended up doing was converting from an implementation of Filter to an implementation of RequestBodyAdvice as outlined below:

@Component
@ControllerAdvice
@RequiredArgsConstructor
@Slf4j
public class RequestSizeAdvice implements RequestBodyAdvice {

@Value("${fam.max_request_size:10485760}")
private int maxContentBytes;

@Override
public boolean supports(MethodParameter methodParameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
}

@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
        Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
    return inputMessage;
}

@Override
public Object afterBodyRead(Object body, HttpInputMessage inputMessage,
        MethodParameter parameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {
    String bodyString = "";
    try {
        bodyString = new Gson().toJson(body);
    } catch (OutOfMemoryError e) {
        throw new MaxSizeExceededException("Unable to calculate body size. Maximum size is %s".formatted(maxContentBytes));
    }
    long bodySize = bodyString.getBytes().length;
    if (bodySize > maxContentBytes) {
        throw new MaxSizeExceededException("Body size %s greater than maximum %s".formatted(bodySize, maxContentBytes));
    }
    return body;
}

@Override
public Object handleEmptyBody(Object body, HttpInputMessage inputMessage,
        MethodParameter parameter, Type targetType,
        Class<? extends HttpMessageConverter<?>> converterType) {
    return body;
}
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Starts with a question (0.5): What I
  • Low reputation (1):
Posted by: Steve Gazzo