}
String fileName = getFileNameFromRequest(request);
String waveRefStr = getWaveRefFromRequest(request);
AttachmentMetadata metadata = service.getMetadata(attachmentId);
WaveletName waveletName;
if (metadata == null) {
// Old attachments does not have metainfo.
if (waveRefStr != null) {
waveletName = AttachmentUtil.waveRef2WaveletName(waveRefStr);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
} else {
waveletName = AttachmentUtil.waveRef2WaveletName(metadata.getWaveRef());
}
ParticipantId user = sessionManager.getLoggedInUser(request.getSession(false));
boolean isAuthorized = false;
try {
isAuthorized = waveletProvider.checkAccessPermission(waveletName, user);
} catch (WaveServerException e) {
LOG.warning("Problem while authorizing user: " + user + " for wavelet: " + waveletName, e);
}
if (!isAuthorized) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
if (metadata == null) {
metadata = service.buildAndStoreMetadataWithThumbnail(attachmentId, waveletName, fileName, null);
}
String contentType;
AttachmentData data;
if (request.getRequestURI().startsWith(ATTACHMENT_URL)) {
contentType = metadata.getMimeType();
data = service.getAttachment(attachmentId);
if (data == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
} else if (request.getRequestURI().startsWith(THUMBNAIL_URL)) {
if (metadata.hasImageMetadata()) {
contentType = AttachmentService.THUMBNAIL_MIME_TYPE;
data = service.getThumbnail(attachmentId);
if (data == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
} else {
contentType = THUMBNAIL_PATTERN_FORMAT_NAME;
data = getThumbnailByContentType(metadata.getMimeType());
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (data == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType(contentType);
response.setContentLength((int)data.getSize());
response.setHeader("Content-Disposition", "attachment; filename=\"" + metadata.getFileName() + "\"");
response.setStatus(HttpServletResponse.SC_OK);
response.setDateHeader("Last-Modified", Calendar.getInstance().getTimeInMillis());
AttachmentUtil.writeTo(data.getInputStream(), response.getOutputStream());
LOG.info("Fetched attachment with id '" + attachmentId + "'");