KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > ComplexWebApplicationContext


1 /*
2  * Copyright 2002-2005 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.web.servlet;
18
19 import java.io.IOException JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.List JavaDoc;
22 import java.util.Locale JavaDoc;
23
24 import javax.servlet.Servlet JavaDoc;
25 import javax.servlet.ServletConfig JavaDoc;
26 import javax.servlet.ServletException JavaDoc;
27 import javax.servlet.ServletRequest JavaDoc;
28 import javax.servlet.ServletResponse JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31
32 import org.springframework.beans.BeansException;
33 import org.springframework.beans.MutablePropertyValues;
34 import org.springframework.beans.factory.config.RuntimeBeanReference;
35 import org.springframework.beans.factory.support.ManagedList;
36 import org.springframework.context.ApplicationEvent;
37 import org.springframework.context.ApplicationListener;
38 import org.springframework.context.i18n.LocaleContextHolder;
39 import org.springframework.context.support.ApplicationObjectSupport;
40 import org.springframework.core.Ordered;
41 import org.springframework.web.bind.ServletRequestBindingException;
42 import org.springframework.web.context.WebApplicationContext;
43 import org.springframework.web.context.support.RequestHandledEvent;
44 import org.springframework.web.context.support.StaticWebApplicationContext;
45 import org.springframework.web.multipart.MaxUploadSizeExceededException;
46 import org.springframework.web.multipart.MultipartException;
47 import org.springframework.web.multipart.MultipartHttpServletRequest;
48 import org.springframework.web.multipart.MultipartResolver;
49 import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
50 import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
51 import org.springframework.web.servlet.handler.SimpleServletHandlerAdapter;
52 import org.springframework.web.servlet.handler.SimpleServletPostProcessor;
53 import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
54 import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;
55 import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
56 import org.springframework.web.servlet.i18n.SessionLocaleResolver;
57 import org.springframework.web.servlet.mvc.Controller;
58 import org.springframework.web.servlet.mvc.ParameterizableViewController;
59 import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
60 import org.springframework.web.servlet.mvc.SimpleFormController;
61 import org.springframework.web.servlet.support.RequestContextUtils;
62 import org.springframework.web.servlet.theme.SessionThemeResolver;
63 import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
64 import org.springframework.web.servlet.view.InternalResourceViewResolver;
65 import org.springframework.web.servlet.view.ResourceBundleViewResolver;
66
67 /**
68  * @author Juergen Hoeller
69  * @since 21.05.2003
70  */

