繁体   English   中英

限制基于CXF JAX-RS的服务中的输出有效负载响应

[英]Limit output payload response in CXF JAX-RS based service

我有多个使用cxf / spring构建的jax-rs服务。 我想控制所有服务的输出有效负载响应大小。 为了简单起见,假设任何服务中的api都不应该返回超过500个字符的JSON响应有效负载,我想在一个地方进行控制,而不是依赖单个服务来满足此要求。 (我们已经在所有服务所依赖的自定义框架/基本组件中内置了其他功能)。

我尝试使用JAX-RS的WriterInterceptorContainerResponseFilter和CXF的Phase Interceptor来实现此WriterInterceptor ,但是似乎没有一种方法可以完全满足我的要求。 到目前为止我所做的更多详细信息:

选项1:(WriterInteceptor)在重写的方法中,我获得输出流并将缓存的最大大小设置为500。当我调用一个在响应有效负载中返回500个以上字符的api时,我将获得HTTP 400错误请求状态,但响应主体包含整个JSON有效负载。

@Provider
public class ResponsePayloadInterceptor implements WriterInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponsePayloadInterceptor.class);

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        final OutputStream outputStream = context.getOutputStream();

        CacheAndWriteOutputStream cacheAndWriteOutputStream = new CacheAndWriteOutputStream(outputStream);
        cacheAndWriteOutputStream.setMaxSize(500);
        context.setOutputStream(cacheAndWriteOutputStream);

        context.proceed();
    }
}

选项2a:(CXF相位接收器)在重写方法中,我从输出流中获取响应作为String并检查其大小。 如果大于500,我将创建一个新的Response对象,其中仅包含数据Too many data并将其设置在消息中。 即使响应> 500个字符,我也会获得整个JSON的HTTP 200 OK状态。 只有当我将该阶段用作POST_MARSHAL或以后的阶段时,我才能掌握JSON响应并检查其长度,但是到那时,响应已被流式传输到客户端。

@Provider
public class ResponsePayloadInterceptor extends AbstractPhaseInterceptor<Message> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponsePayloadInterceptor.class);

    public ResponsePayloadInterceptor() {
        super(Phase.POST_MARSHAL);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        LOGGER.info("handleMessage() - Response intercepted");
        try {
            OutputStream outputStream = message.getContent(OutputStream.class);
...
            CachedOutputStream cachedOutputStream = (CachedOutputStream) outputStream;
            String responseBody = IOUtils.toString(cachedOutputStream.getInputStream(), "UTF-8");
...
            LOGGER.info("handleMessage() - Response: {}", responseBody);
            LOGGER.info("handleMessage() - Response Length: {}", responseBody.length());
            if (responseBody.length() > 500) {
                Response response = Response.status(Response.Status.BAD_REQUEST)
                                            .entity("Too much data").build();
                message.getExchange().put(Response.class, response);
            }
        } catch (IOException e) {
            LOGGER.error("handleMessage() - Error");
            e.printStackTrace();
        }
    }
}

选项2b:(CXF相位接收器)与上面相同,但仅if块的内容已更改。 如果响应长度大于500,我将创建一个新的输出流,其字符串为Too too data ,并将其设置为message。 但是,如果响应的有效载荷大于500个字符,我仍然会收到HTTP 200 OK状态,其中包含无效的JSON响应(整个JSON +其他文本),即响应看起来像这样: [{"data":"", ...}, {...}]Too much data (JSON中附加了文本“数据太多”)

        if (responseBody.length() > 500) {
            InputStream inputStream = new ByteArrayInputStream("Too much data".getBytes("UTF-8"));
            outputStream.flush();
            IOUtils.copy(inputStream, outputStream);

            OutputStream out = new CachedOutputStream();
            out.write("Too much data".getBytes("UTF-8"));
            message.setContent(OutputStream.class, out);
        }

选项3:(ContainerResponseFilter)使用ContainerResponseFilter,我添加了一个Content-Length响应标头,其值为500。如果响应长度> 500,我将获得HTTP 200 OK状态以及无效的JSON响应(截断为500个字符)。 如果响应长度小于500,则仍将显示HTTP 200 OK状态,但是客户端将等待服务器返回更多数据(如预期)并超时,这不是理想的解决方案。

@Provider
public class ResponsePayloadFilter implements ContainerResponseFilter {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponsePayloadFilter.class);

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        LOGGER.info("filter() - Response intercepted");
        CachedOutputStream cos = (CachedOutputStream) responseContext.getEntityStream();
        StringBuilder responsePayload = new StringBuilder();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        if (cos.getInputStream().available() > 0) {
            IOUtils.copy(cos.getInputStream(), out);
            byte[] responseEntity = out.toByteArray();
            responsePayload.append(new String(responseEntity));
        }

        LOGGER.info("filter() - Content: {}", responsePayload.toString());
        responseContext.getHeaders().add("Content-Length", "500");
    }
}

关于如何调整上述方法以获得所需的任何建议或任何其他不同的指示?

我使用此答案的帮助部分解决了此问题 我之所以这么说是部分原因是因为我能够成功控制有效负载,但不能控制响应状态代码。 理想情况下,如果响应长度大于500,并且我修改了消息内容,则我想发送其他响应状态代码(不是200 OK)。 但这对我来说是一个很好的解决方案。 如果我也想知道如何更新状态码,我将返回并更新此答案。

import org.apache.commons.io.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ResponsePayloadInterceptor extends AbstractPhaseInterceptor<Message> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResponsePayloadInterceptor.class);

    public ResponsePayloadInterceptor() {
        super(Phase.PRE_STREAM);
    }

    @Override
    public void handleMessage(Message message) throws Fault {
        LOGGER.info("handleMessage() - Response intercepted");
        try {
            OutputStream outputStream = message.getContent(OutputStream.class);
            CachedOutputStream cachedOutputStream = new CachedOutputStream();
            message.setContent(OutputStream.class, cachedOutputStream);

            message.getInterceptorChain().doIntercept(message);

            cachedOutputStream.flush();
            cachedOutputStream.close();

            CachedOutputStream newCachedOutputStream = (CachedOutputStream) message.getContent(OutputStream.class);
            String currentResponse = IOUtils.toString(newCachedOutputStream.getInputStream(), "UTF-8");
            newCachedOutputStream.flush();
            newCachedOutputStream.close();

            if (currentResponse != null) {
                LOGGER.info("handleMessage() - Response: {}", currentResponse);
                LOGGER.info("handleMessage() - Response Length: {}", currentResponse.length());

                if (currentResponse.length() > 500) {
                    InputStream replaceInputStream = IOUtils.toInputStream("{\"message\":\"Too much data\"}", "UTF-8");

                    IOUtils.copy(replaceInputStream, outputStream);
                    replaceInputStream.close();

                    message.setContent(OutputStream.class, outputStream);
                    outputStream.flush();
                    outputStream.close();
                } else {
                    InputStream replaceInputStream = IOUtils.toInputStream(currentResponse, "UTF-8");

                    IOUtils.copy(replaceInputStream, outputStream);
                    replaceInputStream.close();

                    message.setContent(OutputStream.class, outputStream);
                    outputStream.flush();
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            LOGGER.error("handleMessage() - Error", e);
            throw new RuntimeException(e);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM