UrlExternalizerTransformerConfig.java

  1. /*
  2.  * #%L
  3.  * wcm.io
  4.  * %%
  5.  * Copyright (C) 2014 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.handler.url.rewriter.impl;

  21. import java.util.HashMap;
  22. import java.util.Map;

  23. import org.apache.commons.lang3.StringUtils;
  24. import org.apache.sling.api.resource.ValueMap;
  25. import org.slf4j.Logger;
  26. import org.slf4j.LoggerFactory;

  27. /**
  28.  * Configuration for {@link UrlExternalizerTransformer}.
  29.  */
  30. class UrlExternalizerTransformerConfig {

  31.   static final String PN_REWRITE_ELEMENTS = "rewriteElements";

  32.   private static final String[] REWRITE_ELEMENTS_DEFAULT = {
  33.       "img:src", "link:href", "script:src"
  34.   };

  35.   private static final String ELEMENT_ATTRIBUTE_SEPARATOR = ":";

  36.   private final Map<String, String> elementAttributeNames;

  37.   private static final Logger log = LoggerFactory.getLogger(UrlExternalizerTransformerConfig.class.getName());

  38.   UrlExternalizerTransformerConfig(ValueMap config) {
  39.     this.elementAttributeNames = toElementAttributeNamesMap(config.get(PN_REWRITE_ELEMENTS, REWRITE_ELEMENTS_DEFAULT));
  40.   }

  41.   private static Map<String, String> toElementAttributeNamesMap(String[] elementAttributeNames) {
  42.     Map<String, String> map = new HashMap<>();
  43.     for (String item : elementAttributeNames) {
  44.       String elementName = StringUtils.trim(StringUtils.substringBefore(item, ELEMENT_ATTRIBUTE_SEPARATOR));
  45.       String attributeName = StringUtils.trim(StringUtils.substringAfter(item, ELEMENT_ATTRIBUTE_SEPARATOR));
  46.       if (StringUtils.isBlank(elementName) || StringUtils.isBlank(attributeName)) {
  47.         log.info("Invalid URL externalizier transformer configuration - skipping invalid element entry: {}", item);
  48.       }
  49.       else if (map.containsKey(elementName)) {
  50.         log.info("Invalid URL externalizier transformer configuration - skipping duplicate element name: {}", item);
  51.       }
  52.       else {
  53.         map.put(elementName, attributeName);
  54.       }
  55.     }
  56.     return map;
  57.   }

  58.   public Map<String, String> getElementAttributeNames() {
  59.     return this.elementAttributeNames;
  60.   }

  61. }