View Javadoc
1   /**
2    * This file Copyright (c) 2010-2015 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.module.blossom.render;
35  
36  import java.io.IOException;
37  import java.util.Locale;
38  
39  import javax.servlet.ServletException;
40  import javax.servlet.http.HttpServletRequest;
41  import javax.servlet.http.HttpServletResponse;
42  
43  import org.springframework.beans.BeansException;
44  import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
45  import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
46  import org.springframework.beans.factory.support.BeanDefinitionRegistry;
47  import org.springframework.context.ApplicationContext;
48  import org.springframework.util.Assert;
49  import org.springframework.web.context.ConfigurableWebApplicationContext;
50  import org.springframework.web.context.WebApplicationContext;
51  import org.springframework.web.servlet.DispatcherServlet;
52  import org.springframework.web.servlet.HandlerAdapter;
53  import org.springframework.web.servlet.HandlerExecutionChain;
54  import org.springframework.web.servlet.HandlerInterceptor;
55  import org.springframework.web.servlet.LocaleResolver;
56  import org.springframework.web.servlet.ModelAndView;
57  import org.springframework.web.servlet.View;
58  
59  import info.magnolia.context.MgnlContext;
60  import info.magnolia.module.blossom.context.MagnoliaLocaleResolver;
61  import info.magnolia.module.blossom.dialog.DialogExporter;
62  import info.magnolia.module.blossom.dispatcher.BlossomDispatcher;
63  import info.magnolia.module.blossom.dispatcher.BlossomDispatcherAwareBeanPostProcessor;
64  import info.magnolia.module.blossom.dispatcher.BlossomDispatcherInitializedEvent;
65  import info.magnolia.module.blossom.support.BeanFactoryUtils;
66  import info.magnolia.module.blossom.support.ForwardRequestWrapper;
67  import info.magnolia.module.blossom.support.IncludeRequestWrapper;
68  import info.magnolia.module.blossom.template.TemplateExporter;
69  import info.magnolia.module.blossom.urimapping.AnnotatedVirtualURIMappingExporter;
70  import info.magnolia.module.blossom.urimapping.VirtualURIMappingExporter;
71  
72  /**
73   * Specialization of DispatcherServlet that detects templates, paragraphs and dialogs factories and expose functionality
74   * for rendering and pre-execution.
75   *
76   * @since 0.5
77   */
78  public class BlossomDispatcherServlet extends DispatcherServlet implements BlossomDispatcher, BeanFactoryPostProcessor {
79  
80      public BlossomDispatcherServlet() {
81          super();
82      }
83  
84      public BlossomDispatcherServlet(WebApplicationContext webApplicationContext) {
85          super(webApplicationContext);
86      }
87  
88      @Override
89      protected Object getDefaultStrategy(ApplicationContext context, Class strategyInterface) throws BeansException {
90          if (strategyInterface.equals(LocaleResolver.class)) {
91              return super.createDefaultStrategy(context, MagnoliaLocaleResolver.class);
92          }
93          return super.getDefaultStrategy(context, strategyInterface);
94      }
95  
96      @Override
97      protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext wac) {
98          wac.addBeanFactoryPostProcessor(this);
99      }
100 
101     @Override
102     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
103 
104         Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory);
105 
106         BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
107 
108         beanFactory.addBeanPostProcessor(new BlossomDispatcherAwareBeanPostProcessor(this));
109 
110         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, TemplateExporter.class);
111         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, DialogExporter.class);
112         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, AnnotatedVirtualURIMappingExporter.class);
113         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, VirtualURIMappingExporter.class);
114     }
115 
116     @Override
117     protected WebApplicationContext initWebApplicationContext() throws BeansException {
118         WebApplicationContext wac = super.initWebApplicationContext();
119         wac.publishEvent(new BlossomDispatcherInitializedEvent(this));
120         return wac;
121     }
122 
123     @Override
124     public void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
125 
126         String contextPath = request.getContextPath();
127 
128         ForwardRequestWrapper forwardRequestWrapper = new ForwardRequestWrapper(request, contextPath + path, contextPath, path, null);
129 
130         MgnlContext.push(forwardRequestWrapper, response);
131         try {
132             super.service(forwardRequestWrapper, response);
133         } finally {
134             forwardRequestWrapper.restore();
135             MgnlContext.pop();
136         }
137     }
138 
139     @Override
140     public void include(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
141 
142         String contextPath = request.getContextPath();
143 
144         IncludeRequestWrapper includeRequestWrapper = new IncludeRequestWrapper(request, contextPath + path, contextPath, path, null, request.getQueryString());
145 
146         MgnlContext.push(includeRequestWrapper, response);
147         try {
148             super.service(includeRequestWrapper, response);
149         } finally {
150             includeRequestWrapper.restore();
151             MgnlContext.pop();
152         }
153     }
154 
155     @Override
156     public ModelAndView executeChain(HandlerExecutionChain mappedHandler, HttpServletRequest request, HttpServletResponse response) throws Exception {
157 
158         // This methods mimics the functionality in org.springframework.web.servlet.DispatcherServlet#doDispatch
159 
160         // Apply preHandle methods of registered interceptors.
161         HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
162         if (interceptors != null) {
163             for (int i = 0; i < interceptors.length; i++) {
164                 HandlerInterceptor interceptor = interceptors[i];
165                 if (!interceptor.preHandle(request, response, mappedHandler.getHandler())) {
166                     return null;
167                 }
168             }
169         }
170 
171         // Actually invoke the handler.
172         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
173         ModelAndView mv = ha.handle(request, response, mappedHandler.getHandler());
174 
175         // Do we need view name translation?
176         if (mv != null && !mv.hasView()) {
177             mv.setViewName(getDefaultViewName(request));
178         }
179 
180         // Apply postHandle methods of registered interceptors.
181         if (interceptors != null) {
182             for (int i = interceptors.length - 1; i >= 0; i--) {
183                 HandlerInterceptor interceptor = interceptors[i];
184                 interceptor.postHandle(request, response, mappedHandler.getHandler(), mv);
185             }
186         }
187 
188         if (mv != null && !mv.wasCleared()) {
189 
190             // Resolving the view mimics org.springframework.web.servlet.DispatcherServlet#render
191 
192             LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(LOCALE_RESOLVER_ATTRIBUTE);
193 
194             // Determine locale for request and apply it to the response.
195             Locale locale = localeResolver.resolveLocale(request);
196             response.setLocale(locale);
197 
198             View view;
199             if (mv.isReference()) {
200                 // We need to resolve the view name.
201                 view = resolveViewName(mv.getViewName(), mv.getModel(), locale, request);
202                 if (view == null) {
203                     throw new ServletException(
204                             "Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" +
205                                     getServletName() + "'");
206                 }
207             }
208             else {
209                 // No need to lookup: the ModelAndView object contains the actual View object.
210                 view = mv.getView();
211                 if (view == null) {
212                     throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
213                             "View object in servlet with name '" + getServletName() + "'");
214                 }
215             }
216 
217             mv.setView(view);
218         }
219 
220         return mv;
221     }
222 }