< Return to Feed
Sean McKaharay - 03.13.2017

Custom Thumbnail Servlet

What image rendition should I use? AEM has a workflow that will create all kinds of renditions depending on how you want to work with your original image. AEM has a ThumbnailServlet. Now given that information, we have created a better more extensible servlet that can be customized any way you like it.


@Override
	protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
		// Convert request to convenience object
		RenditionMeta renditionMeta = buildRenditionMeta(request);
		if (renditionMeta == null) {
			log.debug("Failed to build rendition meta for {}", request.getPathInfo());
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		// Resolve image resource
		Resource resource = request.getResource();
		if (resource == null) {
			log.debug("Missing dam asset at {}", request.getPathInfo());
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		// Adapt image resource to dam object, supports node with fileReference to image
		Asset damAsset = resource.adaptTo(Asset.class);
		if (damAsset == null) {
			damAsset = extractAssetFromFileReference(resource);
		}
		if (damAsset == null) {
			log.debug("Cannot resolve dam asset at {} for {}", resource.getPath(), request.getPathInfo());
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		// Resolve dam asset + meta data to actual rendition
		Rendition rendition = assetRenditionResolver.resolveRendition(damAsset, renditionMeta);
		if (rendition == null) {
			//If rendition is not available then get known web rendition
			renditionMeta = buildRenditionMeta(request, 1280, 1280);
			rendition = assetRenditionResolver.resolveRendition(damAsset, renditionMeta);
			
			if(rendition == null){
				if (redirectOnMissingRendition) {
					sendRedirectToOriginalRendition(request, response, damAsset);
					return;
				} else {
					log.debug("Missing rendition for {} and {}", renditionMeta, damAsset.getPath());
					response.sendError(HttpServletResponse.SC_NOT_FOUND);
					return;
				}
			}
		}
		
		// If extension does not match rendition mime type, redirect or 415 error
		if (!rendition.getMimeType().contains(renditionMeta.getExtension())) {
			if (redirectOnWrongType) {
				sendRedirectToProperExtension(request, response, rendition, renditionMeta);
				return;
			} else {
				log.debug("Wrong extension for {} and request {}", rendition.getMimeType(), renditionMeta.getExtension());
				response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
				return;
			}
		}
		
		writeResponse(response, rendition);
	}