View Javadoc
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  
22  import java.util.HashMap;
23  import java.util.Map;
24  
25  import org.apache.commons.lang3.StringUtils;
26  import org.apache.sling.api.resource.ValueMap;
27  import org.slf4j.Logger;
28  import org.slf4j.LoggerFactory;
29  
30  /**
31   * Configuration for {@link UrlExternalizerTransformer}.
32   */
33  class UrlExternalizerTransformerConfig {
34  
35    static final String PN_REWRITE_ELEMENTS = "rewriteElements";
36  
37    private static final String[] REWRITE_ELEMENTS_DEFAULT = {
38        "img:src", "link:href", "script:src"
39    };
40  
41    private static final String ELEMENT_ATTRIBUTE_SEPARATOR = ":";
42  
43    private final Map<String, String> elementAttributeNames;
44  
45    private static final Logger log = LoggerFactory.getLogger(UrlExternalizerTransformerConfig.class.getName());
46  
47    UrlExternalizerTransformerConfig(ValueMap config) {
48      this.elementAttributeNames = toElementAttributeNamesMap(config.get(PN_REWRITE_ELEMENTS, REWRITE_ELEMENTS_DEFAULT));
49    }
50  
51    private static Map<String, String> toElementAttributeNamesMap(String[] elementAttributeNames) {
52      Map<String, String> map = new HashMap<>();
53      for (String item : elementAttributeNames) {
54        String elementName = StringUtils.trim(StringUtils.substringBefore(item, ELEMENT_ATTRIBUTE_SEPARATOR));
55        String attributeName = StringUtils.trim(StringUtils.substringAfter(item, ELEMENT_ATTRIBUTE_SEPARATOR));
56        if (StringUtils.isBlank(elementName) || StringUtils.isBlank(attributeName)) {
57          log.info("Invalid URL externalizier transformer configuration - skipping invalid element entry: {}", item);
58        }
59        else if (map.containsKey(elementName)) {
60          log.info("Invalid URL externalizier transformer configuration - skipping duplicate element name: {}", item);
61        }
62        else {
63          map.put(elementName, attributeName);
64        }
65      }
66      return map;
67    }
68  
69    public Map<String, String> getElementAttributeNames() {
70      return this.elementAttributeNames;
71    }
72  
73  }