View Javadoc
1   /* 
2    * Licensed under the Apache License, Version 2.0 (the "License");
3    * you may not use this file except in compliance with the License.
4    * You may obtain a copy of the License at
5    *
6    * http://www.apache.org/licenses/LICENSE-2.0
7    *
8    * Unless required by applicable law or agreed to in writing, software
9    * distributed under the License is distributed on an "AS IS" BASIS,
10   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11   * See the License for the specific language governing permissions and
12   * limitations under the License.
13   *
14   */
15  
16  package org.esigate.extension;
17  
18  import java.util.Properties;
19  
20  import org.esigate.Driver;
21  import org.esigate.events.Event;
22  import org.esigate.events.EventDefinition;
23  import org.esigate.events.EventManager;
24  import org.esigate.events.IEventListener;
25  import org.esigate.events.impl.RenderEvent;
26  import org.esigate.renderers.ResourceFixupRenderer;
27  import org.esigate.util.Parameter;
28  import org.esigate.util.ParameterString;
29  
30  /**
31   * Rewrites URLs found inside html pages.
32   * 
33   * @author Francois-Xavier Bonnet
34   * 
35   */
36  public class ResourceFixup implements Extension, IEventListener {
37  
38      private static final Parameter<String> FIX_MODE = new ParameterString("fixMode", "relative");
39      private boolean absolute;
40  
41      @Override
42      public boolean event(EventDefinition id, Event event) {
43  
44          RenderEvent renderEvent = (RenderEvent) event;
45          // Fix resources
46          String baseUrl = renderEvent.getOriginalRequest().getBaseUrl().toString();
47          String visibleBaseUrl = renderEvent.getOriginalRequest().getVisibleBaseUrl();
48          ResourceFixupRenderer fixup =
49                  new ResourceFixupRenderer(baseUrl, renderEvent.getRemoteUrl(), renderEvent.getOriginalRequest()
50                          .getDriver().getUrlRewriter(), visibleBaseUrl, absolute);
51  
52          // Add fixup renderer as first renderer.
53          renderEvent.getRenderers().add(0, fixup);
54  
55          // Continue processing
56          return true;
57      }
58  
59      @Override
60      public void init(Driver driver, Properties properties) {
61          absolute = "absolute".equalsIgnoreCase(FIX_MODE.getValue(properties));
62          driver.getEventManager().register(EventManager.EVENT_RENDER_PRE, this);
63      }
64  
65  }