View Javadoc
1   /**
2    * This file Copyright (c) 2014-2018 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.web;
35  
36  import info.magnolia.module.blossom.view.UuidRedirectViewResolver;
37  import info.magnolia.repository.RepositoryConstants;
38  
39  import java.lang.reflect.InvocationTargetException;
40  import java.util.ArrayList;
41  import java.util.Iterator;
42  import java.util.List;
43  
44  import org.springframework.beans.factory.BeanInitializationException;
45  import org.springframework.core.MethodParameter;
46  import org.springframework.util.PatternMatchUtils;
47  import org.springframework.web.context.request.NativeWebRequest;
48  import org.springframework.web.method.support.HandlerMethodArgumentResolver;
49  import org.springframework.web.method.support.HandlerMethodArgumentResolverComposite;
50  import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
51  import org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite;
52  import org.springframework.web.method.support.ModelAndViewContainer;
53  import org.springframework.web.servlet.ModelAndView;
54  import org.springframework.web.servlet.mvc.method.annotation.ModelAndViewMethodReturnValueHandler;
55  import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
56  import org.springframework.web.servlet.mvc.method.annotation.ViewNameMethodReturnValueHandler;
57  
58  /**
59   * Custom RequestMappingHandlerAdapter with support for detecting views that will result in redirects and marking them
60   * for redirect scenario handling, this is necessary for flash attributes to function properly. Typical view names
61   * used in Blossom are automatically supported and a set of custom patterns can also be set.
62   * <p>
63   * For more information see <a href="http://jira.magnolia-cms.com/browse/BLOSSOM-181">BLOSSOM-181</a> and <a href="https://jira.spring.io/browse/SPR-12054">SPR-12054</a>.
64   * <p>
65   * Also rearranges argument resolvers to make sure that {@link BlossomHandlerMethodArgumentResolver} is first in order
66   * to prevent the default resolvers from treating {@link info.magnolia.context.Context} and
67   * {@link info.magnolia.cms.security.User} arguments.
68   * <p>
69   * For more information see <a href="https://jira.magnolia-cms.com/browse/BLOSSOM-226">BLOSSOM-226</a>.
70   *
71   * @see ModelAndViewContainer#setRedirectModelScenario(boolean)
72   * @since 3.0.4
73   */
74  public class BlossomRequestMappingHandlerAdapter extends RequestMappingHandlerAdapter {
75  
76      public String[] redirectPatterns = new String[]{RepositoryConstants.WEBSITE + ":*", "dms:*"};
77  
78      public String[] getRedirectPatterns() {
79          return redirectPatterns;
80      }
81  
82      /**
83       * Sets the view name patterns that will result in a redirect, in a pattern format supporting wildcards.
84       *
85       * @see PatternMatchUtils#simpleMatch(String, String)
86       */
87      public void setRedirectPatterns(String... redirectPatterns) {
88          this.redirectPatterns = redirectPatterns;
89      }
90  
91      @Override
92      public void afterPropertiesSet() {
93          super.afterPropertiesSet();
94  
95          List<HandlerMethodReturnValueHandler> handlers = new ArrayList<HandlerMethodReturnValueHandler>(getExistingReturnValueHandlers());
96  
97          for (int i = 0; i < handlers.size(); i++) {
98              HandlerMethodReturnValueHandler handler = handlers.get(i);
99              if (handler instanceof ViewNameMethodReturnValueHandler) {
100                 handlers.set(i, new ViewNameMethodReturnValueHandler() {
101 
102                     @Override
103                     protected boolean isRedirectViewName(String viewName) {
104                         return super.isRedirectViewName(viewName) || BlossomRequestMappingHandlerAdapter.this.isRedirectViewName(viewName);
105                     }
106                 });
107             }
108             if (handler instanceof ModelAndViewMethodReturnValueHandler) {
109                 handlers.set(i, new ModelAndViewMethodReturnValueHandler() {
110 
111                     @Override
112                     public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
113                         if (returnValue != null) {
114                             ModelAndView mav = (ModelAndView) returnValue;
115                             if (mav.isReference()) {
116                                 String viewName = mav.getViewName();
117                                 if (viewName != null && BlossomRequestMappingHandlerAdapter.this.isRedirectViewName(viewName)) {
118                                     mavContainer.setRedirectModelScenario(true);
119                                 }
120                             }
121                         }
122                         super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
123                     }
124                 });
125             }
126         }
127 
128         super.setReturnValueHandlers(handlers);
129 
130         List<HandlerMethodArgumentResolver> resolvers = new ArrayList<HandlerMethodArgumentResolver>(getExistingHandlerMethodArgumentResolvers());
131         sortArgumentResolvers(resolvers);
132         super.setArgumentResolvers(resolvers);
133     }
134 
135     protected void sortArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
136         // Arrange BlossomHandlerMethodArgumentResolver first to prevent default resolvers from resolving Context and User arguments
137         Iterator<HandlerMethodArgumentResolver> iterator = resolvers.iterator();
138         while (iterator.hasNext()) {
139             HandlerMethodArgumentResolver resolver = iterator.next();
140             if (resolver instanceof BlossomHandlerMethodArgumentResolver) {
141                 iterator.remove();
142                 resolvers.add(0, resolver);
143                 break;
144             }
145         }
146     }
147 
148     /**
149      * The method getReturnValueHandlers changed return type in Spring 4. Doing it this way we can remain compatible with both.
150      * <ul>
151      * <li>In Spring 3 it returned HandlerMethodReturnValueHandlerComposite
152      * <li>In Spring 4 it returns List&lt;HandlerMethodReturnValueHandler&gt;
153      * </ul>
154      */
155     private List<HandlerMethodReturnValueHandler> getExistingReturnValueHandlers() {
156 
157         Object returnValueHandlers;
158         try {
159             returnValueHandlers = getClass().getMethod("getReturnValueHandlers").invoke(this);
160         } catch (IllegalAccessException e) {
161             throw new BeanInitializationException("Could not get existing return value handlers", e);
162         } catch (InvocationTargetException e) {
163             throw new BeanInitializationException("Could not get existing return value handlers", e.getTargetException());
164         } catch (NoSuchMethodException e) {
165             throw new BeanInitializationException("Could not get existing return value handlers", e);
166         }
167 
168         if (returnValueHandlers instanceof List) {
169             return (List<HandlerMethodReturnValueHandler>) returnValueHandlers;
170         }
171 
172         if (returnValueHandlers instanceof HandlerMethodReturnValueHandlerComposite) {
173             return ((HandlerMethodReturnValueHandlerComposite) returnValueHandlers).getHandlers();
174         }
175 
176         throw new BeanInitializationException("Could not get existing return value handlers");
177     }
178 
179     /**
180      * The method getArgumentResolvers changed return type in Spring 4. Doing it this way we can remain compatible with both.
181      * <ul>
182      * <li>In Spring 3 it returned HandlerMethodArgumentResolverComposite
183      * <li>In Spring 4 it returns List&lt;HandlerMethodArgumentResolver&gt;
184      * </ul>
185      */
186     private List<HandlerMethodArgumentResolver> getExistingHandlerMethodArgumentResolvers() {
187 
188         Object argumentResolvers;
189         try {
190             argumentResolvers = getClass().getMethod("getArgumentResolvers").invoke(this);
191         } catch (IllegalAccessException e) {
192             throw new BeanInitializationException("Could not get existing argument resolvers", e);
193         } catch (InvocationTargetException e) {
194             throw new BeanInitializationException("Could not get existing argument resolvers", e.getTargetException());
195         } catch (NoSuchMethodException e) {
196             throw new BeanInitializationException("Could not get existing argument resolvers", e);
197         }
198 
199         if (argumentResolvers instanceof List) {
200             return (List<HandlerMethodArgumentResolver>) argumentResolvers;
201         }
202 
203         if (argumentResolvers instanceof HandlerMethodArgumentResolverComposite) {
204             return ((HandlerMethodArgumentResolverComposite) argumentResolvers).getResolvers();
205         }
206 
207         throw new BeanInitializationException("Could not get existing argument resolvers");
208     }
209 
210     protected boolean isRedirectViewName(String viewName) {
211         return viewName.equals(UuidRedirectViewResolver.REDIRECT_MAIN_CONTENT_PLACEHOLDER) ||
212                 viewName.equals(UuidRedirectViewResolver.REDIRECT_CURRENT_CONTENT_PLACEHOLDER) ||
213                 (redirectPatterns != null && PatternMatchUtils.simpleMatch(redirectPatterns, viewName));
214     }
215 }