/
AbstractImageDelegatingModel.java
68 lines (56 loc) · 2.78 KB
/
AbstractImageDelegatingModel.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.techrevel.core.models.impl;
import com.adobe.cq.wcm.core.components.util.AbstractComponentImpl;
import com.day.cq.commons.DownloadResource;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.techrevel.core.internal.resources.ImageResourceWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
public abstract class AbstractImageDelegatingModel extends AbstractComponentImpl {
/**
* Component property name that indicates which Image Component will perform the image rendering for composed components. When
* rendering images, the composed components that provide this property will be able to retrieve the content policy defined for the
* Image Component's resource type.
*/
public static final String IMAGE_DELEGATE = "imageDelegate";
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractImageDelegatingModel.class);
private Resource toBeWrappedResource;
private Resource imageResource;
protected void setImageResource( @NotNull Resource toBeWrappedResource) {
this.toBeWrappedResource = toBeWrappedResource;
}
@JsonIgnore
public Resource getImageResource() {
if (imageResource == null && component != null) {
String delegateResourceType = component.getProperties().get(IMAGE_DELEGATE, String.class);
if (StringUtils.isEmpty(delegateResourceType)) {
LOGGER.error("In order for image rendering delegation to work correctly you need to set up the imageDelegate property on" +
" the {} component; its value has to point to the resource type of an image component.", component.getPath());
} else {
imageResource = new ImageResourceWrapper(toBeWrappedResource, delegateResourceType);
}
}
return imageResource;
}
/**
* Check if the component has an image.
*
* The component has an image if the `{@value DownloadResource#PN_REFERENCE}` property is set and the value
* resolves to a resource; or if the `{@value DownloadResource#NN_FILE} child resource exists.
*
* @return True if the component has an image, false if it does not.
*/
protected boolean hasImage() {
return Optional.ofNullable(this.resource.getValueMap().get(DownloadResource.PN_REFERENCE, String.class))
.map(request.getResourceResolver()::getResource)
.orElseGet(() -> request.getResource().getChild(DownloadResource.NN_FILE)) != null;
}
protected void initImage() {
if (this.hasImage()) {
this.setImageResource(request.getResource());
}
}
}