|
From: Sebastian G. <s.g...@go...> - 2014-11-16 13:44:25
|
Hey,
I am using RestEasy 3.0.9 to implement a client for a remote endpoint. This endpoint consumes application/x-www-form-urlencoded.
I am currently writing an WriterInterceptor which should basically log the requests bodies I am sending. The interceptor looks like this:
import com.google.common.base.Charsets;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.TeeOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Provider
public class WriterLoggingInterceptor implements WriterInterceptor {
private final Logger log;
public WriterLoggingInterceptor(final String loggerName) {
log = LoggerFactory.getLogger(loggerName);
}
@SuppressWarnings("try")
@Override
public void aroundWriteTo(final WriterInterceptorContext context) throws IOException, WebApplicationException {
try (
final OutputStream originalOutputStream = context.getOutputStream();
final PipedInputStream sinkInputStream = new PipedInputStream();
final OutputStream forkedOutputStream = new PipedOutputStream(sinkInputStream);
final TeeOutputStream teeOutputStream = new TeeOutputStream(originalOutputStream, forkedOutputStream);
) {
context.setOutputStream(teeOutputStream);
context.proceed();
// why is this necessary?
teeOutputStream.close();
final String body = IOUtils.toString(sinkInputStream, Charsets.UTF_8);
log.trace(body);
}
}
}
Everything with the above code is working fine, except for the weirdness that I have to close the OutputStream, because if I don’t I will be waiting infinitely for the stream to close or provide new data when reading from it.
For some reason the FormUrlEncodedProvider does not close the OutputStream, which is why I am forced to do this.
Is this a bug or am I missing something here? I would expected that any MessageBodyWriter implementation is required to close the OutputStream once it is done with its work.
Cheers!
Sebastian
|