// Check if the request uri matches the special uri for images. If so, try
// to extract the id from the last part of the path. If not, check if there
// is an image with the current path.
ResourceURI imageURI = null;
ImageResource imageResource = null;
try {
String id = null;
String imagePath = null;
if (path.startsWith(URI_PREFIX)) {
String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");
// Check whether we are looking at a uuid or a url path
if (uriSuffix.length() == UUID_LENGTH) {
id = uriSuffix;
} else if (uriSuffix.length() >= UUID_LENGTH) {
int lastSeparator = uriSuffix.indexOf('/');
if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
id = uriSuffix.substring(0, lastSeparator);
fileName = uriSuffix.substring(lastSeparator + 1);
} else {
imagePath = uriSuffix;
fileName = FilenameUtils.getName(imagePath);
}
} else {
imagePath = "/" + uriSuffix;
fileName = FilenameUtils.getName(imagePath);
}
} else {
imagePath = path;
fileName = FilenameUtils.getName(imagePath);
}
// Try to load the resource
imageURI = new ImageResourceURIImpl(site, imagePath, id);
imageResource = contentRepository.get(imageURI);
if (imageResource == null) {
logger.debug("No image found at {}", imageURI);
return false;
}
} catch (ContentRepositoryException e) {
logger.error("Error loading image from {}: {}", contentRepository, e.getMessage());
DispatchUtils.sendInternalError(request, response);
return true;
} catch (UnsupportedEncodingException e) {
logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage());
DispatchUtils.sendInternalError(request, response);
return true;
}
// Agree to serve the image
logger.debug("Image handler agrees to handle {}", path);
// Check the request method. Only GET is supported right now.
String requestMethod = request.getMethod().toUpperCase();
if ("OPTIONS".equals(requestMethod)) {
String verbs = "OPTIONS,GET";
logger.trace("Answering options request to {} with {}", url, verbs);
response.setHeader("Allow", verbs);
response.setContentLength(0);
return true;
} else if (!"GET".equals(requestMethod)) {
logger.debug("Image request handler does not support {} requests", requestMethod);
DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
return true;
}
// Is it published?
// TODO: Fix this. imageResource.isPublished() currently returns false,
// as both from and to dates are null (see PublishingCtx)
// if (!imageResource.isPublished()) {
// logger.debug("Access to unpublished image {}", imageURI);
// DispatchUtils.sendNotFound(request, response);
// return true;
// }
// Can the image be accessed by the current user?
User user = request.getUser();
try {
// TODO: Check permission
// PagePermission p = new PagePermission(page, user);
// AccessController.checkPermission(p);
} catch (SecurityException e) {
logger.warn("Access to image {} denied for user {}", imageURI, user);
DispatchUtils.sendAccessDenied(request, response);
return true;
}
// Determine the response language by filename
Language language = null;
if (StringUtils.isNotBlank(fileName)) {
for (ImageContent c : imageResource.contents()) {
if (c.getFilename().equalsIgnoreCase(fileName)) {
if (language != null) {
logger.debug("Unable to determine language from ambiguous filename");
language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
break;
}
language = c.getLanguage();
}
}
if (language == null)
language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
} else {
language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
}
// If the filename did not lead to a language, apply language resolution
if (language == null) {
logger.warn("Image {} does not exist in any supported language", imageURI);
DispatchUtils.sendNotFound(request, response);
return true;
}
// Extract the image style and scale the image
String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
if (styleId != null) {
try {
StringBuffer redirect = new StringBuffer(PathUtils.concat(PreviewRequestHandlerImpl.URI_PREFIX, imageResource.getURI().getIdentifier()));
redirect.append("?style=").append(styleId);
response.sendRedirect(redirect.toString());
} catch (Throwable t) {
logger.debug("Error sending redirect to the client: {}", t.getMessage());
}
return true;
}
// Check the modified headers
long revalidationTime = MS_PER_DAY;
long expirationDate = System.currentTimeMillis() + revalidationTime;
if (!ResourceUtils.hasChanged(request, imageResource, language)) {
logger.debug("Image {} was not modified", imageURI);
response.setDateHeader("Expires", expirationDate);
DispatchUtils.sendNotModified(request, response);
return true;
}
// Load the image contents from the repository
ImageContent imageContents = imageResource.getContent(language);
// Add mime type header
String contentType = imageContents.getMimetype();
if (contentType == null)
contentType = MediaType.APPLICATION_OCTET_STREAM;