Search in sources :

Example 81 with Image

use of com.adobe.cq.wcm.core.components.models.Image in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class ImageImplTest method testImageWithTwoOrMoreSmartSizes.

@Test
@SuppressWarnings("deprecation")
@Override
protected void testImageWithTwoOrMoreSmartSizes() {
    context.contentPolicyMapping(resourceType, "allowedRenditionWidths", new int[] { 600, 700, 800, 2000, 2500 });
    String escapedResourcePath = AbstractImageTest.IMAGE0_PATH.replace("jcr:content", "_jcr_content");
    Image image = getImageUnderTest(AbstractImageTest.IMAGE0_PATH);
    assertEquals("Adobe Systems Logo and Wordmark in PNG format", image.getAlt());
    assertEquals("Adobe Systems Logo and Wordmark", image.getTitle());
    assertEquals(IMAGE_FILE_REFERENCE, image.getFileReference());
    String expectedJson = "{\"smartImages\":[\"/core/content/test/_jcr_content/root/image0." + selector + "." + JPEG_QUALITY + ".600.png/1490005239000/" + ASSET_NAME + ".png\",\"/core/content/test/_jcr_content/root/image0." + selector + "." + JPEG_QUALITY + ".700.png/1490005239000/" + ASSET_NAME + ".png\",\"/core/content/test/_jcr_content/root/image0" + "." + selector + "." + JPEG_QUALITY + ".800.png/1490005239000/" + ASSET_NAME + ".png\",\"/core/content/test/_jcr_content/root/image0." + selector + "." + JPEG_QUALITY + ".2000.png/1490005239000/" + ASSET_NAME + ".png\", \"/core/content/test/_jcr_content/root/image0." + selector + "." + JPEG_QUALITY + ".2500.png/1490005239000/" + ASSET_NAME + ".png\"],\"smartSizes\":[600,700,800,2000,2500],\"lazyEnabled\":false}";
    compareJSON(expectedJson, image.getJson());
    assertTrue(image.displayPopupTitle());
    assertEquals(CONTEXT_PATH + "/content/test-image.html", image.getLink());
    assertEquals(CONTEXT_PATH + escapedResourcePath + "." + selector + ".png/1490005239000/" + ASSET_NAME + ".png", image.getSrc());
    Utils.testJSONExport(image, Utils.getTestExporterJSONPath(testBase, AbstractImageTest.IMAGE0_PATH));
}
Also used : Image(com.adobe.cq.wcm.core.components.models.Image) AbstractImageTest(com.adobe.cq.wcm.core.components.internal.models.v1.AbstractImageTest) Test(org.junit.jupiter.api.Test)

Example 82 with Image

use of com.adobe.cq.wcm.core.components.models.Image in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class ImageImplTest method testImageFromTemplateStructure.

@Test
@SuppressWarnings("deprecation")
@Override
protected void testImageFromTemplateStructure() {
    context.contentPolicyMapping(resourceType, "allowedRenditionWidths", new int[] { 600, 700, 800, 2000, 2500 });
    com.adobe.cq.wcm.core.components.models.Image image = getImageUnderTest(TEMPLATE_IMAGE_PATH);
    assertEquals(CONTEXT_PATH + "/conf/coretest/settings/wcm/templates/testtemplate/structure." + selector + ".png/structure/jcr%3acontent/root/image_template/1490005239000/" + ASSET_NAME + ".png", image.getSrc());
    assertEquals("Adobe Systems Logo and Wordmark in PNG format", image.getAlt());
    assertEquals("Adobe Systems Logo and Wordmark", image.getTitle());
    assertEquals(IMAGE_FILE_REFERENCE, image.getFileReference());
    String expectedJson = "{" + "\"smartImages\":[" + "\"/core/conf/coretest/settings/wcm/templates/testtemplate/structure." + selector + "." + JPEG_QUALITY + ".600.png/structure/jcr%3acontent/root/image_template/1490005239000/" + ASSET_NAME + ".png\",\"/core/conf/coretest/settings/wcm/templates/testtemplate/structure." + selector + "." + JPEG_QUALITY + ".700.png/structure/jcr%3acontent/root/image_template/1490005239000/" + ASSET_NAME + ".png\", \"/core/conf/coretest/settings/wcm/templates/testtemplate/structure." + selector + "." + JPEG_QUALITY + ".800.png/structure/jcr%3acontent/root/image_template/1490005239000/" + ASSET_NAME + ".png\"," + "\"/core/conf/coretest/settings/wcm/templates/testtemplate/structure." + selector + "." + JPEG_QUALITY + "." + "2000.png/structure/jcr%3acontent/root/image_template/1490005239000/" + ASSET_NAME + ".png\"," + "\"/core/conf/coretest/settings/wcm/templates/testtemplate/structure." + selector + "." + JPEG_QUALITY + ".2500.png/structure/jcr%3acontent/root/image_template/1490005239000/" + ASSET_NAME + ".png\"" + "]," + "\"smartSizes\":[600,700,800,2000,2500]," + "\"lazyEnabled\":false" + "}";
    compareJSON(expectedJson, image.getJson());
    assertTrue(image.displayPopupTitle());
    assertEquals(CONTEXT_PATH + "/content/test-image.html", image.getLink());
    Utils.testJSONExport(image, Utils.getTestExporterJSONPath(testBase, TEMPLATE_IMAGE_PATH));
}
Also used : Image(com.adobe.cq.wcm.core.components.models.Image) AbstractImageTest(com.adobe.cq.wcm.core.components.internal.models.v1.AbstractImageTest) Test(org.junit.jupiter.api.Test)

