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.net.URLDecoder;
23  import java.nio.charset.StandardCharsets;
24  
25  import org.apache.commons.lang3.StringUtils;
26  import org.apache.commons.lang3.Strings;
27  import org.apache.sling.rewriter.ProcessingComponentConfiguration;
28  import org.apache.sling.rewriter.ProcessingContext;
29  import org.apache.sling.rewriter.Transformer;
30  import org.slf4j.Logger;
31  import org.slf4j.LoggerFactory;
32  import org.xml.sax.Attributes;
33  import org.xml.sax.ContentHandler;
34  import org.xml.sax.Locator;
35  import org.xml.sax.SAXException;
36  import org.xml.sax.helpers.AttributesImpl;
37  import org.xml.sax.helpers.DefaultHandler;
38  
39  import io.wcm.handler.url.UrlHandler;
40  
41  /**
42   * HTML transformer that rewrites URLs in certain HTML element attributes.
43   */
44  class UrlExternalizerTransformer implements Transformer {
45  
46    private UrlExternalizerTransformerConfig transformerConfig;
47    private ContentHandler contentHandler = EMPTY_CONTENT_HANDLER;
48    private UrlHandler urlHandler;
49  
50    private static final Logger log = LoggerFactory.getLogger(UrlExternalizerTransformer.class.getName());
51    private static final ContentHandler EMPTY_CONTENT_HANDLER = new DefaultHandler();
52  
53    @Override
54    public void init(ProcessingContext pipelineContext, ProcessingComponentConfiguration config) {
55      log.trace("Initialize UrlExternalizerTransformer with config: {}", config.getConfiguration());
56      transformerConfig = new UrlExternalizerTransformerConfig(config.getConfiguration());
57      urlHandler = pipelineContext.getRequest().adaptTo(UrlHandler.class);
58    }
59  
60    @Override
61    public void setContentHandler(ContentHandler contentHandler) {
62      this.contentHandler = contentHandler;
63    }
64  
65    @Override
66    @SuppressWarnings("PMD.UseStringBufferForStringAppends")
67    public void startElement(String nsUri, String name, String raw, Attributes attrs) throws SAXException {
68  
69      // check if for this element an attribute for rewriting is configured
70      String rewriteAttr = transformerConfig.getElementAttributeNames().get(name);
71      if (rewriteAttr == null) {
72        log.trace("Rewrite element {}: Skip - No rewrite attribute configured.", name);
73        contentHandler.startElement(nsUri, name, raw, attrs);
74        return;
75      }
76  
77      // validate URL handler
78      if (urlHandler == null) {
79        log.warn("Rewrite element {}: Skip - Unable to get URL handler/Integrator handler instance.", name);
80        contentHandler.startElement(nsUri, name, raw, attrs);
81        return;
82      }
83  
84      // check if attribute exists
85      int attributeIndex = attrs.getIndex(rewriteAttr);
86      if (attributeIndex < 0) {
87        log.trace("Rewrite element {}: Skip - Attribute does not exist: {}", name, rewriteAttr);
88        contentHandler.startElement(nsUri, name, raw, attrs);
89        return;
90      }
91  
92      // rewrite URL
93      String url = attrs.getValue(attributeIndex);
94      if (StringUtils.isEmpty(url)) {
95        log.trace("Rewrite element {}: Skip - URL is empty.", name);
96        contentHandler.startElement(nsUri, name, raw, attrs);
97        return;
98      }
99  
100     // split off query string or fragment that may be appended to the URL
101     String urlRemainder = null;
102     int urlRemainderPos = StringUtils.indexOfAny(url, '?', '#');
103     if (urlRemainderPos >= 0) {
104       urlRemainder = url.substring(urlRemainderPos);
105       url = url.substring(0, urlRemainderPos);
106     }
107 
108     // decode URL (without URL remainder)
109     url = URLDecoder.decode(url, StandardCharsets.UTF_8);
110 
111     // externalize URL (if it is not already externalized)
112     String rewrittenUrl = urlHandler.get(url).buildExternalResourceUrl();
113     if (urlRemainder != null) {
114       if (rewrittenUrl == null) {
115         rewrittenUrl = urlRemainder;
116       }
117       else {
118         rewrittenUrl += urlRemainder;
119       }
120     }
121 
122     if (Strings.CS.equals(url, rewrittenUrl)) {
123       log.debug("Rewrite element {}: Skip - URL is already externalized: {}", name, url);
124       contentHandler.startElement(nsUri, name, raw, attrs);
125       return;
126     }
127 
128     // set new attribute value
129     log.debug("Rewrite element {}: Rewrite URL {} to {}", name, url, rewrittenUrl);
130     AttributesImpl newAttrs = new AttributesImpl(attrs);
131     newAttrs.setValue(attributeIndex, rewrittenUrl);
132     contentHandler.startElement(nsUri, name, raw, newAttrs);
133   }
134 
135   @Override
136   public void setDocumentLocator(Locator locator) {
137     this.contentHandler.setDocumentLocator(locator);
138   }
139 
140   @Override
141   public void startDocument() throws SAXException {
142     this.contentHandler.startDocument();
143   }
144 
145   @Override
146   public void endDocument() throws SAXException {
147     this.contentHandler.endDocument();
148   }
149 
150   @Override
151   public void startPrefixMapping(String prefix, String uri) throws SAXException {
152     this.contentHandler.startPrefixMapping(prefix, uri);
153   }
154 
155   @Override
156   public void endPrefixMapping(String prefix) throws SAXException {
157     this.contentHandler.endPrefixMapping(prefix);
158   }
159 
160   @Override
161   public void endElement(String uri, String localName, String qName) throws SAXException {
162     this.contentHandler.endElement(uri, localName, qName);
163   }
164 
165   @Override
166   public void characters(char[] ch, int start, int length) throws SAXException {
167     this.contentHandler.characters(ch, start, length);
168   }
169 
170   @Override
171   public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
172     this.contentHandler.ignorableWhitespace(ch, start, length);
173   }
174 
175   @Override
176   public void processingInstruction(String target, String data) throws SAXException {
177     this.contentHandler.processingInstruction(target, data);
178   }
179 
180   @Override
181   public void skippedEntity(String name) throws SAXException {
182     this.contentHandler.skippedEntity(name);
183   }
184 
185   @Override
186   public void dispose() {
187     // nothing to do
188   }
189 
190 }