View Javadoc
1   /**
2    * This file Copyright (c) 2003-2016 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.beans.config;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.util.DeprecationUtil;
38  import info.magnolia.cms.util.ModuleConfigurationObservingManager;
39  import info.magnolia.event.EventBus;
40  import info.magnolia.event.SystemEventBus;
41  import info.magnolia.jcr.node2bean.Node2BeanProcessor;
42  import info.magnolia.jcr.util.NodeUtil;
43  import info.magnolia.module.ModuleRegistry;
44  import info.magnolia.module.ModulesStartedEvent;
45  import info.magnolia.objectfactory.Components;
46  
47  import java.util.ArrayList;
48  import java.util.Collection;
49  import java.util.Collections;
50  import java.util.Iterator;
51  import java.util.List;
52  import java.util.concurrent.atomic.AtomicReference;
53  
54  import javax.inject.Inject;
55  import javax.inject.Named;
56  import javax.inject.Singleton;
57  import javax.jcr.Node;
58  import javax.jcr.RepositoryException;
59  
60  import org.apache.commons.lang3.StringUtils;
61  import org.slf4j.Logger;
62  import org.slf4j.LoggerFactory;
63  
64  /**
65   * Manages the configured virtual URI mappings and invokes them to perform the mapping operation. Monitors configuration
66   * of virtual URI mappings in JCR within each module under a node named <code>virtualURIMapping</code>.
67   *
68   * @see VirtualURIMapping
69   * @see info.magnolia.cms.filters.VirtualUriFilter
70   */
71  @Singleton
72  public final class VirtualURIManager extends ModuleConfigurationObservingManager {
73  
74      private static final Logger log = LoggerFactory.getLogger(VirtualURIManager.class);
75  
76      public static final String FROM_URI_NODEDATANAME = "fromURI";
77  
78      public static final String TO_URI_NODEDATANAME = "toURI";
79  
80      private final Node2BeanProcessor nodeToBean;
81  
82      /**
83       * Atomic reference to a list containing the virtual URI mappings in use. For thread safety the list must never be
84       * changed and is replaced entirely when something is changed in the JCR.
85       */
86      private final AtomicReference<List<VirtualURIMapping>> virtualUriMappings = new AtomicReference<List<VirtualURIMapping>>(new ArrayList<VirtualURIMapping>());
87  
88      @Inject
89      public VirtualURIManager(ModuleRegistry moduleRegistry, Node2BeanProcessor nodeToBean, @Named(SystemEventBus.NAME) EventBus systemEventBus) {
90          super("virtualURIMapping", moduleRegistry);
91          this.nodeToBean = nodeToBean;
92          systemEventBus.addHandler(ModulesStartedEvent.class, new ModulesStartedEvent.Handler() {
93              @Override
94              public void onModuleStartupCompleted(ModulesStartedEvent event) {
95                  VirtualURIManager.this.start();
96              }
97          });
98      }
99  
100     /**
101      * @deprecated since 5.4.5 use {@link #VirtualURIManager(ModuleRegistry, Node2BeanProcessor, info.magnolia.event.EventBus)}
102      */
103     public VirtualURIManager(Node2BeanProcessor nodeToBean) {
104         this(Components.getComponent(ModuleRegistry.class), nodeToBean, Components.getComponentWithAnnotation(EventBus.class, Components.named(SystemEventBus.NAME)));
105     }
106 
107     /**
108      * Checks for the requested URI mapping in Server config : Servlet Specification 2.3 Section 10 "Mapping Requests to
109      * Servlets".
110      *
111      * @param uri the URI of the current request, decoded and without the context path
112      * @return URI string mapping
113      */
114     public String getURIMapping(String uri) {
115         return getURIMapping(uri, null);
116     }
117 
118     /**
119      * Checks for the requested URI mapping in Server config : Servlet Specification 2.3 Section 10 "Mapping Requests to
120      * Servlets".
121      *
122      * @param uri the URI of the current request, decoded and without the context path
123      * @param queryString the Query String of the current request
124      * @return URI string mapping
125      */
126     public String getURIMapping(String uri, String queryString) {
127         Iterator<VirtualURIMapping> e = virtualUriMappings.get().iterator();
128         String mappedURI = StringUtils.EMPTY;
129         int lastMatchedLevel = 0;
130         while (e.hasNext()) {
131             try {
132                 VirtualURIMapping vm = e.next();
133                 final VirtualURIMapping.MappingResult result;
134                 if (queryString != null && vm instanceof QueryAwareVirtualURIMapping) {
135                     result = ((QueryAwareVirtualURIMapping) vm).mapURI(uri, queryString);
136                 } else {
137                     result = vm.mapURI(uri);
138                 }
139                 if (result != null && lastMatchedLevel < result.getLevel()) {
140                     lastMatchedLevel = result.getLevel();
141                     mappedURI = result.getToURI();
142                 }
143             } catch (ClassCastException ex) {
144                 log.error("Virtual URI configuration error, mapping rule is skipped: {}", ex.getMessage(), ex);
145             }
146         }
147         return mappedURI;
148     }
149 
150     @Override
151     protected void reload(List<Node> nodes) throws RepositoryException {
152         try {
153 
154             final List<VirtualURIMapping> foundMappings = new ArrayList<VirtualURIMapping>();
155 
156             for (Node node : nodes) {
157                 for (Node child : NodeUtil.getNodes(node)) {
158                     VirtualURIMapping virtualURIMapping = readVirtualURIMapping(child);
159                     if (virtualURIMapping != null) {
160                         foundMappings.add(virtualURIMapping);
161                     }
162                 }
163             }
164 
165             this.virtualUriMappings.set(foundMappings);
166 
167         } catch (Exception e) {
168             log.error("Failed to load VirtualURIMappings {}", e.getMessage(), e);
169         }
170     }
171 
172     protected VirtualURIMapping readVirtualURIMapping(Node node) {
173         try {
174             log.info("Loading VirtualURIMapping from {}", node.getPath());
175             VirtualURIMapping virtualURIMapping = (VirtualURIMapping) nodeToBean.toBean(node, DefaultVirtualURIMapping.class);
176             log.debug("VirtualURIMapping loaded from {}", node.getPath());
177             return virtualURIMapping;
178         } catch (Exception e) {
179             log.error("Unable to read VirtualURIMapping from node [{}]", NodeUtil.getNodePathIfPossible(node), e);
180             return null;
181         }
182     }
183 
184     public Collection<VirtualURIMapping> getURIMappings() {
185         return Collections.unmodifiableList(virtualUriMappings.get());
186     }
187 
188     /**
189      * @return Returns the instance.
190      * @deprecated since 4.5, use IoC !
191      */
192     @Deprecated
193     public static VirtualURIManager getInstance() {
194         return Components.getSingleton(VirtualURIManager.class);
195     }
196 
197     /**
198      * @deprecated since 5.4.5. Use {@link #reload(java.util.List)} instead.
199      */
200     @Deprecated
201     protected void onRegister(Content content) {
202         DeprecationUtil.isDeprecated("Use reload(java.util.List) instead");
203         try {
204             List<Node> observedNodes = getObservedNodes();
205             observedNodes.add(content.getJCRNode());
206             reload(observedNodes);
207         } catch (RepositoryException e) {
208             log.error("Failed to load VirtualURIMappings {}", e.getMessage(), e);
209         }
210     }
211 }