71 public class ComplexWebApplicationContext extends StaticWebApplicationContext {
72
73     public void refresh() throws BeansException {
74         registerSingleton(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, SessionLocaleResolver.class);
75         registerSingleton(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, SessionThemeResolver.class);
76
77         MutablePropertyValues pvs = new MutablePropertyValues();
78         pvs.addPropertyValue(
79                 "mappings", "/view.do=viewHandler\n/locale.do=localeHandler\nloc.do=anotherLocaleHandler");
80         registerSingleton("myUrlMapping1", SimpleUrlHandlerMapping.class, pvs);
81
82         pvs = new MutablePropertyValues();
83         pvs.addPropertyValue(
84                 "mappings", "/form.do=localeHandler\n/unknown.do=unknownHandler\nservlet.do=myServlet");
85         pvs.addPropertyValue("order", "2");
86         registerSingleton("myUrlMapping2", SimpleUrlHandlerMapping.class, pvs);
87
88         pvs = new MutablePropertyValues();
89         pvs.addPropertyValue(
90                 "mappings", "/form.do=formHandler\n/head.do=headController\nbody.do=bodyController");
91         pvs.addPropertyValue("order", "1");
92         registerSingleton("handlerMapping", SimpleUrlHandlerMapping.class, pvs);
93
94         registerSingleton("myDummyAdapter", MyDummyAdapter.class);
95         registerSingleton("myHandlerAdapter", MyHandlerAdapter.class);
96         registerSingleton("standardHandlerAdapter", SimpleControllerHandlerAdapter.class);
97
98         pvs = new MutablePropertyValues();
99         pvs.addPropertyValue("order", new Integer JavaDoc(0));
100         pvs.addPropertyValue("basename", "org.springframework.web.servlet.complexviews");
101         registerSingleton("viewResolver", ResourceBundleViewResolver.class, pvs);
102
103         pvs = new MutablePropertyValues();
104         pvs.addPropertyValue("suffix", ".jsp");
105         registerSingleton("viewResolver2", InternalResourceViewResolver.class, pvs);
106
107         pvs = new MutablePropertyValues();
108         pvs.addPropertyValue("commandClass", "org.springframework.beans.TestBean");
109         pvs.addPropertyValue("formView", "form");
110         registerSingleton("formHandler", SimpleFormController.class, pvs);
111
112         pvs = new MutablePropertyValues();
113         pvs.addPropertyValue("viewName", "form");
114         registerSingleton("viewHandler", ParameterizableViewController.class, pvs);
115
116         registerSingleton("localeHandler", ComplexLocaleChecker.class);
117         registerSingleton("anotherLocaleHandler", ComplexLocaleChecker.class);
118         registerSingleton("unknownHandler", Object JavaDoc.class);
119
120         registerSingleton("headController", HeadController.class);
121         registerSingleton("bodyController", BodyController.class);
122
123         registerSingleton("servletPostProcessor", SimpleServletPostProcessor.class);
124         registerSingleton("servletHandlerAdapter", SimpleServletHandlerAdapter.class);
125         registerSingleton("myServlet", MyServlet.class);
126
127         pvs = new MutablePropertyValues();
128         pvs.addPropertyValue("order", "1");
129         pvs.addPropertyValue("exceptionMappings",
130             "java.lang.IllegalAccessException=failed2\n" +
131             "ServletRequestBindingException=failed3");
132         pvs.addPropertyValue("defaultErrorView", "failed0");
133         registerSingleton("exceptionResolver1", SimpleMappingExceptionResolver.class, pvs);
134
135         pvs = new MutablePropertyValues();
136         pvs.addPropertyValue("order", "0");
137         pvs.addPropertyValue("exceptionMappings", "java.lang.Exception=failed1");
138         List JavaDoc mappedHandlers = new ManagedList();
139         mappedHandlers.add(new RuntimeBeanReference("anotherLocaleHandler"));
140         pvs.addPropertyValue("mappedHandlers", mappedHandlers);
141         pvs.addPropertyValue("defaultStatusCode", "500");
142         pvs.addPropertyValue("defaultErrorView", "failed2");
143         registerSingleton("handlerExceptionResolver", SimpleMappingExceptionResolver.class, pvs);
144
145         registerSingleton("multipartResolver", MockMultipartResolver.class);
146         registerSingleton("testListener", TestApplicationListener.class);
147
148         addMessage("test", Locale.ENGLISH, "test message");
149         addMessage("test", Locale.CANADA, "Canadian & test message");
150
151         super.refresh();
152
153         SimpleUrlHandlerMapping myUrlMapping1 = (SimpleUrlHandlerMapping) getBean("myUrlMapping1");
154         LocaleChangeInterceptor interceptor1 = new LocaleChangeInterceptor();
155         LocaleChangeInterceptor interceptor2 = new LocaleChangeInterceptor();
156         interceptor2.setParamName("locale2");
157         ThemeChangeInterceptor interceptor3 = new ThemeChangeInterceptor();
158         ThemeChangeInterceptor interceptor4 = new ThemeChangeInterceptor();
159         interceptor4.setParamName("theme2");
160         UserRoleAuthorizationInterceptor interceptor5 = new UserRoleAuthorizationInterceptor();
161         interceptor5.setAuthorizedRoles(new String JavaDoc[] {"role1", "role2"});
162
163         List JavaDoc interceptors = new ArrayList JavaDoc();
164         interceptors.add(interceptor5);
165         interceptors.add(interceptor1);
166         interceptors.add(interceptor2);
167         interceptors.add(interceptor3);
168         interceptors.add(interceptor4);
169         interceptors.add(new MyHandlerInterceptor1());
170         interceptors.add(new MyHandlerInterceptor2());
171         myUrlMapping1.setInterceptors((HandlerInterceptor[]) interceptors.toArray(new HandlerInterceptor[interceptors.size()]));
172     }
173
174
175     public static class HeadController implements Controller {
176
177         public ModelAndView handleRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
178             if ("HEAD".equals(request.getMethod())) {
179                 response.setContentLength(5);
180             }
181             return null;
182         }
183     }
184
185
186     public static class BodyController implements Controller {
187
188         public ModelAndView handleRequest(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
189             response.getOutputStream().write("body".getBytes());
190             return null;
191         }
192     }
193
194
195     public static class MyServlet implements Servlet JavaDoc {
196
197         private ServletConfig JavaDoc servletConfig;
198
199         public void init(ServletConfig JavaDoc servletConfig) throws ServletException JavaDoc {
200             this.servletConfig = servletConfig;
201         }
202
203         public ServletConfig JavaDoc getServletConfig() {
204             return servletConfig;
205         }
206
207         public void service(ServletRequest JavaDoc servletRequest, ServletResponse JavaDoc servletResponse) throws IOException JavaDoc {
208             servletResponse.getOutputStream().write("body".getBytes());
209         }
210
211         public String JavaDoc getServletInfo() {
212             return null;
213         }
214
215         public void destroy() {
216             this.servletConfig = null;
217         }
218     }
219
220
221     public static interface MyHandler {
222
223         public void doSomething(HttpServletRequest JavaDoc request) throws ServletException JavaDoc, IllegalAccessException JavaDoc;
224
225         public long lastModified();
226     }
227
228
229     public static class MyHandlerAdapter extends ApplicationObjectSupport implements HandlerAdapter, Ordered {
230
231         public int getOrder() {
232             return 99;
233         }
234
235         public boolean supports(Object JavaDoc handler) {
236             return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
237         }
238
239         public ModelAndView handle(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc delegate)
240             throws ServletException JavaDoc, IllegalAccessException JavaDoc {
241             ((MyHandler) delegate).doSomething(request);
242             return null;
243         }
244
245         public long getLastModified(HttpServletRequest JavaDoc request, Object JavaDoc delegate) {
246             return ((MyHandler) delegate).lastModified();
247         }
248     }
249
250
251     public static class MyDummyAdapter extends ApplicationObjectSupport implements HandlerAdapter {
252
253         public boolean supports(Object JavaDoc handler) {
254             return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
255         }
256
257         public ModelAndView handle(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc delegate)
258             throws IOException JavaDoc, ServletException JavaDoc {
259             throw new ServletException JavaDoc("dummy");
260         }
261
262         public long getLastModified(HttpServletRequest JavaDoc request, Object JavaDoc delegate) {
263             return -1;
264         }
265     }
266
267
268     public static class MyHandlerInterceptor1 implements HandlerInterceptor {
269
270         public boolean preHandle(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc handler)
271             throws ServletException JavaDoc {
272             if (request.getAttribute("test2") != null) {
273                 throw new ServletException JavaDoc("Wrong interceptor order");
274             }
275             request.setAttribute("test1", "test1");
276             request.setAttribute("test1x", "test1x");
277             request.setAttribute("test1y", "test1y");
278             return true;
279         }
280
281         public void postHandle(
282                 HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc handler, ModelAndView modelAndView)
283                 throws ServletException JavaDoc {
284             if (request.getAttribute("test2x") != null) {
285                 throw new ServletException JavaDoc("Wrong interceptor order");
286             }
287             if (!"test1x".equals(request.getAttribute("test1x"))) {
288                 throw new ServletException JavaDoc("Incorrect request attribute");
289             }
290             request.removeAttribute("test1x");
291         }
292
293         public void afterCompletion(
294                 HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc handler, Exception JavaDoc ex)
295                 throws ServletException JavaDoc {
296             if (request.getAttribute("test2y") != null) {
297                 throw new ServletException JavaDoc("Wrong interceptor order");
298             }
299             request.removeAttribute("test1y");
300         }
301     }
302
303
304     public static class MyHandlerInterceptor2 implements HandlerInterceptor {
305
306         public boolean preHandle(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc handler)
307             throws ServletException JavaDoc {
308             if (request.getAttribute("test1x") == null) {
309                 throw new ServletException JavaDoc("Wrong interceptor order");
310             }
311             if (request.getParameter("abort") != null) {
312                 return false;
313             }
314             request.setAttribute("test2", "test2");
315             request.setAttribute("test2x", "test2x");
316             request.setAttribute("test2y", "test2y");
317             return true;
318         }
319
320         public void postHandle(
321                 HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc handler, ModelAndView modelAndView)
322                 throws ServletException JavaDoc {
323             if (request.getParameter("noView") != null) {
324                 modelAndView.clear();
325             }
326             if (request.getAttribute("test1x") == null) {
327                 throw new ServletException JavaDoc("Wrong interceptor order");
328             }
329             if (!"test2x".equals(request.getAttribute("test2x"))) {
330                 throw new ServletException JavaDoc("Incorrect request attribute");
331             }
332             request.removeAttribute("test2x");
333         }
334
335         public void afterCompletion(
336                 HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response, Object JavaDoc handler, Exception JavaDoc ex)
337                 throws Exception JavaDoc {
338             if (request.getAttribute("test1y") == null) {
339                 throw new ServletException JavaDoc("Wrong interceptor order");
340             }
341             request.removeAttribute("test2y");
342         }
343     }
344
345
346     public static class ComplexLocaleChecker implements MyHandler {
347
348         public void doSomething(HttpServletRequest JavaDoc request) throws ServletException JavaDoc, IllegalAccessException JavaDoc {
349             WebApplicationContext wac = RequestContextUtils.getWebApplicationContext(request);
350             if (!(wac instanceof ComplexWebApplicationContext)) {
351                 throw new ServletException JavaDoc("Incorrect WebApplicationContext");
352             }
353             if (!(request instanceof MultipartHttpServletRequest)) {
354                 throw new ServletException JavaDoc("Not in a MultipartHttpServletRequest");
355             }
356             if (!(RequestContextUtils.getLocaleResolver(request) instanceof SessionLocaleResolver)) {
357                 throw new ServletException JavaDoc("Incorrect LocaleResolver");
358             }
359             if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
360                 throw new ServletException JavaDoc("Incorrect Locale");
361             }
362             if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
363                 throw new ServletException JavaDoc("Incorrect Locale");
364             }
365             if (!(RequestContextUtils.getThemeResolver(request) instanceof SessionThemeResolver)) {
366                 throw new ServletException JavaDoc("Incorrect ThemeResolver");
367             }
368             if (!"theme".equals(RequestContextUtils.getThemeResolver(request).resolveThemeName(request))) {
369                 throw new ServletException JavaDoc("Incorrect theme name");
370             }
371             if (request.getParameter("fail") != null) {
372                 throw new ModelAndViewDefiningException(new ModelAndView("failed1"));
373             }
374             if (request.getParameter("access") != null) {
375                 throw new IllegalAccessException JavaDoc("illegal access");
376             }
377             if (request.getParameter("servlet") != null) {
378                 throw new ServletRequestBindingException("servlet");
379             }
380             if (request.getParameter("exception") != null) {
381                 throw new RuntimeException JavaDoc("servlet");
382             }
383         }
384
385         public long lastModified() {
386             return 99;
387         }
388     }
389
390
391     public static class MockMultipartResolver implements MultipartResolver {
392
393         public boolean isMultipart(HttpServletRequest JavaDoc request) {
394             return true;
395         }
396
397         public MultipartHttpServletRequest resolveMultipart(HttpServletRequest JavaDoc request) throws MultipartException {
398             if (request.getAttribute("fail") != null) {
399                 throw new MaxUploadSizeExceededException(1000);
400             }
401             if (request instanceof MultipartHttpServletRequest) {
402                 throw new IllegalStateException JavaDoc("Already a multipart request");
403             }
404             if (request.getAttribute("resolved") != null) {
405                 throw new IllegalStateException JavaDoc("Already resolved");
406             }
407             request.setAttribute("resolved", Boolean.TRUE);
408             return new AbstractMultipartHttpServletRequest(request) {
409             };
410         }
411
412         public void cleanupMultipart(MultipartHttpServletRequest request) {
413             if (request.getAttribute("cleanedUp") != null) {
414                 throw new IllegalStateException JavaDoc("Already cleaned up");
415             }
416             request.setAttribute("cleanedUp", Boolean.TRUE);
417         }
418     }
419
420
421     public static class TestApplicationListener implements ApplicationListener {
422
423         public int counter = 0;
424
425         public void onApplicationEvent(ApplicationEvent event) {
426             if (event instanceof RequestHandledEvent) {
427                 this.counter++;
428             }
429         }
430     }
431
432 }
433
Popular Tags