View Javadoc
1   /**
2    * This file Copyright (c) 2003-2017 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   * @deprecated since 5.5.6, VirtualURIManager has been replaced by a registry in the virtual-uri module (see MAGNOLIA-3349).
72   */
73  @Singleton
74  @Deprecated
75  public class VirtualURIManager extends ModuleConfigurationObservingManager {
76  
77      private static final Logger log = LoggerFactory.getLogger(VirtualURIManager.class);
78  
79      public static final String FROM_URI_NODEDATANAME = "fromURI";
80  
81      public static final String TO_URI_NODEDATANAME = "toURI";
82  
83      private final Node2BeanProcessor nodeToBean;
84  
85      /**
86       * Atomic reference to a list containing the virtual URI mappings in use. For thread safety the list must never be
87       * changed and is replaced entirely when something is changed in the JCR.
88       */
89      private final AtomicReference<List<VirtualURIMapping>> virtualUriMappings = new AtomicReference<List<VirtualURIMapping>>(new ArrayList<VirtualURIMapping>());
90  
91      @Inject
92      public VirtualURIManager(ModuleRegistry moduleRegistry, Node2BeanProcessor nodeToBean, @Named(SystemEventBus.NAME) EventBus systemEventBus) {
93          super("virtualURIMapping", moduleRegistry);
94          this.nodeToBean = nodeToBean;
95          if (systemEventBus != null) {
96              systemEventBus.addHandler(ModulesStartedEvent.class, new ModulesStartedEvent.Handler() {
97                  @Override
98                  public void onModuleStartupCompleted(ModulesStartedEvent event) {
99                      VirtualURIManager.this.start();
100                 }
101             });
102         }
103     }
104 
105     /**
106      * @deprecated since 5.4.5 use {@link #VirtualURIManager(ModuleRegistry, Node2BeanProcessor, info.magnolia.event.EventBus)}
107      */
108     @Deprecated
109     public VirtualURIManager(Node2BeanProcessor nodeToBean) {
110         this(Components.getComponent(ModuleRegistry.class), nodeToBean, Components.getComponentWithAnnotation(EventBus.class, Components.named(SystemEventBus.NAME)));
111     }
112 
113     /**
114      * Checks for the requested URI mapping in Server config : Servlet Specification 2.3 Section 10 "Mapping Requests to
115      * Servlets".
116      *
117      * @param uri the URI of the current request, decoded and without the context path
118      * @return URI string mapping
119      */
120     public String getURIMapping(String uri) {
121         return getURIMapping(uri, null);
122     }
123 
124     /**
125      * Checks for the requested URI mapping in Server config : Servlet Specification 2.3 Section 10 "Mapping Requests to
126      * Servlets".
127      *
128      * @param uri the URI of the current request, decoded and without the context path
129      * @param queryString the Query String of the current request
130      * @return URI string mapping
131      */
132     public String getURIMapping(String uri, String queryString) {
133         Iterator<VirtualURIMapping> e = virtualUriMappings.get().iterator();
134         String mappedURI = StringUtils.EMPTY;
135         int lastMatchedLevel = 0;
136         while (e.hasNext()) {
137             try {
138                 VirtualURIMapping vm = e.next();
139                 final VirtualURIMapping.MappingResult result;
140                 if (queryString != null && vm instanceof QueryAwareVirtualURIMapping) {
141                     result = ((QueryAwareVirtualURIMapping) vm).mapURI(uri, queryString);
142                 } else {
143                     result = vm.mapURI(uri);
144                 }
145                 if (result != null && lastMatchedLevel < result.getLevel()) {
146                     lastMatchedLevel = result.getLevel();
147                     mappedURI = result.getToURI();
148                 }
149             } catch (ClassCastException ex) {
150                 log.error("Virtual URI configuration error, mapping rule is skipped: {}", ex.getMessage(), ex);
151             }
152         }
153         return mappedURI;
154     }
155 
156     @Override
157     protected void reload(List<Node> nodes) throws RepositoryException {
158         try {
159 
160             final List<VirtualURIMapping> foundMappings = new ArrayList<VirtualURIMapping>();
161 
162             for (Node node : nodes) {
163                 for (Node child : NodeUtil.getNodes(node)) {
164                     VirtualURIMapping virtualURIMapping = readVirtualURIMapping(child);
165                     if (virtualURIMapping != null) {
166                         foundMappings.add(virtualURIMapping);
167                     }
168                 }
169             }
170 
171             this.virtualUriMappings.set(foundMappings);
172 
173         } catch (Exception e) {
174             log.error("Failed to load VirtualURIMappings {}", e.getMessage(), e);
175         }
176     }
177 
178     protected VirtualURIMapping readVirtualURIMapping(Node node) {
179         try {
180             log.info("Loading VirtualURIMapping from {}", node.getPath());
181             VirtualURIMapping virtualURIMapping = (VirtualURIMapping) nodeToBean.toBean(node, DefaultVirtualURIMapping.class);
182             log.debug("VirtualURIMapping loaded from {}", node.getPath());
183             return virtualURIMapping;
184         } catch (Exception e) {
185             log.error("Unable to read VirtualURIMapping from node [{}]", NodeUtil.getNodePathIfPossible(node), e);
186             return null;
187         }
188     }
189 
190     public Collection<VirtualURIMapping> getURIMappings() {
191         return Collections.unmodifiableList(virtualUriMappings.get());
192     }
193 
194     /**
195      * @return Returns the instance.
196      * @deprecated since 4.5, use IoC !
197      */
198     @Deprecated
199     public static VirtualURIManager getInstance() {
200         return Components.getSingleton(VirtualURIManager.class);
201     }
202 
203     /**
204      * @deprecated since 5.4.5. Use {@link #reload(java.util.List)} instead.
205      */
206     @Deprecated
207     protected void onRegister(Content content) {
208         DeprecationUtil.isDeprecated("Use reload(java.util.List) instead");
209         try {
210             List<Node> observedNodes = getObservedNodes();
211             observedNodes.add(content.getJCRNode());
212             reload(observedNodes);
213         } catch (RepositoryException e) {
214             log.error("Failed to load VirtualURIMappings {}", e.getMessage(), e);
215         }
216     }
217 }