Search in sources :

Example 16 with Resource

use of org.apache.sling.api.resource.Resource in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class AdaptiveImageServlet method resizeAndStream.

/**
     * Calling this method will copy the image's bytes into the response's output stream, after performing all the needed transformations
     * on the requested image.
     *
     * @param request         the request
     * @param response        the response
     * @param image           the image component resource
     * @param imageProperties the image properties
     * @param resizeWidth     the width to which the image has to be resized
     */
private void resizeAndStream(SlingHttpServletRequest request, SlingHttpServletResponse response, Resource image, ValueMap imageProperties, int resizeWidth) throws IOException {
    if (resizeWidth < 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    String fileReference = imageProperties.get(DownloadResource.PN_REFERENCE, String.class);
    String imageType = getImageType(request.getRequestPathInfo().getExtension());
    String extension = mimeTypeService.getExtension(imageType);
    Asset asset = null;
    Resource imageFile = null;
    if (StringUtils.isNotEmpty(fileReference)) {
        // the image is coming from DAM
        final Resource assetResource = request.getResourceResolver().getResource(fileReference);
        if (assetResource == null) {
            LOGGER.error(String.format("Unable to find resource %s used by image %s.", fileReference, image.getPath()));
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        asset = assetResource.adaptTo(Asset.class);
        if (asset == null) {
            LOGGER.error(String.format("Unable to adapt resource %s used by image %s to an asset.", fileReference, image.getPath()));
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if ("gif".equalsIgnoreCase(extension)) {
            LOGGER.debug("GIF asset detected; will render the original rendition.");
            stream(response, asset.getOriginal().getStream(), imageType);
            return;
        }
    } else {
        imageFile = image.getChild(DownloadResource.NN_FILE);
        if ("gif".equalsIgnoreCase(extension)) {
            LOGGER.debug("GIF file detected; will render the original file.");
            InputStream is = imageFile.adaptTo(InputStream.class);
            if (is != null) {
                stream(response, is, imageType);
            }
            return;
        }
    }
    if (asset != null) {
        int rotationAngle = getRotation(image, imageProperties);
        Rectangle rectangle = getCropRect(image, imageProperties);
        if (rotationAngle != 0 || rectangle != null || resizeWidth > 0) {
            int originalWidth = getDimension(asset.getMetadataValue(DamConstants.TIFF_IMAGEWIDTH));
            int originalHeight = getDimension(asset.getMetadataValue(DamConstants.TIFF_IMAGELENGTH));
            AssetHandler assetHandler = assetStore.getAssetHandler(imageType);
            Layer layer = null;
            boolean appliedRotationOrCropping = false;
            if (rectangle != null) {
                double scaling;
                Rendition webRendition = getAWebRendition(asset);
                double renditionWidth = 1280D;
                if (webRendition != null) {
                    try {
                        renditionWidth = Double.parseDouble(webRendition.getName().split("\\.")[2]);
                        LOGGER.debug("Found rendition {} with width {}px; assuming the cropping rectangle was calculated using this " + "rendition.", webRendition.getPath(), renditionWidth);
                    } catch (NumberFormatException e) {
                        LOGGER.warn("Cannot determine rendition width for {}. Will fallback to 1280px.", webRendition.getPath());
                    }
                } else {
                    renditionWidth = originalWidth;
                }
                if (originalWidth > renditionWidth) {
                    scaling = (double) originalWidth / renditionWidth;
                } else {
                    scaling = renditionWidth / originalWidth;
                }
                layer = new Layer(assetHandler.getImage(asset.getOriginal()));
                if (Math.abs(scaling - 1.0D) != 0) {
                    Rectangle scaledRectangle = new Rectangle((int) (rectangle.x * scaling), (int) (rectangle.y * scaling), (int) (rectangle.getWidth() * scaling), (int) (rectangle.getHeight() * scaling));
                    layer.crop(scaledRectangle);
                } else {
                    layer.crop(rectangle);
                }
                appliedRotationOrCropping = true;
            }
            if (rotationAngle != 0) {
                if (layer == null) {
                    layer = new Layer(assetHandler.getImage(asset.getOriginal()));
                }
                layer.rotate(rotationAngle);
                LOGGER.debug("Applied rotation transformation ({} degrees).", rotationAngle);
                appliedRotationOrCropping = true;
            }
            if (!appliedRotationOrCropping) {
                Rendition rendition = asset.getRendition(String.format(DamConstants.PREFIX_ASSET_WEB + ".%d.%d.%s", resizeWidth, resizeWidth, extension));
                if (rendition != null) {
                    LOGGER.debug("Found rendition {} with a width equal to the resize width ({}px); rendering.", rendition.getPath(), resizeWidth);
                    stream(response, rendition.getStream(), imageType);
                } else {
                    int resizeHeight = calculateResizeHeight(originalWidth, originalHeight, resizeWidth);
                    if (resizeHeight > 0 && resizeHeight != originalHeight) {
                        layer = new Layer(assetHandler.getImage(asset.getOriginal()));
                        layer.resize(resizeWidth, resizeHeight);
                        response.setContentType(imageType);
                        LOGGER.debug("Resizing asset {} to requested width of {}px; rendering.", asset.getPath(), resizeWidth);
                        layer.write(imageType, 1.0, response.getOutputStream());
                    } else {
                        LOGGER.debug("Rendering the original asset {} since its width ({}px) is either smaller than the requested " + "width ({}px) or since no resize is needed.", asset.getPath(), originalWidth, resizeWidth);
                        stream(response, asset.getOriginal().getStream(), imageType);
                    }
                }
            } else {
                resizeAndStreamLayer(response, layer, imageType, resizeWidth);
            }
        } else {
            LOGGER.debug("No need to perform any processing on asset {}; rendering.", asset.getPath());
            stream(response, asset.getOriginal().getStream(), imageType);
        }
    } else if (imageFile != null) {
        InputStream is = null;
        try {
            is = imageFile.adaptTo(InputStream.class);
            int rotationAngle = getRotation(image, imageProperties);
            Rectangle rectangle = getCropRect(image, imageProperties);
            if (rotationAngle != 0 || rectangle != null || resizeWidth > 0) {
                Layer layer = null;
                if (rectangle != null) {
                    layer = new Layer(is);
                    layer.crop(rectangle);
                    LOGGER.debug("Applied cropping transformation.");
                }
                if (rotationAngle != 0) {
                    if (layer == null) {
                        layer = new Layer(is);
                    }
                    layer.rotate(rotationAngle);
                    LOGGER.debug("Applied rotation transformation ({} degrees).", rotationAngle);
                }
                if (layer == null) {
                    layer = new Layer(is);
                }
                resizeAndStreamLayer(response, layer, imageType, resizeWidth);
            } else {
                LOGGER.debug("No need to perform any processing on file {}; rendering.", imageFile.getPath());
                stream(response, is, imageType);
            }
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}
Also used : InputStream(java.io.InputStream) Rendition(com.day.cq.dam.api.Rendition) DownloadResource(com.day.cq.commons.DownloadResource) Resource(org.apache.sling.api.resource.Resource) ImageResource(com.day.cq.commons.ImageResource) Asset(com.day.cq.dam.api.Asset) AssetHandler(com.day.cq.dam.api.handler.AssetHandler) Layer(com.day.image.Layer)

Example 17 with Resource

use of org.apache.sling.api.resource.Resource in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class TitleImplTest method testGetTitleFromResourceWithElementInfo.

@Test
public void testGetTitleFromResourceWithElementInfo() {
    Resource resource = context.currentResource(TITLE_RESOURCE_JCR_TITLE_TYPE);
    slingBindings.put(WCMBindings.CURRENT_STYLE, new MockStyle(resource));
    underTest = context.request().adaptTo(Title.class);
    assertEquals("Hello World", underTest.getText());
    assertEquals("h2", underTest.getType());
}
Also used : Resource(org.apache.sling.api.resource.Resource) MockStyle(com.adobe.cq.wcm.core.components.context.MockStyle) Title(com.adobe.cq.wcm.core.components.models.Title) Test(org.junit.Test)

Example 18 with Resource

use of org.apache.sling.api.resource.Resource in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class MockContentPolicyMapping method getPolicy.

@Override
public ContentPolicy getPolicy() {
    ValueMap valueMap = contentPolicyResource.adaptTo(ValueMap.class);
    if (valueMap.containsKey("cq:policy")) {
        String policyPath = valueMap.get("cq:policy", StringUtils.EMPTY);
        if (StringUtils.isNotEmpty(policyPath)) {
            policyPath = "/conf/coretest/settings/wcm/policies/" + policyPath;
            Resource policyResource = contentPolicyResource.getResourceResolver().getResource(policyPath);
            if (policyResource != null) {
                return new MockContentPolicy(policyResource);
            }
        }
    }
    return null;
}
Also used : ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource)

Example 19 with Resource

use of org.apache.sling.api.resource.Resource in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class WCMUsePojoBaseTest method getResourceBackedBindings.

/**
     * <p>
     * Creates a {@link Bindings} map initialised with the following default bindings available to Sightly use objects based on {@link
     * WCMUsePojo}:
     * </p>
     * <ul>
     * <li>{@link SlingBindings#RESOURCE}</li>
     * <li>{@link SlingBindings#REQUEST}</li>
     * <li>{@link SlingBindings#RESPONSE}</li>
     * <li>{@link WCMBindings#PROPERTIES}</li>
     * <li>{@link WCMBindings#WCM_MODE}</li>
     * <li>{@link WCMBindings#PAGE_MANAGER}</li>
     * <li>{@link WCMBindings#RESOURCE_PAGE}</li>
     * <li>{@link WCMBindings#CURRENT_PAGE}</li>
     * <li>{@link WCMBindings#PAGE_PROPERTIES}</li>
     * </ul>
     *
     * @param resourcePath the path to a resource already loaded in the testing context
     * @return the bindings map
     */
protected Bindings getResourceBackedBindings(String resourcePath) {
    Bindings bindings = getDefaultSlingBindings();
    Resource resource = context.resourceResolver().getResource(resourcePath);
    if (resource != null) {
        ValueMap properties = resource.adaptTo(ValueMap.class);
        bindings.put(SlingBindings.RESOURCE, resource);
        bindings.put(WCMBindings.PROPERTIES, properties);
        bindings.put(WCMBindings.WCM_MODE, new SightlyWCMMode(context.request()));
        PageManager pageManager = context.pageManager();
        bindings.put(WCMBindings.PAGE_MANAGER, pageManager);
        context.request().setResource(resource);
        Page resourcePage = pageManager.getContainingPage(resource);
        if (resourcePage != null) {
            bindings.put(WCMBindings.RESOURCE_PAGE, resourcePage);
            bindings.put(WCMBindings.CURRENT_PAGE, resourcePage);
            bindings.put(WCMBindings.PAGE_PROPERTIES, properties);
        }
    } else {
        throw new IllegalArgumentException("Cannot find a resource at " + resourcePath);
    }
    return bindings;
}
Also used : PageManager(com.day.cq.wcm.api.PageManager) ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) Page(com.day.cq.wcm.api.Page) SightlyWCMMode(com.adobe.cq.sightly.SightlyWCMMode) Bindings(javax.script.Bindings) SlingBindings(org.apache.sling.api.scripting.SlingBindings) SimpleBindings(javax.script.SimpleBindings) WCMBindings(com.adobe.cq.sightly.WCMBindings)

Example 20 with Resource

use of org.apache.sling.api.resource.Resource in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class TitleImplTest method testGetTitleFromResource.

@Test
public void testGetTitleFromResource() {
    Resource resource = context.currentResource(TITLE_RESOURCE_JCR_TITLE);
    slingBindings.put(WCMBindings.CURRENT_STYLE, new MockStyle(resource));
    underTest = context.request().adaptTo(Title.class);
    assertEquals("Hello World", underTest.getText());
    assertNull(underTest.getType());
}
Also used : Resource(org.apache.sling.api.resource.Resource) MockStyle(com.adobe.cq.wcm.core.components.context.MockStyle) Title(com.adobe.cq.wcm.core.components.models.Title) Test(org.junit.Test)

Aggregations

Resource (org.apache.sling.api.resource.Resource)1569 Test (org.junit.Test)695 ValueMap (org.apache.sling.api.resource.ValueMap)338 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)260 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)164 HashMap (java.util.HashMap)160 Node (javax.jcr.Node)151 ArrayList (java.util.ArrayList)137 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)119 PersistenceException (org.apache.sling.api.resource.PersistenceException)114 Test (org.junit.jupiter.api.Test)72 Map (java.util.Map)70 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)70 HttpServletRequest (javax.servlet.http.HttpServletRequest)62 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)60 FakeSlingHttpServletRequest (org.apache.sling.launchpad.testservices.exported.FakeSlingHttpServletRequest)59 LoginException (org.apache.sling.api.resource.LoginException)58 RepositoryException (javax.jcr.RepositoryException)54 Calendar (java.util.Calendar)50 Session (javax.jcr.Session)49