I’m working on a java project, and now I have been asked to track how much data is sent to and from our server. So I’ve written a filter and mapped it to all the calls it should be monitoring as other people told me to do. This filter works as it should, but i’m having problems getting the size of the response. This is my basic implementation of the doFilter and i’m using a wrapper for the response.
DoFilter:
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (filterConfig == null)
return;
LogResponseWrapper logResponseWrapper = new LogResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, logResponseWrapper);
}
Wrapper based upon examples online:
public class LogResponseWrapper extends HttpServletResponseWrapper
{
public long size = 0;
public PrintWriter myWriter = null;
public OutputStream myOutputStream = null;
LogResponseWrapper(HttpServletResponse response)
{
super(response);
}
@Override
public PrintWriter getWriter()
{
PrintWriter writer = null;
try
{
System.out.println("calling the writer");
writer = super.getWriter();
myWriter = writer;
}
catch (Exception e)
{
e.printStackTrace();
}
return writer;
}
@Override
public ServletOutputStream getOutputStream()
{
ServletOutputStream os = null;
try
{
System.out.println("calling the getOutputStream");
os = super.getOutputStream();
myOutputStream = os;
}
catch (Exception e)
{
e.printStackTrace();
}
return os;
}
}
So, you see, this is very basic and does what it should do. But I seem to be unable to find out how many bytes have been transfered to the response after the chain.doFilter has been called. I’ve tried converting it to a DataOutputStream and ByteArrayOutputStream as others have suggested, but that didn’t work either. So If anyone has any pointers on how to do this, feel free to help me out.
Thank you in advance.
Let’s assume that all output is done using the output stream (not really sure of that, maybe the writer gets to write directly too). Then you have to provide a proxy that actually increments your “size” counter. Beware that this may impact performance.
You would then return a
new MyOutputStream(super.getOutputStream())instead ofsuper.getOutputStream(), where MyOutputStream is a proxy that updates your totals when it gets closed. Example code (warning: not tested):the magic is in the “updateTotals” – which is where you update your LogResponseWrapper’s size. If this is going to be executed in a multithreaded environment, you should add synchronization to avoid race conditions.