Example 83 with Image

use of com.adobe.cq.wcm.core.components.models.Image in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class ImageImplTest method testSimpleDecorativeImage.

@Test
@SuppressWarnings("deprecation")
@Override
protected void testSimpleDecorativeImage() {
    context.contentPolicyMapping(resourceType, "uuidDisabled", true);
    String escapedResourcePath = AbstractImageTest.IMAGE4_PATH.replace("jcr:content", "_jcr_content");
    com.adobe.cq.wcm.core.components.models.Image image = getImageUnderTest(AbstractImageTest.IMAGE4_PATH);
    assertNull(image.getAlt(), "Did not expect a value for the alt attribute, since the image is marked as decorative.");
    assertEquals("Adobe Systems Logo and Wordmark", image.getTitle());
    assertTrue(image.displayPopupTitle(), "Image should display a caption popup.");
    assertNull(image.getLink(), "Did not expect a link for this image, since it's marked as decorative.");
    assertEquals(CONTEXT_PATH + escapedResourcePath + "." + selector + ".png/1494867377756/" + ASSET_NAME + ".png", image.getSrc());
    compareJSON("{\"" + com.adobe.cq.wcm.core.components.models.Image.JSON_SMART_IMAGES + "\":[], \"" + com.adobe.cq.wcm.core.components.models.Image.JSON_SMART_SIZES + "\":[], \"" + com.adobe.cq.wcm.core.components.models.Image.JSON_LAZY_ENABLED + "\":false}", image.getJson());
    Utils.testJSONExport(image, Utils.getTestExporterJSONPath(testBase, AbstractImageTest.IMAGE4_PATH));
}
Also used : Image(com.adobe.cq.wcm.core.components.models.Image) AbstractImageTest(com.adobe.cq.wcm.core.components.internal.models.v1.AbstractImageTest) Test(org.junit.jupiter.api.Test)

Example 84 with Image

use of com.adobe.cq.wcm.core.components.models.Image in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class AdaptiveImageServlet method doGet.

