This is an automated email from the ASF dual-hosted git repository.
snoopdave pushed a commit to branch roller-6.1.x
in repository https://gitbox.apache.org/repos/asf/roller.git
The following commit(s) were added to refs/heads/roller-6.1.x by this push:
new e67e5763b Read image dimensions before decoding uploads for thumbnails
(#327)
e67e5763b is described below
commit e67e5763bbbb63d6feb240f2b214d5530b7e9408
Author: Matt Raible <[email protected]>
AuthorDate: Sat Nov 21 10:58:10 2026 -0700
Read image dimensions before decoding uploads for thumbnails (#327)
* Read image dimensions before decoding uploads for thumbnails
Thumbnail creation now reads the image's width and height from its header
with an ImageReader before decoding it. Images with more pixels than the new
uploads.thumbnail.maxPixels setting (default 50,000,000) are stored without a
thumbnail, and the skip is logged. Other images are decoded with subsampling
sized to the thumbnail. The upload's content stream is now closed, and content
that no image reader recognizes gets no thumbnail whatever content type the
client sent.
* Keep image sizes and drop old thumbnails when an image gets no thumbnail
The width and height read from an image's header are now saved before the
pixel limit is checked, so an image too large for a thumbnail still shows its
real size. When a file's new content gets no thumbnail, for any reason, the
thumbnail left from its previous content is removed, so a replaced image no
longer shows the old image's thumbnail.
MediaResourceServlet answers a thumbnail request for an image over
uploads.thumbnail.maxPixels with the small file icon instead of the full image.
Other images without a thumbnail are still served in full at the thumbnail
address. The media library and chooser show their file icon for such images
without requesting a thumbnail, and inserting one into an entry uses the
image's own address.
* Set the file icon's response headers through MediaTypePolicy
The placeholder for an image too large for a thumbnail now gets its content
type from MediaTypePolicy.applyResponseHeaders, like every other response from
MediaResourceServlet.
* Stub the weblog-scoped media lookup in the thumbnail servlet test
* Tolerate a bad thumbnail pixel limit, forget stale image sizes and pass
hasThumbnail from the chooser
A value of uploads.thumbnail.maxPixels that is not a positive int (for
example 50_000_000, 3000000000, an empty value or 0) used to throw
NumberFormatException out of the media servlet and the media library pages, and
silently stopped thumbnails being made on upload. The limit is now read in one
place, MediaFile.thumbnailMaxPixels(), which falls back to the default and logs
a warning once for each bad value.
When a file's content is replaced with something no image reader
recognizes, or whose header can't be read, the stored width and height are
reset to -1 (unknown), so the previous image's size no longer marks the new
content as over the limit.
The media chooser's onSelectMediaFile wrapper now passes hasThumbnail on to
the entry editor, so an image too large for a thumbnail is inserted at its own
URL instead of the thumbnail URL that shows the placeholder icon.
The derived overThumbnailPixelLimit getter is listed as transient in
MediaFile.orm.xml like the other derived getters.
* Decide thumbnail availability from what was stored
Whether an image has a thumbnail was worked out from the current
uploads.thumbnail.maxPixels setting, but the thumbnail was made or skipped at
upload time, so changing the limit later could make a file with a thumbnail
look like it had none, or the other way around. isOverThumbnailPixelLimit() is
replaced by isThumbnailSkipped(), which is true for an image whose size was
read on upload but which has no _sm file stored, whatever the limit is now.
* Check thumbnail state on a freshly loaded media file
The limit-change tests now end the session before reloading the file
without its content, as the list views load it, so whether it has a thumbnail
is looked up in the file store rather than read from the instance loaded during
upload.
* Preview images without a thumbnail file that are under the limit
Most images on an upgraded blog have no _sm file, because they were carried
over from older versions or by migrations, so treating every image without one
as skipped would have taken away their previews. An image now counts as skipped
only when it has no _sm file and its recorded size is over the current
uploads.thumbnail.maxPixels; an image without a thumbnail under the limit is
previewed from the original as before, and one with a thumbnail always gets it.
* Size thumbnail subsampling from both sides and skip images too narrow to
scale
The subsampling step now comes from whichever side needs the larger step,
so both sides are decoded at about twice the thumbnail size. An image so much
wider than tall, or taller than wide, that its thumbnail would be less than a
pixel across is no longer decoded, since no thumbnail could be made from it
anyway. Setting a media file's width or height also resets its cached thumbnail
size, so a replaced image's thumbnail gets the new image's shape.
* Make thumbnails only from JPEG, PNG, GIF and BMP images
These are the formats whose image readers decode a subsampled image row by
row. The TIFF reader reads a whole strip or tile into memory even when
subsampling, so TIFF images, and any other format a reader is installed for,
are now stored with their size and without a thumbnail. The format comes from
the content, not the file name. CHANGES lists the images that get no thumbnail.
* Keep the upload working when an image can't be decoded for its thumbnail
Running out of memory while decoding an image for its thumbnail is logged
and leaves the image without a thumbnail, instead of failing the upload after
the file was saved. An image whose header can be read but whose pixels can't is
stored without a size, as it was before the size came from the header. A
thumbnail that was saved is kept when a later step fails, and removing an old
thumbnail also clears it from the media file and logs failures other than a
missing file.
* Close the streams the thumbnail tests open and give each upload its own
name
The invalid-limit test named its uploads by the length of the limit value,
so two of them shared a name.
* Drop the old thumbnail and size when an image is replaced by a file that
isn't an image
Before, the replaced image's thumbnail was still served at the file's
thumbnail address.
* Serve the original for the thumbnail of an image too large to have one
Entries that embed an image's thumbnail address showed the file icon once
the image was stored without a thumbnail. The thumbnail request now falls back
to the original, as it does for any image without a thumbnail and as it did
before. The media list and chooser already show the file type icon for such an
image themselves, so they don't load the original as a preview.
---
CHANGES.md | 9 +-
.../weblogger/business/MediaFileManager.java | 7 +
.../business/jpa/JPAMediaFileManagerImpl.java | 166 ++++++-
.../apache/roller/weblogger/pojos/MediaFile.java | 68 +++
.../ui/struts2/editor/EntryAddWithMediaFile.java | 5 +-
.../roller/weblogger/config/roller.properties | 4 +
.../roller/weblogger/pojos/MediaFile.orm.xml | 1 +
.../webapp/WEB-INF/jsps/editor/EntryEditor.jsp | 6 +-
.../WEB-INF/jsps/editor/MediaFileImageChooser.jsp | 13 +-
.../webapp/WEB-INF/jsps/editor/MediaFileView.jsp | 6 +-
.../weblogger/business/MediaFileThumbnailTest.java | 475 +++++++++++++++++++++
.../business/jpa/ThumbnailSubsamplingTest.java | 73 ++++
.../servlets/MediaResourceThumbnailTest.java | 187 ++++++++
13 files changed, 1001 insertions(+), 19 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index adaa2d4b9..3618fcaa6 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -38,10 +38,11 @@
escaped unless the HTMLSubset plugin applies to them (#330).
- **Limits on uploads and fetched feeds.** Images with more pixels than
- `uploads.thumbnail.maxPixels` (50 million) are stored without a thumbnail
- (#327). Planet stops reading a feed past `planet.aggregator.fetch.maxBytes`
- (5 MB) or `planet.aggregator.fetch.maxSeconds` (30 seconds), and fetches
- only http and https URLs (#326).
+ `uploads.thumbnail.maxPixels` (50 million) are stored without a thumbnail,
+ and so are TIFF images (#327). Planet stops reading a feed past
+ `planet.aggregator.fetch.maxBytes` (5 MB) or
+ `planet.aggregator.fetch.maxSeconds` (30 seconds), and fetches only http
+ and https URLs (#326).
- **AtomPub checks.** Publishing an entry through an AtomPub update needs the
permission to publish, media uploads over `uploads.file.maxsize` are
diff --git
a/app/src/main/java/org/apache/roller/weblogger/business/MediaFileManager.java
b/app/src/main/java/org/apache/roller/weblogger/business/MediaFileManager.java
index f8a361132..2c464fa3c 100644
---
a/app/src/main/java/org/apache/roller/weblogger/business/MediaFileManager.java
+++
b/app/src/main/java/org/apache/roller/weblogger/business/MediaFileManager.java
@@ -36,6 +36,13 @@ public interface MediaFileManager {
int MAX_WIDTH = 120;
int MAX_HEIGHT = 120;
+ /**
+ * Images with more pixels than this get no thumbnail, so that an upload
+ * can't make the server decode an arbitrarily large image.
+ */
+ String THUMBNAIL_MAX_PIXELS_PROPERTY = "uploads.thumbnail.maxPixels";
+ int DEFAULT_THUMBNAIL_MAX_PIXELS = 50_000_000;
+
/**
* Initialization; deal with upgrade migrations, etc.
*/
diff --git
a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java
b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java
index 85a19cd44..1121bee77 100644
---
a/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java
+++
b/app/src/main/java/org/apache/roller/weblogger/business/jpa/JPAMediaFileManagerImpl.java
@@ -33,10 +33,14 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import javax.imageio.ImageIO;
+import javax.imageio.ImageReadParam;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
import jakarta.persistence.NoResultException;
import jakarta.persistence.TypedQuery;
@@ -46,6 +50,7 @@ import org.apache.commons.logging.LogFactory;
import org.apache.roller.weblogger.WebloggerException;
import org.apache.roller.weblogger.business.FileContentManager;
import org.apache.roller.weblogger.business.FileIOException;
+import org.apache.roller.weblogger.business.FileNotFoundException;
import org.apache.roller.weblogger.business.MediaFileManager;
import org.apache.roller.weblogger.business.WeblogManager;
import org.apache.roller.weblogger.business.Weblogger;
@@ -65,6 +70,14 @@ import org.apache.roller.weblogger.util.Utilities;
@com.google.inject.Singleton
public class JPAMediaFileManagerImpl implements MediaFileManager {
+ /**
+ * Image formats that get thumbnails. Their readers decode a subsampled
+ * image without holding the whole image in memory; the TIFF reader, for
+ * one, reads a whole strip or tile at a time.
+ */
+ private static final Set<String> THUMBNAIL_FORMATS =
+ Set.of("jpeg", "png", "gif", "bmp");
+
private final Weblogger roller;
private final JPAPersistenceStrategy strategy;
private static final Log log =
LogFactory.getFactory().getInstance(JPAMediaFileManagerImpl.class);
@@ -249,20 +262,116 @@ public class JPAMediaFileManagerImpl implements
MediaFileManager {
}
}
+ /**
+ * Record the image's size and save a thumbnail of it. The size is read
+ * from the image header first; images with more pixels than
+ * uploads.thumbnail.maxPixels are left without a thumbnail rather than
+ * decoded, and the rest are decoded subsampled to near thumbnail size.
+ * Only JPEG, PNG, GIF and BMP content gets a thumbnail, whatever content
+ * type the client sent. When no thumbnail is made, any thumbnail
+ * left from the file's previous content is removed.
+ */
private void updateThumbnail(MediaFile mediaFile) {
+ if (!createThumbnail(mediaFile)) {
+ removeThumbnail(mediaFile);
+ }
+ }
+
+ private void removeThumbnail(MediaFile mediaFile) {
+ mediaFile.setThumbnailContent(null);
+ try {
+ WebloggerFactory.getWeblogger().getFileContentManager()
+ .deleteFile(mediaFile.getWeblog(), mediaFile.getId() +
"_sm");
+ } catch (FileNotFoundException e) {
+ // there was no thumbnail
+ log.debug("No thumbnail to remove for media file " +
mediaFile.getId());
+ } catch (Exception e) {
+ log.warn("ERROR removing the thumbnail of media file "
+ + mediaFile.getId(), e);
+ }
+ }
+
+ /** @return true if a thumbnail was saved */
+ private boolean createThumbnail(MediaFile mediaFile) {
+ boolean sizeRead = false;
+ boolean thumbnailSaved = false;
try {
FileContentManager cmgr = WebloggerFactory.getWeblogger()
.getFileContentManager();
FileContent fc = cmgr.getFileContent(mediaFile.getWeblog(),
mediaFile.getId());
+ int maxPixels = MediaFile.thumbnailMaxPixels();
BufferedImage img;
- img = ImageIO.read(fc.getInputStream());
+ try (InputStream in = fc.getInputStream();
+ ImageInputStream iis = ImageIO.createImageInputStream(in)) {
+ Iterator<ImageReader> readers = iis == null
+ ? null : ImageIO.getImageReaders(iis);
+ if (readers == null || !readers.hasNext()) {
+ log.debug("No image reader for media file "
+ + mediaFile.getId() + ", not creating a
thumbnail");
+ return false;
+ }
+ ImageReader reader = readers.next();
+ try {
+ reader.setInput(iis, true, true);
+ int width = reader.getWidth(0);
+ int height = reader.getHeight(0);
+ if (width <= 0 || height <= 0) {
+ return false;
+ }
- // determine and save width and height
- mediaFile.setWidth(img.getWidth());
- mediaFile.setHeight(img.getHeight());
- strategy.store(mediaFile);
+ // save width and height, also for an image too large
+ // for a thumbnail
+ mediaFile.setWidth(width);
+ mediaFile.setHeight(height);
+ strategy.store(mediaFile);
+ sizeRead = true;
+
+ if ((long) width * height > maxPixels) {
+ log.info("Not creating a thumbnail for media file "
+ + mediaFile.getId() + " (" + width + "x"
+ + height + "), it is larger than "
+ +
MediaFileManager.THUMBNAIL_MAX_PIXELS_PROPERTY + "="
+ + maxPixels + " pixels");
+ return false;
+ }
+
+ String format =
reader.getFormatName().toLowerCase(Locale.ROOT);
+ if (!THUMBNAIL_FORMATS.contains(format)) {
+ log.debug("Not creating a thumbnail for media file "
+ + mediaFile.getId() + ", " + format
+ + " images get none");
+ return false;
+ }
+
+ int step = thumbnailSubsampling(width, height,
+ mediaFile.getThumbnailWidth(),
+ mediaFile.getThumbnailHeight());
+ if (step < 1) {
+ log.debug("Not creating a thumbnail for media file "
+ + mediaFile.getId() + " (" + width + "x" +
height
+ + "), it is too narrow to scale down");
+ return false;
+ }
+ ImageReadParam param = reader.getDefaultReadParam();
+ param.setSourceSubsampling(step, step, 0, 0);
+ try {
+ img = reader.read(0, param);
+ } catch (OutOfMemoryError e) {
+ log.warn("Not enough memory to create a thumbnail for"
+ + " media file " + mediaFile.getId() + " ("
+ + width + "x" + height + ")");
+ return false;
+ } catch (IOException | RuntimeException e) {
+ // the header's size isn't that of a readable image
+ sizeRead = false;
+ throw e;
+ }
+ } finally {
+ reader.dispose();
+ }
+ }
int newWidth = mediaFile.getThumbnailWidth();
int newHeight = mediaFile.getThumbnailHeight();
@@ -281,13 +390,55 @@ public class JPAMediaFileManagerImpl implements
MediaFileManager {
cmgr.saveFileContent(mediaFile.getWeblog(), mediaFile.getId()
+ "_sm", new ByteArrayInputStream(baos.toByteArray()));
+ thumbnailSaved = true;
roller.flush();
// Refresh associated parent for changes
strategy.refresh(mediaFile.getDirectory());
+ return true;
} catch (Exception e) {
log.debug("ERROR creating thumbnail", e);
+ return thumbnailSaved;
+ } finally {
+ if (!sizeRead) {
+ forgetSize(mediaFile);
+ }
+ }
+ }
+
+ /**
+ * The subsampling step for decoding an image for its thumbnail: only
+ * every n-th pixel is decoded, keeping about twice the thumbnail size in
+ * each direction so the smooth scaling has detail. Returns 0 when the
+ * image is so much wider than tall, or taller than wide, that its
+ * thumbnail would be less than a pixel across; no thumbnail is made then.
+ */
+ static int thumbnailSubsampling(int width, int height,
+ int thumbnailWidth, int thumbnailHeight) {
+ if (thumbnailWidth < 1 || thumbnailHeight < 1) {
+ return 0;
+ }
+ return Math.max(1, Math.max(width / (2 * thumbnailWidth),
+ height / (2 * thumbnailHeight)));
+ }
+
+ /**
+ * Mark the image's size as unknown, so that the size of the file's
+ * previous content isn't taken for the size of content that could not
+ * be read.
+ */
+ private void forgetSize(MediaFile mediaFile) {
+ if (mediaFile.getWidth() == -1 && mediaFile.getHeight() == -1) {
+ return;
+ }
+ try {
+ mediaFile.setWidth(-1);
+ mediaFile.setHeight(-1);
+ strategy.store(mediaFile);
+ } catch (Exception e) {
+ log.debug("ERROR clearing the size of media file "
+ + mediaFile.getId(), e);
}
}
@@ -335,6 +486,11 @@ public class JPAMediaFileManagerImpl implements
MediaFileManager {
if (mediaFile.isImageFile()) {
updateThumbnail(mediaFile);
+ } else {
+ // content that isn't an image keeps no thumbnail or size from
+ // the image it replaced
+ removeThumbnail(mediaFile);
+ forgetSize(mediaFile);
}
}
diff --git a/app/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java
b/app/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java
index b94749be6..52c801839 100644
--- a/app/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java
+++ b/app/src/main/java/org/apache/roller/weblogger/pojos/MediaFile.java
@@ -33,6 +33,7 @@ import org.apache.roller.util.UUIDGenerator;
import org.apache.roller.weblogger.WebloggerException;
import org.apache.roller.weblogger.business.MediaFileManager;
import org.apache.roller.weblogger.business.WebloggerFactory;
+import org.apache.roller.weblogger.config.WebloggerConfig;
import org.apache.roller.weblogger.util.Utilities;
/**
@@ -45,6 +46,9 @@ public class MediaFile implements Serializable {
private static final Log log =
LogFactory.getFactory().getInstance(MediaFile.class);
+ // the last invalid uploads.thumbnail.maxPixels value warned about
+ private static volatile String invalidMaxPixelsLogged;
+
private String id = UUIDGenerator.generateUUID();
private String name;
@@ -366,6 +370,64 @@ public class MediaFile implements Serializable {
.getMediaFileThumbnailURL(getWeblog(), this.getId(), true);
}
+ /**
+ * True for an image that has no thumbnail stored and whose recorded size
+ * is over uploads.thumbnail.maxPixels. An image with a thumbnail, or one
+ * without a thumbnail but under the limit (such as a file carried over
+ * from an older version), is not skipped and is previewed as before.
+ */
+ public boolean isThumbnailSkipped() {
+ if (!isImageFile() || getWidth() <= 0 || getHeight() <= 0) {
+ return false;
+ }
+ if ((long) getWidth() * getHeight() <= thumbnailMaxPixels()) {
+ return false;
+ }
+ return !thumbnailStored();
+ }
+
+ private boolean thumbnailStored() {
+ if (thumbnail != null) {
+ return true;
+ }
+ try {
+ WebloggerFactory.getWeblogger().getFileContentManager()
+ .getFileContent(getWeblog(), getId() + "_sm");
+ return true;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+
+ /**
+ * The value of uploads.thumbnail.maxPixels. A value that is not a
+ * positive whole number is ignored in favour of the default, with a
+ * warning logged once for each such value.
+ */
+ public static int thumbnailMaxPixels() {
+ int maxPixels;
+ try {
+ maxPixels = WebloggerConfig.getIntProperty(
+ MediaFileManager.THUMBNAIL_MAX_PIXELS_PROPERTY,
+ MediaFileManager.DEFAULT_THUMBNAIL_MAX_PIXELS);
+ } catch (NumberFormatException e) {
+ maxPixels = 0;
+ }
+ if (maxPixels > 0) {
+ return maxPixels;
+ }
+ String value = WebloggerConfig.getProperty(
+ MediaFileManager.THUMBNAIL_MAX_PIXELS_PROPERTY);
+ if (!String.valueOf(value).equals(invalidMaxPixelsLogged)) {
+ invalidMaxPixelsLogged = String.valueOf(value);
+ log.warn(MediaFileManager.THUMBNAIL_MAX_PIXELS_PROPERTY + "=" +
value
+ + " is not a whole number between 1 and " +
Integer.MAX_VALUE
+ + ", using the default of "
+ + MediaFileManager.DEFAULT_THUMBNAIL_MAX_PIXELS);
+ }
+ return MediaFileManager.DEFAULT_THUMBNAIL_MAX_PIXELS;
+ }
+
public String getCreatorUserName() {
return creatorUserName;
}
@@ -434,6 +496,9 @@ public class MediaFile implements Serializable {
*/
public void setWidth(int width) {
this.width = width;
+ // the thumbnail size is worked out again from the new size
+ thumbnailWidth = -1;
+ thumbnailHeight = -1;
}
/**
@@ -449,6 +514,9 @@ public class MediaFile implements Serializable {
*/
public void setHeight(int height) {
this.height = height;
+ // the thumbnail size is worked out again from the new size
+ thumbnailWidth = -1;
+ thumbnailHeight = -1;
}
/**
diff --git
a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/EntryAddWithMediaFile.java
b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/EntryAddWithMediaFile.java
index 23c02712b..8858b21ab 100644
---
a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/EntryAddWithMediaFile.java
+++
b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/editor/EntryAddWithMediaFile.java
@@ -82,7 +82,10 @@ public class EntryAddWithMediaFile extends MediaFileBase {
link = "<p>" + mediaFile.getName() + "</p>";
link += "<a href=\"<url>\"><img src=\"<urlt>\"
alt=\"<name>\" width=\"<width>\" height=\"<height>\"></img></a>";
link = link.replace("<url>", mediaFile.getPermalink())
- .replace("<urlt>",
mediaFile.getThumbnailURL())
+ // an image too large for a thumbnail is
shown
+ // at thumbnail size from its own URL
+ .replace("<urlt>",
mediaFile.isThumbnailSkipped()
+ ? mediaFile.getPermalink() :
mediaFile.getThumbnailURL())
.replace("<name>", mediaFile.getName())
.replace("<width>",
""+mediaFile.getThumbnailWidth())
.replace("<height>",
""+mediaFile.getThumbnailHeight());
diff --git
a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
index f165134ae..ef7f48b47 100644
---
a/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
+++
b/app/src/main/resources/org/apache/roller/weblogger/config/roller.properties
@@ -119,6 +119,10 @@ mediafile.resource.url=/resources
# Migrate old file resources to Roller 5.0 Mediafile Storage automatically
uploads.migrate.auto=false
+# Largest image, in pixels (width times height), that gets a thumbnail when
+# uploaded. Larger images are stored without one.
+uploads.thumbnail.maxPixels=50000000
+
# Directory in which search index is to be created
# (delete this directory to force Roller to recreate the entire search index)
search.index.dir=${user.home}/roller_data/search-index
diff --git
a/app/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml
b/app/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml
index f7b0113c7..ee68610a6 100644
--- a/app/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml
+++ b/app/src/main/resources/org/apache/roller/weblogger/pojos/MediaFile.orm.xml
@@ -70,6 +70,7 @@
<transient name="path"/>
<transient name="creator"/>
<transient name="imageFile"/>
+ <transient name="thumbnailSkipped"/>
<transient name="addedTags"/>
<transient name="removedTags"/>
<transient name="tagsAsString"/>
diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
b/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
index b7837e851..fe63d7001 100644
--- a/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
+++ b/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
@@ -217,11 +217,13 @@
$("#mediaFileEditor").attr('src', 'about:blank');
}
- function onSelectMediaFile(name, url, isImage) {
+ // An image too large for a thumbnail is inserted at its own URL.
+ function onSelectMediaFile(name, url, isImage, hasThumbnail) {
$("#mediafile_edit_lightbox").modal("hide");
$("#mediaFileEditor").attr('src', 'about:blank');
if (isImage === "true") {
- insertMediaFile('<a href="' + url + '"><img src="' + url +
'?t=true" alt="' + name + '" /></a>');
+ var src = hasThumbnail === "false" ? url : url + '?t=true';
+ insertMediaFile('<a href="' + url + '"><img src="' + src + '"
alt="' + name + '" /></a>');
} else {
insertMediaFile('<a href="' + url + '">' + name + '</a>');
}
diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileImageChooser.jsp
b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileImageChooser.jsp
index 093832fec..f8fb28080 100644
--- a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileImageChooser.jsp
+++ b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileImageChooser.jsp
@@ -75,9 +75,11 @@
<div class="mediaObject
mediafile-select-target"
data-mediafile-name="<s:property
value="#mediaFile.name"/>"
data-mediafile-url="<s:property
value="%{mediaFileURL}"/>"
- data-mediafile-is-image="<s:property
value="#mediaFile.isImageFile()"/>">
+ data-mediafile-is-image="<s:property
value="#mediaFile.isImageFile()"/>"
+ data-mediafile-has-thumbnail="<s:property
value="!#mediaFile.thumbnailSkipped"/>">
- <s:if test="#mediaFile.imageFile">
+ <%-- an image too large for a thumbnail
shows the file icon --%>
+ <s:if test="#mediaFile.imageFile &&
!#mediaFile.thumbnailSkipped">
<img border="0" src="<s:property
value='%{mediaFileThumbnailURL}' />"
width="<s:property
value='#mediaFile.thumbnailWidth'/>"
height="<s:property
value='#mediaFile.thumbnailHeight'/>"
@@ -114,15 +116,16 @@
<script>
- function onSelectMediaFile(name, url, isImage) {
- window.parent.onSelectMediaFile(name, url, isImage);
+ function onSelectMediaFile(name, url, isImage, hasThumbnail) {
+ window.parent.onSelectMediaFile(name, url, isImage, hasThumbnail);
}
// Values come from data-* attributes and are bound via delegated
listeners.
$(document).on('click', '.mediafile-select-target', function () {
onSelectMediaFile($(this).attr('data-mediafile-name'),
$(this).attr('data-mediafile-url'),
- $(this).attr('data-mediafile-is-image'));
+ $(this).attr('data-mediafile-is-image'),
+ $(this).attr('data-mediafile-has-thumbnail'));
});
function highlight(el, flag) {
diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileView.jsp
b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileView.jsp
index 0e65cbd83..58d21591c 100644
--- a/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileView.jsp
+++ b/app/src/main/webapp/WEB-INF/jsps/editor/MediaFileView.jsp
@@ -173,7 +173,8 @@
data-mediafile-id="<s:property
value="#mediaFile.id"/>"
data-mediafile-name="<s:property
value="#mediaFile.name"/>">
- <s:if test="#mediaFile.imageFile">
+ <%-- an image too large for a thumbnail
shows the file icon --%>
+ <s:if test="#mediaFile.imageFile &&
!#mediaFile.thumbnailSkipped">
<img border="0" src="<s:property
value='%{#mediaFile.thumbnailURL}' />"
width="<s:property
value='#mediaFile.thumbnailWidth' />"
height="<s:property
value='#mediaFile.thumbnailHeight' />"
@@ -227,7 +228,8 @@
data-mediafile-id="<s:property
value="#mediaFile.id"/>"
data-mediafile-name="<s:property
value="#mediaFile.name"/>">
- <s:if test="#mediaFile.imageFile">
+ <%-- an image too large for a thumbnail
shows the file icon --%>
+ <s:if test="#mediaFile.imageFile &&
!#mediaFile.thumbnailSkipped">
<img border="0" src="<s:property
value='%{#mediaFile.thumbnailURL}' />"
width="<s:property
value='#mediaFile.thumbnailWidth'/>"
height="<s:property
value='#mediaFile.thumbnailHeight'/>"
diff --git
a/app/src/test/java/org/apache/roller/weblogger/business/MediaFileThumbnailTest.java
b/app/src/test/java/org/apache/roller/weblogger/business/MediaFileThumbnailTest.java
new file mode 100644
index 000000000..5e48dc2b6
--- /dev/null
+++
b/app/src/test/java/org/apache/roller/weblogger/business/MediaFileThumbnailTest.java
@@ -0,0 +1,475 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.roller.weblogger.business;
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import java.util.zip.CRC32;
+import java.util.zip.Deflater;
+
+import javax.imageio.ImageIO;
+
+import org.apache.roller.weblogger.TestUtils;
+import org.apache.roller.weblogger.config.WebloggerConfig;
+import org.apache.roller.weblogger.pojos.MediaFile;
+import org.apache.roller.weblogger.pojos.MediaFileDirectory;
+import org.apache.roller.weblogger.pojos.RuntimeConfigProperty;
+import org.apache.roller.weblogger.pojos.User;
+import org.apache.roller.weblogger.pojos.Weblog;
+import org.apache.roller.weblogger.util.RollerMessages;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.CALLS_REAL_METHODS;
+import static org.mockito.Mockito.mockStatic;
+
+/**
+ * Thumbnails are made for ordinary images, and skipped, without decoding the
+ * image, for images whose pixel count is over uploads.thumbnail.maxPixels,
+ * images too narrow to scale and formats other than JPEG, PNG, GIF and BMP.
+ * The upload itself succeeds either way.
+ */
+public class MediaFileThumbnailTest {
+
+ private User user;
+ private Weblog weblog;
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ TestUtils.setupWeblogger();
+ Map<String, RuntimeConfigProperty> config =
+
WebloggerFactory.getWeblogger().getPropertiesManager().getProperties();
+ config.get("uploads.enabled").setValue("true");
+ user = TestUtils.setupUser("thumbnailTestUser");
+ weblog = TestUtils.setupWeblog("thumbnailTestWeblog", user);
+ TestUtils.endSession(true);
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ TestUtils.teardownWeblog(weblog.getId());
+ TestUtils.teardownUser(user.getUserName());
+ TestUtils.endSession(true);
+ }
+
+ /** Upload an image and reload it with its content and thumbnail. */
+ private MediaFile upload(String name, String type, InputStream in, long
length)
+ throws Exception {
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ Weblog managed = TestUtils.getManagedWebsite(weblog);
+ MediaFileDirectory dir = mgr.getDefaultMediaFileDirectory(managed);
+
+ MediaFile mediaFile = new MediaFile();
+ mediaFile.setName(name);
+ mediaFile.setLength(length);
+ mediaFile.setDirectory(dir);
+ mediaFile.setWeblog(managed);
+ mediaFile.setContentType(type);
+ mediaFile.setInputStream(in);
+ dir.getMediaFiles().add(mediaFile);
+
+ RollerMessages errors = new RollerMessages();
+ mgr.createMediaFile(managed, mediaFile, errors);
+ TestUtils.endSession(true);
+ assertEquals(0, errors.getErrorCount(), "upload should succeed");
+ assertNotNull(mediaFile.getId());
+ return mgr.getMediaFile(mediaFile.getId(), true);
+ }
+
+ @Test
+ public void testThumbnailIsMadeForNormalImage() throws Exception {
+ MediaFile saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+
+ assertEquals(500, saved.getWidth());
+ assertEquals(373, saved.getHeight());
+ try (InputStream in = saved.getThumbnailInputStream()) {
+ assertNotNull(in, "a normal image should get a thumbnail");
+ BufferedImage thumbnail = ImageIO.read(in);
+ assertEquals(MediaFileManager.MAX_WIDTH, thumbnail.getWidth());
+ assertTrue(thumbnail.getHeight() <= MediaFileManager.MAX_HEIGHT);
+ }
+ }
+
+ /**
+ * A few hundred bytes of PNG whose header claims 50000 x 50000 pixels
+ * must not be decoded.
+ */
+ @Test
+ public void testHugeImageIsStoredWithoutThumbnail() throws Exception {
+ byte[] png = pngHeaderOnly(50000, 50000);
+ MediaFile saved = upload("huge.png", "image/png",
+ new ByteArrayInputStream(png), png.length);
+
+ try (InputStream in = saved.getInputStream()) {
+ assertNotNull(in, "the upload itself must be kept");
+ }
+ assertNull(saved.getThumbnailInputStream());
+ // the size still comes from the header, for the upload result page
+ assertEquals(50000, saved.getWidth());
+ assertEquals(50000, saved.getHeight());
+ assertTrue(saved.isThumbnailSkipped());
+ }
+
+ /**
+ * Replacing an image with one over the limit removes the old image's
+ * thumbnail and records the new image's size.
+ */
+ @Test
+ public void testReplacingWithHugeImageRemovesOldThumbnail() throws
Exception {
+ MediaFile saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+ try (InputStream in = saved.getThumbnailInputStream()) {
+ assertNotNull(in);
+ }
+ assertFalse(saved.isThumbnailSkipped());
+
+ byte[] png = pngHeaderOnly(50000, 50000);
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ MediaFile replaced = mgr.getMediaFile(saved.getId());
+ replaced.setContentType("image/png");
+ replaced.setLength(png.length);
+ mgr.updateMediaFile(TestUtils.getManagedWebsite(weblog), replaced,
+ new ByteArrayInputStream(png));
+ TestUtils.endSession(true);
+
+ MediaFile reloaded = mgr.getMediaFile(saved.getId(), true);
+ assertNull(reloaded.getThumbnailInputStream(),
+ "the previous image's thumbnail must not be kept");
+ assertEquals(50000, reloaded.getWidth());
+ assertEquals(50000, reloaded.getHeight());
+ }
+
+ /**
+ * Replacing an image with a file that is not an image removes the old
+ * image's thumbnail and size.
+ */
+ @Test
+ public void testReplacingWithNonImageRemovesOldThumbnail() throws
Exception {
+ MediaFile saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+ try (InputStream in = saved.getThumbnailInputStream()) {
+ assertNotNull(in);
+ }
+
+ byte[] text = "notes".getBytes(StandardCharsets.US_ASCII);
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ MediaFile replaced = mgr.getMediaFile(saved.getId());
+ replaced.setName("notes.txt");
+ replaced.setContentType("text/plain");
+ replaced.setLength(text.length);
+ mgr.updateMediaFile(TestUtils.getManagedWebsite(weblog), replaced,
+ new ByteArrayInputStream(text));
+ TestUtils.endSession(true);
+
+ MediaFile reloaded = mgr.getMediaFile(saved.getId(), true);
+ assertNull(reloaded.getThumbnailInputStream(),
+ "the previous image's thumbnail must not be kept");
+ assertEquals(-1, reloaded.getWidth());
+ assertEquals(-1, reloaded.getHeight());
+ }
+
+ /** The pixel limit comes from uploads.thumbnail.maxPixels. */
+ @Test
+ public void testThumbnailIsSkippedOverConfiguredLimit() throws Exception {
+ WebloggerConfig.init();
+ MediaFile saved;
+ try (MockedStatic<WebloggerConfig> config =
+ mockStatic(WebloggerConfig.class, CALLS_REAL_METHODS)) {
+ config.when(() -> WebloggerConfig.getIntProperty(
+ eq("uploads.thumbnail.maxPixels"),
anyInt())).thenReturn(100000);
+ // 500 x 373 is 186500 pixels, over the limit set above
+ saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+ }
+ try (InputStream in = saved.getInputStream()) {
+ assertNotNull(in);
+ }
+ assertNull(saved.getThumbnailInputStream());
+ assertEquals(500, saved.getWidth());
+ assertEquals(373, saved.getHeight());
+ }
+
+ /**
+ * An image stored without a thumbnail because it was over the limit is
+ * served in full once uploads.thumbnail.maxPixels is raised above its
+ * size, like any other image without a thumbnail under the limit.
+ */
+ @Test
+ public void testRaisingLimitAfterUploadServesOriginal() throws Exception {
+ WebloggerConfig.init();
+ MediaFile saved;
+ try (MockedStatic<WebloggerConfig> config =
+ mockStatic(WebloggerConfig.class, CALLS_REAL_METHODS)) {
+ config.when(() -> WebloggerConfig.getIntProperty(
+ eq("uploads.thumbnail.maxPixels"),
anyInt())).thenReturn(100000);
+ saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+ }
+ assertNull(saved.getThumbnailInputStream());
+
+ // back at the default limit, which 500 x 373 is well under
+ TestUtils.endSession(true);
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ assertFalse(loadedWithoutContent(saved.getId()).isThumbnailSkipped());
+ assertFalse(mgr.getMediaFile(saved.getId(),
true).isThumbnailSkipped());
+ }
+
+ /**
+ * An image under the limit that has no thumbnail file, as for files
+ * carried over from older versions or by migrations, is served in full.
+ */
+ @Test
+ public void testSmallImageWithoutThumbnailFileIsNotSkipped() throws
Exception {
+ MediaFile saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+ WebloggerFactory.getWeblogger().getFileContentManager().deleteFile(
+ saved.getWeblog(), saved.getId() + "_sm");
+ TestUtils.endSession(true);
+
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ MediaFile reloaded = mgr.getMediaFile(saved.getId(), true);
+ assertNull(reloaded.getThumbnailInputStream());
+ assertEquals(500, reloaded.getWidth());
+ assertEquals(373, reloaded.getHeight());
+ assertFalse(reloaded.isThumbnailSkipped());
+ TestUtils.endSession(true);
+ assertFalse(loadedWithoutContent(saved.getId()).isThumbnailSkipped());
+ }
+
+ /**
+ * An image stored with a thumbnail keeps showing as having one after
+ * uploads.thumbnail.maxPixels is lowered below its size.
+ */
+ @Test
+ public void testLoweringLimitAfterUploadKeepsThumbnail() throws Exception {
+ MediaFile saved = upload("hawk.jpg", "image/jpeg",
+ getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE),
2000);
+ try (InputStream in = saved.getThumbnailInputStream()) {
+ assertNotNull(in);
+ }
+
+ TestUtils.endSession(true);
+ WebloggerConfig.init();
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ try (MockedStatic<WebloggerConfig> config =
+ mockStatic(WebloggerConfig.class, CALLS_REAL_METHODS)) {
+ config.when(() -> WebloggerConfig.getIntProperty(
+ eq("uploads.thumbnail.maxPixels"),
anyInt())).thenReturn(100000);
+
assertFalse(loadedWithoutContent(saved.getId()).isThumbnailSkipped());
+ assertFalse(mgr.getMediaFile(saved.getId(), true)
+ .isThumbnailSkipped());
+ }
+ }
+
+ /**
+ * Load a media file the way the list views do, without its content, so
+ * that whether it has a thumbnail has to be looked up in the file store.
+ */
+ private static MediaFile loadedWithoutContent(String id) throws Exception {
+ MediaFile mediaFile =
WebloggerFactory.getWeblogger().getMediaFileManager()
+ .getMediaFile(id);
+ assertNull(mediaFile.getThumbnailInputStream(),
+ "the thumbnail content should not be loaded");
+ return mediaFile;
+ }
+
+ /**
+ * A limit that is not a positive int is ignored in favour of the default.
+ */
+ @Test
+ public void testInvalidLimitFallsBackToDefault() throws Exception {
+ WebloggerConfig.init();
+ String[] values = {"50_000_000", "3000000000", "", "0", "-1"};
+ for (int i = 0; i < values.length; i++) {
+ String value = values[i];
+ MediaFile saved;
+ try (MockedStatic<WebloggerConfig> config =
+ mockStatic(WebloggerConfig.class, CALLS_REAL_METHODS)) {
+ config.when(() -> WebloggerConfig.getProperty(
+ "uploads.thumbnail.maxPixels")).thenReturn(value);
+
+ assertEquals(MediaFileManager.DEFAULT_THUMBNAIL_MAX_PIXELS,
+ MediaFile.thumbnailMaxPixels(), "limit '" + value +
"'");
+
+ saved = upload("hawk" + i + ".jpg", "image/jpeg",
+
getClass().getResourceAsStream(MediaFileTest.TEST_IMAGE), 2000);
+ }
+ try (InputStream in = saved.getThumbnailInputStream()) {
+ assertNotNull(in, "limit '" + value + "' should not stop
thumbnails");
+ }
+ }
+ }
+
+ /**
+ * Replacing an image with content no image reader recognizes forgets the
+ * previous image's size.
+ */
+ @Test
+ public void testReplacingWithUnrecognizedContentForgetsOldSize() throws
Exception {
+ assertOldSizeIsForgotten("unrecognized.png",
+ "not an image".getBytes(StandardCharsets.US_ASCII));
+ }
+
+ /**
+ * Replacing an image with one whose header can't be read forgets the
+ * previous image's size.
+ */
+ @Test
+ public void testReplacingWithUnreadableHeaderForgetsOldSize() throws
Exception {
+ // a PNG signature with a header cut off before the height
+ assertOldSizeIsForgotten("truncated.png",
+ java.util.Arrays.copyOf(pngHeaderOnly(50000, 50000), 22));
+ }
+
+ private void assertOldSizeIsForgotten(String name, byte[] replacement)
+ throws Exception {
+ byte[] png = pngHeaderOnly(50000, 50000);
+ MediaFile saved = upload(name, "image/png",
+ new ByteArrayInputStream(png), png.length);
+ assertTrue(saved.isThumbnailSkipped());
+
+ MediaFileManager mgr =
WebloggerFactory.getWeblogger().getMediaFileManager();
+ MediaFile replaced = mgr.getMediaFile(saved.getId());
+ replaced.setLength(replacement.length);
+ mgr.updateMediaFile(TestUtils.getManagedWebsite(weblog), replaced,
+ new ByteArrayInputStream(replacement));
+ TestUtils.endSession(true);
+
+ MediaFile reloaded = mgr.getMediaFile(saved.getId(), true);
+ assertNull(reloaded.getThumbnailInputStream());
+ assertEquals(-1, reloaded.getWidth());
+ assertEquals(-1, reloaded.getHeight());
+ assertFalse(reloaded.isThumbnailSkipped(),
+ "the previous image's size must not count against the new
content");
+ }
+
+ /**
+ * An image under the limit whose header can be read but whose pixels
+ * can't is stored without a size, as before the size was read from the
+ * header.
+ */
+ @Test
+ public void testUndecodableImageIsStoredWithoutSize() throws Exception {
+ byte[] png = pngHeaderOnly(2000, 1000);
+ MediaFile saved = upload("cut-off.png", "image/png",
+ new ByteArrayInputStream(png), png.length);
+
+ assertNull(saved.getThumbnailInputStream());
+ assertEquals(-1, saved.getWidth());
+ assertEquals(-1, saved.getHeight());
+ assertFalse(saved.isThumbnailSkipped());
+ }
+
+ /**
+ * An image so much wider than tall that its thumbnail would be less than
+ * a pixel high is stored with its size and without a thumbnail.
+ */
+ @Test
+ public void testVeryWideImageIsStoredWithoutThumbnail() throws Exception {
+ byte[] png = encode(new BufferedImage(30000, 10,
+ BufferedImage.TYPE_BYTE_GRAY), "png");
+ MediaFile saved = upload("banner.png", "image/png",
+ new ByteArrayInputStream(png), png.length);
+
+ assertNull(saved.getThumbnailInputStream());
+ assertEquals(30000, saved.getWidth());
+ assertEquals(10, saved.getHeight());
+ assertFalse(saved.isThumbnailSkipped());
+ }
+
+ /**
+ * A TIFF image is stored with its size and without a thumbnail, also when
+ * its name says it is another type.
+ */
+ @Test
+ public void testTiffImageIsStoredWithoutThumbnail() throws Exception {
+ byte[] tiff = encode(new BufferedImage(200, 100,
+ BufferedImage.TYPE_BYTE_GRAY), "tiff");
+ for (String name : new String[] {"scan.tif", "scan.png"}) {
+ MediaFile saved = upload(name, name.endsWith(".tif") ?
"image/tiff" : "image/png",
+ new ByteArrayInputStream(tiff), tiff.length);
+
+ assertNull(saved.getThumbnailInputStream(), name);
+ assertEquals(200, saved.getWidth(), name);
+ assertEquals(100, saved.getHeight(), name);
+ }
+ }
+
+ private static byte[] encode(BufferedImage image, String format)
+ throws Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ assertTrue(ImageIO.write(image, format, out), "no " + format + "
writer");
+ return out.toByteArray();
+ }
+
+ /** A valid PNG signature and header followed by a token amount of data. */
+ private static byte[] pngHeaderOnly(int width, int height) throws
Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ DataOutputStream data = new DataOutputStream(out);
+ data.write(new byte[] {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1a,
'\n'});
+
+ ByteArrayOutputStream ihdr = new ByteArrayOutputStream();
+ DataOutputStream header = new DataOutputStream(ihdr);
+ header.writeInt(width);
+ header.writeInt(height);
+ header.writeByte(8); // bit depth
+ header.writeByte(2); // truecolour
+ header.writeByte(0); // compression
+ header.writeByte(0); // filter
+ header.writeByte(0); // no interlace
+ chunk(data, "IHDR", ihdr.toByteArray());
+
+ Deflater deflater = new Deflater();
+ deflater.setInput(new byte[1024]);
+ deflater.finish();
+ byte[] buf = new byte[1024];
+ int n = deflater.deflate(buf);
+ deflater.end();
+ chunk(data, "IDAT", java.util.Arrays.copyOf(buf, n));
+ chunk(data, "IEND", new byte[0]);
+ return out.toByteArray();
+ }
+
+ private static void chunk(DataOutputStream out, String type, byte[] body)
+ throws Exception {
+ byte[] name = type.getBytes(StandardCharsets.US_ASCII);
+ CRC32 crc = new CRC32();
+ crc.update(name);
+ crc.update(body);
+ out.writeInt(body.length);
+ out.write(name);
+ out.write(body);
+ out.writeInt((int) crc.getValue());
+ }
+}
diff --git
a/app/src/test/java/org/apache/roller/weblogger/business/jpa/ThumbnailSubsamplingTest.java
b/app/src/test/java/org/apache/roller/weblogger/business/jpa/ThumbnailSubsamplingTest.java
new file mode 100644
index 000000000..b4d8de6d3
--- /dev/null
+++
b/app/src/test/java/org/apache/roller/weblogger/business/jpa/ThumbnailSubsamplingTest.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.roller.weblogger.business.jpa;
+
+import org.apache.roller.weblogger.pojos.MediaFile;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Images are decoded for their thumbnail at about twice the thumbnail size
+ * in both directions, and images too narrow to scale get no thumbnail.
+ */
+class ThumbnailSubsamplingTest {
+
+ @Test
+ void photoIsDecodedAtAboutTwiceThumbnailSize() {
+ // a 6000 x 4000 photo has a 120 x 80 thumbnail
+ assertEquals(25, JPAMediaFileManagerImpl.thumbnailSubsampling(6000,
4000, 120, 80));
+ }
+
+ @Test
+ void smallImageIsDecodedInFull() {
+ assertEquals(1, JPAMediaFileManagerImpl.thumbnailSubsampling(100, 50,
100, 50));
+ assertEquals(1, JPAMediaFileManagerImpl.thumbnailSubsampling(300, 200,
120, 80));
+ }
+
+ @Test
+ void longerSideDecidesTheStep() {
+ // 12000 x 100 has a 120 x 1 thumbnail; both sides are subsampled
+ assertEquals(50, JPAMediaFileManagerImpl.thumbnailSubsampling(12000,
100, 120, 1));
+ assertEquals(50, JPAMediaFileManagerImpl.thumbnailSubsampling(100,
12000, 1, 120));
+ }
+
+ @Test
+ void imageTooNarrowForThumbnailIsNotDecoded() {
+ // the thumbnail of a 50,000,000 x 1 image would be 120 x 0
+ assertEquals(0,
JPAMediaFileManagerImpl.thumbnailSubsampling(50_000_000, 1, 120, 0));
+ assertEquals(0, JPAMediaFileManagerImpl.thumbnailSubsampling(1,
50_000_000, 0, 120));
+ }
+
+ /** A new size gives a new thumbnail size, as when an image is replaced. */
+ @Test
+ void thumbnailSizeFollowsNewImageSize() {
+ MediaFile mediaFile = new MediaFile();
+ mediaFile.setContentType("image/png");
+ mediaFile.setWidth(500);
+ mediaFile.setHeight(373);
+ assertEquals(120, mediaFile.getThumbnailWidth());
+ assertEquals(89, mediaFile.getThumbnailHeight());
+
+ mediaFile.setWidth(400);
+ mediaFile.setHeight(2000);
+ assertEquals(24, mediaFile.getThumbnailWidth());
+ assertEquals(120, mediaFile.getThumbnailHeight());
+ }
+}
diff --git
a/app/src/test/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceThumbnailTest.java
b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceThumbnailTest.java
new file mode 100644
index 000000000..7f6e21b9a
--- /dev/null
+++
b/app/src/test/java/org/apache/roller/weblogger/ui/rendering/servlets/MediaResourceThumbnailTest.java
@@ -0,0 +1,187 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.roller.weblogger.ui.rendering.servlets;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import javax.servlet.ServletOutputStream;
+import javax.servlet.WriteListener;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.roller.weblogger.business.MediaFileManager;
+import org.apache.roller.weblogger.business.Weblogger;
+import org.apache.roller.weblogger.business.WebloggerFactory;
+import org.apache.roller.weblogger.pojos.MediaFile;
+import org.apache.roller.weblogger.pojos.Weblog;
+import
org.apache.roller.weblogger.ui.rendering.util.WeblogMediaResourceRequest;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedConstruction;
+import org.mockito.MockedStatic;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockConstruction;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * A thumbnail request for an image without a thumbnail, also one too large
+ * to get a thumbnail, is answered with the original, so entries that embed
+ * the thumbnail address keep showing the image.
+ */
+class MediaResourceThumbnailTest {
+
+ private static final String FILE_ID =
"3b6d1f0a-7c2e-4e5a-8d9b-0a1b2c3d4e5f";
+
+ private MockedStatic<WebloggerFactory> factory;
+ private Weblog weblog;
+ private MediaFile file;
+ private MediaResourceServlet servlet;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ MediaFileManager media = mock(MediaFileManager.class);
+ Weblogger roller = mock(Weblogger.class);
+ when(roller.getMediaFileManager()).thenReturn(media);
+ factory = mockStatic(WebloggerFactory.class);
+ factory.when(WebloggerFactory::getWeblogger).thenReturn(roller);
+
+ weblog = mock(Weblog.class);
+ when(weblog.getId()).thenReturn("weblog-id");
+ when(weblog.getHandle()).thenReturn("photos");
+
+ file = mock(MediaFile.class);
+ when(file.getId()).thenReturn(FILE_ID);
+ when(file.getWeblog()).thenReturn(weblog);
+ when(file.getName()).thenReturn("panorama.png");
+ when(file.getContentType()).thenReturn("image/png");
+ when(file.isImageFile()).thenReturn(true);
+ when(file.getLastModified()).thenReturn(0L);
+ when(file.getInputStream()).thenAnswer(call -> stream("original"));
+ when(media.getMediaFile(FILE_ID, true)).thenReturn(file);
+ // the servlet may look the file up in the addressed weblog first
+ when(media.getMediaFile(any(Weblog.class),
eq(FILE_ID))).thenReturn(file);
+
+ servlet = new MediaResourceServlet();
+ }
+
+ @AfterEach
+ void tearDown() {
+ factory.close();
+ }
+
+ @Test
+ void thumbnailOfImageTooLargeForOneFallsBackToOriginal() throws Exception {
+ when(file.getThumbnailInputStream()).thenReturn(null);
+ when(file.isThumbnailSkipped()).thenReturn(true);
+
+ ByteArrayOutputStream written = new ByteArrayOutputStream();
+ HttpServletResponse response = serve(true, written);
+
+ verify(response, never()).sendError(anyInt());
+ assertEquals("original",
written.toString(StandardCharsets.UTF_8.name()));
+ }
+
+ @Test
+ void imageStoredWithoutThumbnailIsStillServedInFull() throws Exception {
+ when(file.isThumbnailSkipped()).thenReturn(true);
+
+ ByteArrayOutputStream written = new ByteArrayOutputStream();
+ HttpServletResponse response = serve(false, written);
+
+ verify(response, never()).sendError(anyInt());
+ assertEquals("original",
written.toString(StandardCharsets.UTF_8.name()));
+ }
+
+ @Test
+ void thumbnailIsServedWhenPresent() throws Exception {
+ when(file.getThumbnailInputStream()).thenAnswer(call ->
stream("thumbnail"));
+
+ ByteArrayOutputStream written = new ByteArrayOutputStream();
+ HttpServletResponse response = serve(true, written);
+
+ verify(response, never()).sendError(anyInt());
+ assertEquals("thumbnail",
written.toString(StandardCharsets.UTF_8.name()));
+ }
+
+ /** An image that simply has no thumbnail, e.g. one ImageIO can't read. */
+ @Test
+ void missingThumbnailOfUnreadImageFallsBackToOriginal() throws Exception {
+ when(file.getThumbnailInputStream()).thenReturn(null);
+ when(file.isThumbnailSkipped()).thenReturn(false);
+
+ ByteArrayOutputStream written = new ByteArrayOutputStream();
+ HttpServletResponse response = serve(true, written);
+
+ verify(response, never()).sendError(anyInt());
+ assertEquals("original",
written.toString(StandardCharsets.UTF_8.name()));
+ }
+
+ private static ByteArrayInputStream stream(String text) {
+ return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
+ }
+
+ private HttpServletResponse serve(boolean thumbnail, ByteArrayOutputStream
written)
+ throws Exception {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ when(request.getDateHeader("If-Modified-Since")).thenReturn(-1L);
+ HttpServletResponse response = mock(HttpServletResponse.class);
+ when(response.getOutputStream()).thenReturn(new
CapturingStream(written));
+
+ try (MockedConstruction<WeblogMediaResourceRequest> parsed =
mockConstruction(
+ WeblogMediaResourceRequest.class, (mocked, ctx) -> {
+ when(mocked.getWeblog()).thenReturn(weblog);
+ when(mocked.getWeblogHandle()).thenReturn("photos");
+ when(mocked.getResourceId()).thenReturn(FILE_ID);
+ when(mocked.isThumbnail()).thenReturn(thumbnail);
+ })) {
+ servlet.doGet(request, response);
+ }
+ return response;
+ }
+
+ private static final class CapturingStream extends ServletOutputStream {
+ private final ByteArrayOutputStream target;
+
+ CapturingStream(ByteArrayOutputStream target) {
+ this.target = target;
+ }
+
+ @Override
+ public void write(int b) {
+ target.write(b);
+ }
+
+ @Override
+ public boolean isReady() {
+ return true;
+ }
+
+ @Override
+ public void setWriteListener(WriteListener listener) {
+ }
+ }
+}