View Javadoc

1   /**
2    * This file Copyright (c) 2010-2013 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      @Override
81      protected Object getDefaultStrategy(ApplicationContext context, Class strategyInterface) throws BeansException {
82          if (strategyInterface.equals(LocaleResolver.class)) {
83              return super.createDefaultStrategy(context, MagnoliaLocaleResolver.class);
84          }
85          return super.getDefaultStrategy(context, strategyInterface);
86      }
87  
88      @Override
89      protected void postProcessWebApplicationContext(ConfigurableWebApplicationContext wac) {
90          wac.addBeanFactoryPostProcessor(this);
91      }
92  
93      @Override
94      public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
95  
96          Assert.isInstanceOf(BeanDefinitionRegistry.class, beanFactory);
97  
98          BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
99  
100         beanFactory.addBeanPostProcessor(new BlossomDispatcherAwareBeanPostProcessor(this));
101 
102         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, TemplateExporter.class);
103         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, DialogExporter.class);
104         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, AnnotatedVirtualURIMappingExporter.class);
105         BeanFactoryUtils.registerBeanIfMissing(beanFactory, registry, VirtualURIMappingExporter.class);
106     }
107 
108     @Override
109     protected WebApplicationContext initWebApplicationContext() throws BeansException {
110         WebApplicationContext wac = super.initWebApplicationContext();
111         wac.publishEvent(new BlossomDispatcherInitializedEvent(this));
112         return wac;
113     }
114 
115     @Override
116     public void forward(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
117 
118         String contextPath = request.getContextPath();
119 
120         request = new ForwardRequestWrapper(request, contextPath + path, contextPath, path, null);
121 
122         MgnlContext.push(request, response);
123         try {
124             super.service(request, response);
125         } finally {
126             MgnlContext.pop();
127         }
128     }
129 
130     @Override
131     public void include(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
132 
133         String contextPath = request.getContextPath();
134 
135         request = new IncludeRequestWrapper(request, contextPath + path, contextPath, path, null, request.getQueryString());
136 
137         MgnlContext.push(request, response);
138         try {
139             super.service(request, response);
140         } finally {
141             MgnlContext.pop();
142         }
143     }
144 
145     @Override
146     public ModelAndView executeChain(HandlerExecutionChain mappedHandler, HttpServletRequest request, HttpServletResponse response) throws Exception {
147 
148         // This methods mimics the functionality in org.springframework.web.servlet.DispatcherServlet#doDispatch
149 
150         // Apply preHandle methods of registered interceptors.
151         HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
152         if (interceptors != null) {
153             for (int i = 0; i < interceptors.length; i++) {
154                 HandlerInterceptor interceptor = interceptors[i];
155                 if (!interceptor.preHandle(request, response, mappedHandler.getHandler())) {
156                     return null;
157                 }
158             }
159         }
160 
161         // Actually invoke the handler.
162         HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
163         ModelAndView mv = ha.handle(request, response, mappedHandler.getHandler());
164 
165         // Do we need view name translation?
166         if (mv != null && !mv.hasView()) {
167             mv.setViewName(getDefaultViewName(request));
168         }
169 
170         // Apply postHandle methods of registered interceptors.
171         if (interceptors != null) {
172             for (int i = interceptors.length - 1; i >= 0; i--) {
173                 HandlerInterceptor interceptor = interceptors[i];
174                 interceptor.postHandle(request, response, mappedHandler.getHandler(), mv);
175             }
176         }
177 
178         if (mv != null && !mv.wasCleared()) {
179 
180             // Resolving the view mimics org.springframework.web.servlet.DispatcherServlet#render
181 
182             LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(LOCALE_RESOLVER_ATTRIBUTE);
183 
184             // Determine locale for request and apply it to the response.
185             Locale locale = localeResolver.resolveLocale(request);
186             response.setLocale(locale);
187 
188             View view;
189             if (mv.isReference()) {
190                 // We need to resolve the view name.
191                 view = resolveViewName(mv.getViewName(), mv.getModel(), locale, request);
192                 if (view == null) {
193                     throw new ServletException(
194                             "Could not resolve view with name '" + mv.getViewName() + "' in servlet with name '" +
195                                     getServletName() + "'");
196                 }
197             }
198             else {
199                 // No need to lookup: the ModelAndView object contains the actual View object.
200                 view = mv.getView();
201                 if (view == null) {
202                     throw new ServletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
203                             "View object in servlet with name '" + getServletName() + "'");
204                 }
205             }
206 
207             mv.setView(view);
208         }
209 
210         return mv;
211     }
212 }