There has to be a simple answer to this... I have a servlet that serves a
PNG file if it exists, and if it doesn't, throws an HTTP 404 error and
serves a default image. In the second case, I get the default image but I
see this in the logs. I checked and couldn't find an obvious way to set
the HTTP status code without committing the response...
2015-01-28
14:35:06.318:WARN:oejs.ServletHandler:/featured-event-image/event1-1.png
java.lang.IllegalStateException:
Committed
at
org.eclipse.jetty.server.Response.resetBuffer(Response.java:1090)
at
org.eclipse.jetty.server.Response.reset(Response.java:1034)
at
com.mymitzvahdate.servlet.FeaturedEventImage.doGet(FeaturedEventImage.java:53)
This is the servlet:
package
com.mymitzvahdate.servlet;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.file.Files;
import
javax.servlet.ServletException;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;
import
com.mymitzvahdate.Constants;
import
com.mymitzvahdate.persistence.Globals;
public class FeaturedEventImage
extends HttpServlet {
public static final long
serialVersionUID = 1L;
// Properties
---------------------------------------------------------------------------------
private String imagePath,
defaultImagePath;
// Actions
------------------------------------------------------------------------------------
protected void
doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
imagePath =
Globals.get(Constants.GLOBAL_FEATURED_IMAGE_DIR);
defaultImagePath =
Globals.get(Constants.GLOBAL_DEFAULT_FEATURED_IMAGE);
// Get requested image
by path info.
String requestedImage =
request.getPathInfo();
// Check if file name is
actually supplied to the request URI.
if (requestedImage ==
null) {
sendErrorAndDefaultPNG(response);
}
// Decode the file name
String imageFilename =
URLDecoder.decode(requestedImage, "UTF-8");
// chop off the
extension if one exists
if
(imageFilename.lastIndexOf(".")> -1) imageFilename =
imageFilename.substring(0,imageFilename.lastIndexOf("."));
File image = new
File(imagePath, imageFilename + ".jpg");
// Check if file
actually exists in filesystem.
if (!image.exists()) {
sendErrorAndDefaultPNG(response);
}
response.reset();
sendImage(response,
image);
}
private void
sendImage(HttpServletResponse response, File image) {
response.setContentType("image/png");
response.setHeader("Content-Length", String.valueOf(image.length()));
try {
Files.copy(image.toPath(), response.getOutputStream());
} catch(IOException exc)
{
}
}
private void
sendErrorAndDefaultPNG(HttpServletResponse response) {
response.reset();
response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 404.
File errorImage = new
File(imagePath, defaultImagePath);
sendImage(response,
errorImage);
return;
}
}
Thanks for whatever help you can offer
|