Dilini Rajapaksha
Dilini Rajapaksha

Reputation: 2718

Retrieve the entity in Resteasy PreProcessInterceptor

I am using the resteasy PreProcessInterceptor for logging the request and could not find a way to get hold of the entity or the json object in a POST request. Is it possible to get the entity or the json object at this level? I am using Resteasy 2.3.6

Upvotes: 0

Views: 580

Answers (1)

lefloh
lefloh

Reputation: 10961

You can get the posted entity from request.getInputStream() but note that an InputStream can't be read twice. An easy (but maybe not the most performant) way is to copy the InputStream:

@Provider
public class LoggingInterceptor implements PreProcessInterceptor {

    private static final Logger LOG = LoggerFactory.getLogger(LoggingInterceptor.class);

    @Override
    public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException {
        if ("POST".equals(request.getHttpMethod()) && request.getInputStream() != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                IOUtils.copy(request.getInputStream(), baos);
                byte[] bytes = baos.toByteArray();
                LOG.info("Posted: " + new String(bytes, "UTF-8"));
                request.setInputStream(new ByteArrayInputStream(bytes));
            } catch (IOException ex) {
                throw new WebApplicationException(ex);
            }
        }
        return null;
    }

}

If you are using Resteasy 3.x you should use a ContainerRequestFilter.

Upvotes: 1

Related Questions