// cast once
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse res = (HttpServletResponse)response;
// indicate that we're in SSI processing
req.setAttribute(Globals.SSI_FLAG_ATTR, "true");
// setup to capture output
ByteArrayServletOutputStream basos = new ByteArrayServletOutputStream();
ResponseIncludeWrapper responseIncludeWrapper =
new ResponseIncludeWrapper(config.getServletContext(),req, res, basos);
// process remainder of filter chain
chain.doFilter(req, responseIncludeWrapper);
// we can't assume the chain flushed its output
responseIncludeWrapper.flushOutputStreamOrWriter();
byte[] bytes = basos.toByteArray();
// get content type
String contentType = responseIncludeWrapper.getContentType();
// is this an allowed type for SSI processing?
if (contentTypeRegEx.matcher(contentType).matches()) {
String encoding = res.getCharacterEncoding();
// set up SSI processing
SSIExternalResolver ssiExternalResolver =
new SSIServletExternalResolver(config.getServletContext(), req,
res, isVirtualWebappRelative, debug, encoding);
SSIProcessor ssiProcessor = new SSIProcessor(ssiExternalResolver,
debug);
// prepare readers/writers
Reader reader =
new InputStreamReader(new ByteArrayInputStream(bytes), encoding);
ByteArrayOutputStream ssiout = new ByteArrayOutputStream();
PrintWriter writer =
new PrintWriter(new OutputStreamWriter(ssiout, encoding));
// do SSI processing
long lastModified = ssiProcessor.process(reader,
responseIncludeWrapper.getLastModified(), writer);
// set output bytes
writer.flush();
bytes = ssiout.toByteArray();
// override headers
if (expires != null) {
res.setDateHeader("expires", (new java.util.Date()).getTime()
+ expires.longValue() * 1000);
}
if (lastModified > 0) {
res.setDateHeader("last-modified", lastModified);
}
res.setContentLength(bytes.length);
Matcher shtmlMatcher =
shtmlRegEx.matcher(responseIncludeWrapper.getContentType());
if (shtmlMatcher.matches()) {
// Convert shtml mime type to ordinary html mime type but preserve
// encoding, if any.
String enc = shtmlMatcher.group(1);
res.setContentType("text/html" + ((enc != null) ? enc : ""));
}
}
// write output
OutputStream out = null;
try {
out = res.getOutputStream();
} catch (IllegalStateException e) {
// Ignore, will try to use a writer
}
if (out == null) {
res.getWriter().write(new String(bytes));
} else {
out.write(bytes);
}