AbsoluteParentContextPathStrategy.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2016 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.caconfig.extensions.contextpath.impl;

  21. import java.util.ArrayList;
  22. import java.util.Arrays;
  23. import java.util.Collections;
  24. import java.util.HashSet;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Set;
  28. import java.util.TreeSet;
  29. import java.util.regex.Matcher;
  30. import java.util.regex.Pattern;
  31. import java.util.regex.PatternSyntaxException;

  32. import org.apache.commons.lang3.StringUtils;
  33. import org.apache.sling.api.resource.Resource;
  34. import org.apache.sling.api.resource.ResourceResolver;
  35. import org.apache.sling.caconfig.resource.spi.ContextPathStrategy;
  36. import org.apache.sling.caconfig.resource.spi.ContextResource;
  37. import org.jetbrains.annotations.NotNull;
  38. import org.osgi.service.component.annotations.Activate;
  39. import org.osgi.service.component.annotations.Component;
  40. import org.osgi.service.component.annotations.Reference;
  41. import org.osgi.service.metatype.annotations.AttributeDefinition;
  42. import org.osgi.service.metatype.annotations.Designate;
  43. import org.osgi.service.metatype.annotations.ObjectClassDefinition;
  44. import org.slf4j.Logger;
  45. import org.slf4j.LoggerFactory;

  46. import com.day.cq.wcm.api.NameConstants;
  47. import com.day.cq.wcm.api.Page;
  48. import com.day.cq.wcm.api.PageManager;
  49. import com.day.cq.wcm.api.PageManagerFactory;

  50. import io.wcm.wcm.commons.util.Path;

  51. /**
  52.  * {@link ContextPathStrategy} that detects context paths by absolute parent levels of a context resource.
  53.  */
  54. @Component(service = ContextPathStrategy.class)
  55. @Designate(ocd = AbsoluteParentContextPathStrategy.Config.class, factory = true)
  56. public class AbsoluteParentContextPathStrategy implements ContextPathStrategy {

  57.   @ObjectClassDefinition(name = "wcm.io Context-Aware Configuration Context Path Strategy: Absolute Parents",
  58.       description = "Detects context paths by absolute parent levels of a context resource.")
  59.   @interface Config {

  60.     @AttributeDefinition(name = "Absolute Levels",
  61.         description = "List of absolute parent levels. Example: Absolute parent level 1 of '/foo/bar/test' is '/foo/bar'.",
  62.         required = true)
  63.     int[] levels();

  64.     @AttributeDefinition(name = "Unlimited levels",
  65.         description = "If set to true, the 'Absolute Levels' define only the minimum levels. "
  66.             + "Above the highest level number every additional level is accepted as well.")
  67.     boolean unlimited() default false;

  68.     @AttributeDefinition(name = "Context path whitelist",
  69.         description = "Expression to match context paths. Context paths matching this expression are allowed. Use groups to reference them in configPathPatterns.",
  70.         required = true)
  71.     String contextPathRegex() default "^/content(/.+)$";

  72.     @AttributeDefinition(name = "Context path blacklist",
  73.         description = "Expression to match context paths. Context paths matching this expression are not allowed.",
  74.         required = true)
  75.     String contextPathBlacklistRegex() default "^.*/tools(/config(/.+)?)?$";

  76.     @AttributeDefinition(name = "Template path blacklist",
  77.             description = "Context paths belonging to a page matching one of the given template paths are not allowed.",
  78.             required = true)
  79.     String[] templatePathsBlacklist();

  80.     @AttributeDefinition(name = "Config path patterns",
  81.         description = "Expression to derive the config path from the context path. Regex group references like $1 can be used.",
  82.         required = true)
  83.     String[] configPathPatterns() default "/conf$1";

  84.     @AttributeDefinition(name = "Service Ranking",
  85.         description = "Priority of context path strategy (higher = higher priority).")
  86.     int service_ranking() default 2000;

  87.     String webconsole_configurationFactory_nameHint() default "levels={levels}, path={contextPathRegex}";

  88.   }

  89.   private Set<Integer> levels;
  90.   private int unlimitedLevelStart;
  91.   private boolean unlimited;
  92.   private Pattern contextPathRegex;
  93.   private Pattern contextPathBlacklistRegex;
  94.   private String[] configPathPatterns;
  95.   private int serviceRanking;
  96.   private Set<String> templatePathsBlacklist;

  97.   private static final Logger log = LoggerFactory.getLogger(AbsoluteParentContextPathStrategy.class);

  98.   @Reference
  99.   private PageManagerFactory pageManagerFactory;

  100.   @Activate
  101.   void activate(Config config) {
  102.     levels = new TreeSet<>();
  103.     if (config.levels() != null) {
  104.       for (int level : config.levels()) {
  105.         levels.add(level);
  106.         if (level >= unlimitedLevelStart) {
  107.           unlimitedLevelStart = level + 1;
  108.         }
  109.       }
  110.     }
  111.     unlimited = config.unlimited();
  112.     try {
  113.       contextPathRegex = Pattern.compile(config.contextPathRegex());
  114.     }
  115.     catch (PatternSyntaxException ex) {
  116.       log.warn("Invalid context path regex: {}", config.contextPathRegex(), ex);
  117.     }
  118.     if (StringUtils.isNotEmpty(config.contextPathBlacklistRegex())) {
  119.       try {
  120.         contextPathBlacklistRegex = Pattern.compile(config.contextPathBlacklistRegex());
  121.       }
  122.       catch (PatternSyntaxException ex) {
  123.         log.warn("Invalid context path blacklist regex: {}", config.contextPathBlacklistRegex(), ex);
  124.       }
  125.     }
  126.     configPathPatterns = config.configPathPatterns();
  127.     serviceRanking = config.service_ranking();
  128.     // make sure this is never null (only DS 1.4 initializes them always to empty arrays)
  129.     templatePathsBlacklist = config.templatePathsBlacklist() != null ? new HashSet<>(Arrays.asList(config.templatePathsBlacklist())) : Collections.emptySet();
  130.   }

  131.   @Override
  132.   public @NotNull Iterator<ContextResource> findContextResources(@NotNull Resource resource) {
  133.     if (!isValidConfig()) {
  134.       return Collections.emptyIterator();
  135.     }

  136.     ResourceResolver resourceResolver = resource.getResourceResolver();
  137.     PageManager pageManager = pageManagerFactory.getPageManager(resource.getResourceResolver());
  138.     if (pageManager == null) {
  139.       throw new RuntimeException("No page manager.");
  140.     }
  141.     List<ContextResource> contextResources = new ArrayList<>();

  142.     int maxLevel = Path.getAbsoluteLevel(resource.getPath(), resourceResolver);
  143.     for (int level = 0; level <= maxLevel; level++) {
  144.       if (levels.contains(level) || (unlimited && level >= unlimitedLevelStart)) {
  145.         String contextPath = Path.getAbsoluteParent(resource.getPath(), level, resourceResolver);
  146.         if (StringUtils.isNotEmpty(contextPath)) {
  147.           Resource contextResource = resource.getResourceResolver().getResource(contextPath);
  148.           if (contextResource != null) {
  149.             // first check if resource is blacklisted
  150.             if (isResourceBelongingToBlacklistedTemplates(contextResource, pageManager)) {
  151.               log.trace("Resource '{}' is belonging to a page derived from a blacklisted template, skipping level {}", contextPath, level);
  152.               break;
  153.             }
  154.             for (String configPathPattern : configPathPatterns) {
  155.               String configRef = deriveConfigRef(contextPath, configPathPattern, resourceResolver);
  156.               if (configRef != null) {
  157.                 contextResources.add(new ContextResource(contextResource, configRef, serviceRanking));
  158.               }
  159.             }
  160.           }
  161.         }
  162.       }
  163.     }

  164.     Collections.reverse(contextResources);
  165.     return contextResources.iterator();
  166.   }

  167.   private boolean isValidConfig() {
  168.     return !levels.isEmpty()
  169.         && contextPathRegex != null
  170.         && configPathPatterns != null
  171.         && configPathPatterns.length > 0;
  172.   }

  173.   private String deriveConfigRef(String contextPath, String configPathPattern, ResourceResolver resourceResolver) {
  174.     Matcher matcher = contextPathRegex.matcher(Path.getOriginalPath(contextPath, resourceResolver));
  175.     Matcher blacklistMatcher = null;
  176.     if (contextPathBlacklistRegex != null) {
  177.       blacklistMatcher = contextPathBlacklistRegex.matcher(contextPath);
  178.     }
  179.     if (matcher.matches() && (blacklistMatcher == null || !blacklistMatcher.matches())) {
  180.       return matcher.replaceAll(configPathPattern);
  181.     }
  182.     else {
  183.       return null;
  184.     }
  185.   }

  186.   private boolean isResourceBelongingToBlacklistedTemplates(Resource resource, PageManager pageManager) {
  187.     if (templatePathsBlacklist.isEmpty()) {
  188.       return false;
  189.     }
  190.     Page page = pageManager.getContainingPage(resource);
  191.     // if no containing page could be determined, we don't blacklist
  192.     if (page == null) {
  193.       log.trace("Resource '{}' is not part of page, blacklisted templates are not considered.", resource.getPath());
  194.       return false;
  195.     }
  196.     String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
  197.     if (templatePath != null) {
  198.       if (templatePathsBlacklist.contains(templatePath)) {
  199.         return true;
  200.       }
  201.     }
  202.     else {
  203.       log.trace("Resource '{}' is part of page '{}' which doesn't contain any template property, blacklisted templates are not considered.",
  204.           resource.getPath(), page.getPath());
  205.       return false;
  206.     }
  207.     log.trace("Resource '{}' is part of page '{}' but is not based on any of the blacklisted templates.", resource.getPath(), page.getPath());
  208.     return false;
  209.   }

  210. }