@Override
protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response) throws IOException {
    Timer.Context requestDuration = metrics.startDurationRecording();
    try {
        metrics.markServletInvocation();
        RequestPathInfo requestPathInfo = request.getRequestPathInfo();
        List<String> selectorList = selectorToList(requestPathInfo.getSelectorString());
        String suffix = requestPathInfo.getSuffix();
        String imageName = StringUtils.isNotEmpty(suffix) ? FilenameUtils.getName(suffix) : "";
        if (StringUtils.isNotEmpty(suffix)) {
            String suffixExtension = FilenameUtils.getExtension(suffix);
            if (StringUtils.isNotEmpty(suffixExtension)) {
                if (!suffixExtension.equals(requestPathInfo.getExtension())) {
                    LOGGER.error("The suffix part defines a different extension than the request: {}.", suffix);
                    metrics.markImageErrors();
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
                }
            } else {
                LOGGER.error("Invalid suffix: {}.", suffix);
                metrics.markImageErrors();
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }
        Resource component = request.getResource();
        ResourceResolver resourceResolver = request.getResourceResolver();
        if (!component.isResourceType(IMAGE_RESOURCE_TYPE)) {
            // image coming from template; need to switch resource
            Resource componentCandidate = null;
            PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
            if (pageManager != null) {
                Page page = pageManager.getContainingPage(component);
                if (page != null) {
                    Template template = page.getTemplate();
                    if (template != null) {
                        if (StringUtils.isNotEmpty(suffix)) {
                            long lastModifiedSuffix = getRequestLastModifiedSuffix(suffix);
                            String relativeTemplatePath = lastModifiedSuffix == 0 ? // no timestamp info, but extension is valid; get resource name
                            suffix.substring(0, suffix.lastIndexOf('.')) : // timestamp info, get parent path from suffix
                            suffix.substring(0, suffix.lastIndexOf("/" + String.valueOf(lastModifiedSuffix)));
                            String imagePath = ResourceUtil.normalize(template.getPath() + relativeTemplatePath);
                            if (StringUtils.isNotEmpty(imagePath) && !template.getPath().equals(imagePath)) {
                                componentCandidate = resourceResolver.getResource(imagePath);
                            }
                        }
                    }
                }
            }
            if (componentCandidate == null) {
                LOGGER.error("Unable to retrieve an image from this page's template.");
                metrics.markImageErrors();
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            component = componentCandidate;
        }
        LinkHandler linkHandler = request.adaptTo(LinkHandler.class);
        Style currentStyle = WCMUtils.getStyle(request);
        Page currentPage = Optional.ofNullable(resourceResolver.adaptTo(PageManager.class)).map(pageManager -> pageManager.getContainingPage(request.getResource())).orElse(null);
        Resource wrappedImageResourceWithInheritance = getWrappedImageResourceWithInheritance(component, linkHandler, currentStyle, currentPage);
        ImageComponent imageComponent = new ImageComponent(wrappedImageResourceWithInheritance);
        if (imageComponent.source == Source.NOCONTENT || imageComponent.source == Source.NONEXISTING) {
            LOGGER.error("Either the image from {} does not have a valid file reference" + " or the containing page does not have a valid featured image", component.getPath());
            metrics.markImageErrors();
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        ValueMap componentProperties = component.getValueMap();
        long lastModifiedEpoch = 0;
        Calendar lastModifiedDate = componentProperties.get(JcrConstants.JCR_LASTMODIFIED, Calendar.class);
        if (lastModifiedDate == null) {
            lastModifiedDate = componentProperties.get(NameConstants.PN_PAGE_LAST_MOD, Calendar.class);
        }
        if (lastModifiedDate != null) {
            lastModifiedEpoch = lastModifiedDate.getTimeInMillis();
        }
        Asset asset = null;
        if (imageComponent.source == Source.ASSET) {
            asset = imageComponent.imageResource.adaptTo(Asset.class);
            if (asset == null) {
                LOGGER.error("Unable to adapt resource {} used by image {} to an asset.", imageComponent.imageResource.getPath(), component.getPath());
                metrics.markImageErrors();
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            long assetLastModifiedEpoch = asset.getLastModified();
            if (assetLastModifiedEpoch > lastModifiedEpoch) {
                lastModifiedEpoch = assetLastModifiedEpoch;
            }
        }
        long requestLastModifiedSuffix = getRequestLastModifiedSuffix(suffix);
        if (requestLastModifiedSuffix >= 0 && requestLastModifiedSuffix != lastModifiedEpoch) {
            String redirectLocation = getRedirectLocation(request, lastModifiedEpoch);
            if (StringUtils.isNotEmpty(redirectLocation)) {
                response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                response.setHeader("Location", redirectLocation);
                return;
            } else {
                LOGGER.error("Unable to determine correct redirect location.");
                metrics.markImageErrors();
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        }
        if (!handleIfModifiedSinceHeader(request, response, lastModifiedEpoch)) {
            Map<String, Integer> transformationMap = getTransformationMap(selectorList, component);
            Integer jpegQualityInPercentage = transformationMap.get(SELECTOR_QUALITY_KEY);
            double quality = jpegQualityInPercentage / 100.0d;
            int resizeWidth = transformationMap.get(SELECTOR_WIDTH_KEY);
            String imageType = getImageType(requestPathInfo.getExtension());
            if (imageComponent.source == Source.FILE) {
                transformAndStreamFile(response, componentProperties, resizeWidth, quality, imageComponent.imageResource, imageType, imageName);
            } else if (imageComponent.source == Source.ASSET) {
                transformAndStreamAsset(response, componentProperties, resizeWidth, quality, asset, imageType, imageName);
            }
            metrics.markImageStreamed();
        }
    } catch (IllegalArgumentException e) {
        LOGGER.error("Invalid image request", e.getMessage());
        metrics.markImageErrors();
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } finally {
        requestDuration.stop();
    }
}
Also used : ValueMap(org.apache.sling.api.resource.ValueMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) SortedSet(java.util.SortedSet) ResourceUtil(org.apache.sling.api.resource.ResourceUtil) ContentPolicyManager(com.day.cq.wcm.api.policies.ContentPolicyManager) LoggerFactory(org.slf4j.LoggerFactory) DownloadResource(com.day.cq.commons.DownloadResource) StringUtils(org.apache.commons.lang3.StringUtils) Page(com.day.cq.wcm.api.Page) Layer(com.day.image.Layer) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) WCMUtils(com.day.cq.wcm.commons.WCMUtils) Matcher(java.util.regex.Matcher) Image(com.adobe.cq.wcm.core.components.models.Image) CharEncoding(org.apache.commons.lang3.CharEncoding) Map(java.util.Map) MimeTypeService(org.apache.sling.commons.mime.MimeTypeService) Splitter(com.google.common.base.Splitter) JcrConstants(org.apache.jackrabbit.JcrConstants) BufferedImage(java.awt.image.BufferedImage) HttpConstants(org.apache.sling.api.servlets.HttpConstants) SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) DamConstants(com.day.cq.dam.api.DamConstants) CoreResourceWrapper(com.adobe.cq.wcm.core.components.internal.resource.CoreResourceWrapper) PageManager(com.day.cq.wcm.api.PageManager) IOUtils(org.apache.commons.io.IOUtils) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) RequestPathInfo(org.apache.sling.api.request.RequestPathInfo) Optional(java.util.Optional) SlingSafeMethodsServlet(org.apache.sling.api.servlets.SlingSafeMethodsServlet) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) FilenameUtils(org.apache.commons.io.FilenameUtils) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) Utils.getWrappedImageResourceWithInheritance(com.adobe.cq.wcm.core.components.internal.Utils.getWrappedImageResourceWithInheritance) Joiner(com.google.common.base.Joiner) ComponentManager(com.day.cq.wcm.api.components.ComponentManager) LinkHandler(com.adobe.cq.wcm.core.components.internal.link.LinkHandler) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Style(com.day.cq.wcm.api.designer.Style) Calendar(java.util.Calendar) Lists(com.google.common.collect.Lists) WCMRenditionPicker(com.day.cq.wcm.foundation.WCMRenditionPicker) Timer(org.apache.sling.commons.metrics.Timer) Asset(com.day.cq.dam.api.Asset) Logger(org.slf4j.Logger) Rendition(com.day.cq.dam.api.Rendition) HttpServletResponse(javax.servlet.http.HttpServletResponse) Resource(org.apache.sling.api.resource.Resource) IOException(java.io.IOException) AbstractImageDelegatingModel(com.adobe.cq.wcm.core.components.internal.models.v1.AbstractImageDelegatingModel) java.awt(java.awt) URLEncoder(java.net.URLEncoder) Template(com.day.cq.wcm.api.Template) NameConstants(com.day.cq.wcm.api.NameConstants) Text(org.apache.jackrabbit.util.Text) AssetStore(com.day.cq.dam.api.handler.store.AssetStore) AssetHandler(com.day.cq.dam.api.handler.AssetHandler) ContentPolicy(com.day.cq.wcm.api.policies.ContentPolicy) ImageResource(com.day.cq.commons.ImageResource) Comparator(java.util.Comparator) InputStream(java.io.InputStream) ValueMap(org.apache.sling.api.resource.ValueMap) Calendar(java.util.Calendar) DownloadResource(com.day.cq.commons.DownloadResource) Resource(org.apache.sling.api.resource.Resource) ImageResource(com.day.cq.commons.ImageResource) Page(com.day.cq.wcm.api.Page) Template(com.day.cq.wcm.api.Template) RequestPathInfo(org.apache.sling.api.request.RequestPathInfo) PageManager(com.day.cq.wcm.api.PageManager) Timer(org.apache.sling.commons.metrics.Timer) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Style(com.day.cq.wcm.api.designer.Style) Asset(com.day.cq.dam.api.Asset) LinkHandler(com.adobe.cq.wcm.core.components.internal.link.LinkHandler)

Aggregations

Image (com.adobe.cq.wcm.core.components.models.Image)84 Test (org.junit.jupiter.api.Test)57 AbstractImageTest (com.adobe.cq.wcm.core.components.internal.models.v1.AbstractImageTest)46 Test (org.junit.Test)5 Matchers.anyString (org.mockito.Matchers.anyString)5 Page (com.day.cq.wcm.api.Page)3 PageManager (com.day.cq.wcm.api.PageManager)3 Resource (org.apache.sling.api.resource.Resource)3 Link (com.adobe.cq.wcm.core.components.commons.link.Link)2 LinkHandler (com.adobe.cq.wcm.core.components.internal.link.LinkHandler)2 CoreResourceWrapper (com.adobe.cq.wcm.core.components.internal.resource.CoreResourceWrapper)2 ImageArea (com.adobe.cq.wcm.core.components.models.ImageArea)2 Teaser (com.adobe.cq.wcm.core.components.models.Teaser)2 DownloadResource (com.day.cq.commons.DownloadResource)2 ImageResource (com.day.cq.commons.ImageResource)2 Template (com.day.cq.wcm.api.Template)2 Style (com.day.cq.wcm.api.designer.Style)2 StringReader (java.io.StringReader)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2