if (!(res instanceof HttpServletResponse)) {
throw new ServletException("This filter only supports HTTP");
}
BufferedHttpResponseWrapper responseWrapper =
new BufferedHttpResponseWrapper((HttpServletResponse) res);
chain.doFilter(req, responseWrapper);
// Tomcat 4.0 reuses instances of its HttpServletResponse
// implementation class in some scenarios. For instance, hitting
// reload() repeatedly on a web browser will cause this to happen.
// Unfortunately, when this occurs, output is never written to the
// BufferedHttpResponseWrapper's OutputStream. This means that the
// XML output array is empty when this happens. The following
// code is a workaround:
byte[] origXML = responseWrapper.getBuffer();
if (origXML == null || origXML.length == 0) {
// just let Tomcat deliver its cached data back to the client
chain.doFilter(req, res);
return;
}
try {
// do the XSLT transformation
Transformer trans = StylesheetCache.newTransformer(
this.xsltFileName);
ByteArrayInputStream origXMLIn = new ByteArrayInputStream(origXML);
Source xmlSource = new StreamSource(origXMLIn);
ByteArrayOutputStream resultBuf = new ByteArrayOutputStream();
trans.transform(xmlSource, new StreamResult(resultBuf));
res.setContentLength(resultBuf.size());
res.setContentType("text/html");
res.getOutputStream().write(resultBuf.toByteArray());
res.flushBuffer();
} catch (TransformerException te) {
throw new ServletException(te);
}