@Override
protected ResourceResponse newResourceResponse(Attributes attributes)
{
final ResourceResponse resourceResponse = new ResourceResponse();
final IResourceStream resourceStream = getResourceStream();
// bail out if resource stream could not be found
if (resourceStream == null)
{
return sendResourceError(resourceResponse, HttpServletResponse.SC_NOT_FOUND,
"Unable to find resource");
}
// add Last-Modified header (to support HEAD requests and If-Modified-Since)
final Time lastModified = resourceStream.lastModifiedTime();
resourceResponse.setLastModified(lastModified);
if (resourceResponse.dataNeedsToBeWritten(attributes))
{
String contentType = resourceStream.getContentType();
if (contentType == null && Application.exists())
{
contentType = Application.get().getMimeType(path);
}
// set Content-Type (may be null)
resourceResponse.setContentType(contentType);
// set content encoding (may be null)
resourceResponse.setTextEncoding(getTextEncoding());
try
{
// read resource data
final byte[] bytes;
bytes = IOUtils.toByteArray(resourceStream.getInputStream());
final byte[] processed = processResponse(attributes, bytes);
// send Content-Length header
resourceResponse.setContentLength(processed.length);
// send response body with resource data
resourceResponse.setWriteCallback(new WriteCallback()
{
@Override
public void writeData(Attributes attributes)
{
attributes.getResponse().write(processed);
}
});
}
catch (IOException e)
{
log.debug(e.getMessage(), e);
return sendResourceError(resourceResponse, 500, "Unable to read resource stream");
}
catch (ResourceStreamNotFoundException e)
{
log.debug(e.getMessage(), e);
return sendResourceError(resourceResponse, 500, "Unable to open resource stream");
}
finally
{
try
{
resourceStream.close();
}
catch (IOException e)
{
log.warn("Unable to close the resource stream", e);
}