View Javadoc
1   /*
2    * #%L
3    * wcm.io
4    * %%
5    * Copyright (C) 2022 wcm.io
6    * %%
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   *
11   *      http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   * #L%
19   */
20  package io.wcm.siteapi.handler.caconfig.impl.property;
21  
22  import java.util.Map;
23  import java.util.stream.Collectors;
24  
25  import org.apache.commons.lang3.StringUtils;
26  import org.apache.sling.api.SlingHttpServletRequest;
27  import org.apache.sling.api.resource.Resource;
28  import org.apache.sling.api.resource.ResourceResolver;
29  import org.apache.sling.api.resource.ValueMap;
30  import org.apache.sling.api.wrappers.ValueMapDecorator;
31  import org.apache.sling.caconfig.spi.metadata.PropertyMetadata;
32  import org.jetbrains.annotations.NotNull;
33  import org.jetbrains.annotations.Nullable;
34  import org.osgi.service.component.annotations.Component;
35  import org.osgi.service.component.annotations.Reference;
36  import org.osgi.service.component.propertytypes.ServiceRanking;
37  import org.slf4j.Logger;
38  import org.slf4j.LoggerFactory;
39  
40  import com.day.cq.dam.api.DamConstants;
41  import com.day.cq.wcm.api.NameConstants;
42  import com.day.cq.wcm.api.Page;
43  
44  import io.wcm.handler.link.Link;
45  import io.wcm.handler.link.LinkHandler;
46  import io.wcm.handler.media.Media;
47  import io.wcm.handler.media.MediaArgs;
48  import io.wcm.handler.media.MediaComponentPropertyResolver;
49  import io.wcm.handler.media.MediaHandler;
50  import io.wcm.siteapi.handler.link.LinkDecoratorManager;
51  import io.wcm.siteapi.handler.media.MediaDecoratorManager;
52  import io.wcm.siteapi.processor.caconfig.ContextAwareConfigurationPropertyMapper;
53  import io.wcm.sling.commons.adapter.AdaptTo;
54  
55  /**
56   * Detects properties that use widgetType=pathbrowser.
57   * Depending on the actual path, those are either references to content pages or assets.
58   * A corresponding link or media object is resolved, and mapped to it's JSON representation.
59   */
60  @Component(service = ContextAwareConfigurationPropertyMapper.class)
61  @ServiceRanking(-250)
62  public class ContentPathPropertyMapper implements ContextAwareConfigurationPropertyMapper<Object> {
63  
64    // copied from io.wcm.caconfig.editor.EditorProperties to avoid direct dependency
65    static final String PROPERTY_WIDGET_TYPE = "widgetType";
66    static final String WIDGET_TYPE_PATHBROWSER = "pathbrowser";
67  
68    private static final Logger log = LoggerFactory.getLogger(ContentPathPropertyMapper.class);
69  
70    @Reference
71    private LinkDecoratorManager linkDecoratorManager;
72    @Reference
73    private MediaDecoratorManager mediaDecoratorManager;
74  
75    @Override
76    public boolean accept(@NotNull Object value,
77        @NotNull PropertyMetadata<?> metadata, @NotNull SlingHttpServletRequest request) {
78      Map<String, String> properties = metadata.getProperties();
79      if (properties == null) {
80        return false;
81      }
82      return StringUtils.equals(properties.get(PROPERTY_WIDGET_TYPE), WIDGET_TYPE_PATHBROWSER);
83    }
84  
85    @Override
86    public @Nullable Object map(@NotNull Object value,
87        @NotNull PropertyMetadata<?> metadata, @NotNull SlingHttpServletRequest request) {
88      Resource resource = getResource(value, request.getResourceResolver());
89      if (resource != null) {
90        if (isPage(resource)) {
91          return buildPageReference(resource, request);
92        }
93        else if (isAsset(resource)) {
94          return buildMediaReference(resource, metadata, request);
95        }
96      }
97      return null;
98    }
99  
100   /**
101    * Check if the given path points to a valid resource.
102    */
103   private @Nullable Resource getResource(@NotNull Object value, @NotNull ResourceResolver resourceResolver) {
104     if (value instanceof String) {
105       return resourceResolver.getResource((String)value);
106     }
107     else {
108       return null;
109     }
110   }
111 
112   /**
113    * Checks if the resource is a AEM page.
114    */
115   private boolean isPage(@NotNull Resource resource) {
116     return StringUtils.equals(resource.getResourceType(), NameConstants.NT_PAGE);
117   }
118 
119   /**
120    * Resolves a link to the page using link handler and returns the decorated reference.
121    */
122   private @Nullable Object buildPageReference(@NotNull Resource resource, @NotNull SlingHttpServletRequest request) {
123     Page page = resource.adaptTo(Page.class);
124     if (page == null) {
125       return null;
126     }
127     LinkHandler linkHandler = AdaptTo.notNull(request, LinkHandler.class);
128     Link link = linkHandler.get(page).build();
129     return linkDecoratorManager.decorate(link, request.getResource());
130   }
131 
132   /**
133    * Checks if the resource is an AEM asset.
134    */
135   private boolean isAsset(@NotNull Resource resource) {
136     return StringUtils.equals(resource.getResourceType(), DamConstants.NT_DAM_ASSET);
137   }
138 
139   /**
140    * Resolves a reference to the asset using media handler and returns the decorated reference.
141    */
142   private @Nullable Object buildMediaReference(@NotNull Resource resource,
143       @NotNull PropertyMetadata<?> metadata, @NotNull SlingHttpServletRequest request) {
144     MediaHandler mediaHandler = AdaptTo.notNull(request, MediaHandler.class);
145 
146     // support reading media handler component properties from metadata
147     MediaArgs mediaArgs = new MediaArgs();
148     Map<String, String> properties = metadata.getProperties();
149     if (properties != null) {
150       try (MediaComponentPropertyResolver resolver = new MediaComponentPropertyResolver(convertToValueMap(properties))) {
151         mediaArgs.mediaFormatOptions(resolver.getMediaFormatOptions());
152         mediaArgs.autoCrop(resolver.isAutoCrop());
153         mediaArgs.imageSizes(resolver.getImageSizes());
154       }
155       catch (Exception ex) {
156         log.warn("Unable to close MediaComponentPropertyResolver.", ex);
157       }
158     }
159 
160     Media media = mediaHandler.get(resource.getPath(), mediaArgs).build();
161     return mediaDecoratorManager.decorate(media, request.getResource());
162   }
163 
164   /**
165    * Converts a map of string properties to a value map.
166    * Property values separates by "," are transformed into an string array.
167    * @param properties Properties
168    * @return Value map
169    */
170   private ValueMap convertToValueMap(Map<String, String> properties) {
171     return new ValueMapDecorator(properties.entrySet().stream()
172         .map(entry -> Map.<String, Object>entry(entry.getKey(), StringUtils.split(entry.getValue(), ",")))
173         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
174   }
175 
176 }