KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > portlet > DispatcherPortlet


1 /*
2  * Copyright 2002-2007 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.portlet;
18
19 import java.io.IOException JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Collections JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Properties JavaDoc;
26
27 import javax.portlet.ActionRequest;
28 import javax.portlet.ActionResponse;
29 import javax.portlet.PortletException;
30 import javax.portlet.PortletRequest;
31 import javax.portlet.PortletResponse;
32 import javax.portlet.PortletSession;
33 import javax.portlet.RenderRequest;
34 import javax.portlet.RenderResponse;
35 import javax.portlet.UnavailableException;
36
37 import org.apache.commons.logging.Log;
38 import org.apache.commons.logging.LogFactory;
39
40 import org.springframework.beans.BeansException;
41 import org.springframework.beans.factory.BeanFactoryUtils;
42 import org.springframework.beans.factory.BeanInitializationException;
43 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
44 import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
45 import org.springframework.context.i18n.LocaleContext;
46 import org.springframework.context.i18n.LocaleContextHolder;
47 import org.springframework.context.i18n.SimpleLocaleContext;
48 import org.springframework.core.OrderComparator;
49 import org.springframework.core.io.ClassPathResource;
50 import org.springframework.core.io.support.PropertiesLoaderUtils;
51 import org.springframework.util.ClassUtils;
52 import org.springframework.util.StringUtils;
53 import org.springframework.web.context.request.RequestAttributes;
54 import org.springframework.web.context.request.RequestContextHolder;
55 import org.springframework.web.multipart.MultipartException;
56 import org.springframework.web.portlet.context.PortletRequestAttributes;
57 import org.springframework.web.portlet.multipart.MultipartActionRequest;
58 import org.springframework.web.portlet.multipart.PortletMultipartResolver;
59 import org.springframework.web.servlet.View;
60 import org.springframework.web.servlet.ViewRendererServlet;
61 import org.springframework.web.servlet.ViewResolver;
62
63 /**
64  * Central dispatcher for use within the Portlet MVC framework, e.g. for web UI
65  * controllers. Dispatches to registered handlers for processing a portlet request.
66  *
67  * <p>This portlet is very flexible: It can be used with just about any workflow,
68  * with the installation of the appropriate adapter classes. It offers the
69  * following functionality that distinguishes it from other request-driven
70  * portlet MVC frameworks:
71  *
72  * <ul>
73  * <li>It is based around a JavaBeans configuration mechanism.
74  *
75  * <li>It can use any {@link HandlerMapping} implementation - pre-built or provided
76  * as part of an application - to control the routing of requests to handler objects.
77  * Default is {@link org.springframework.web.portlet.handler.PortletModeHandlerMapping}.
78  * HandlerMapping objects can be defined as beans in the portlet's application context,
79  * implementing the HandlerMapping interface, overriding the default HandlerMapping
80  * if present. HandlerMappings can be given any bean name (they are tested by type).
81  *
82  * <li>It can use any {@link HandlerAdapter}; this allows to use any handler interface.
83  * The default adapter is {@link org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter}
84  * for Spring's {@link org.springframework.web.portlet.mvc.Controller} interface.
85  * HandlerAdapter objects can be added as beans in the application context,
86  * overriding the default HandlerAdapter. Like HandlerMappings, HandlerAdapters
87  * can be given any bean name (they are tested by type).
88  *
89  * <li>The dispatcher's exception resolution strategy can be specified via a
90  * {@link HandlerExceptionResolver}, for example mapping certain exceptions to
91  * error pages. Default is none. Additional HandlerExceptionResolvers can be added
92  * through the application context. HandlerExceptionResolver can be given any
93  * bean name (they are tested by type).
94  *
95  * <li>Its view resolution strategy can be specified via a {@link ViewResolver}
96  * implementation, resolving symbolic view names into View objects. Default is
97  * {@link org.springframework.web.servlet.view.InternalResourceViewResolver}.
98  * ViewResolver objects can be added as beans in the application context,
99  * overriding the default ViewResolver. ViewResolvers can be given any bean name
100  * (they are tested by type).
101  *
102  * <li>The dispatcher's strategy for resolving multipart requests is determined by a
103  * {@link org.springframework.web.portlet.multipart.PortletMultipartResolver} implementation.
104  * An implementations for Jakarta Commons FileUpload is included:
105  * {@link org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver}.
106  * The MultipartResolver bean name is "portletMultipartResolver"; default is none.
107  * </ul>
108  *
109  * <p><b>A web application can define any number of DispatcherPortlets.</b>
110  * Each portlet will operate in its own namespace, loading its own application
111  * context with mappings, handlers, etc. Only the root application context
112  * as loaded by {@link org.springframework.web.context.ContextLoaderListener},
113  * if any, will be shared.
114  *
115  * @author William G. Thompson, Jr.
116  * @author John A. Lewis
117  * @author Juergen Hoeller
118  * @author Nick Lothian
119  * @author Rainer Schmitz
120  * @since 2.0
121  * @see org.springframework.web.portlet.mvc.Controller
122  * @see org.springframework.web.servlet.ViewRendererServlet
123  * @see org.springframework.web.context.ContextLoaderListener
124  */

125 public class DispatcherPortlet extends FrameworkPortlet {
126
127     /**
128      * Well-known name for the PortletMultipartResolver object in the bean factory for this namespace.
129      */

130     public static final String JavaDoc MULTIPART_RESOLVER_BEAN_NAME = "portletMultipartResolver";
131
132     /**
133      * Well-known name for the HandlerMapping object in the bean factory for this namespace.
134      * Only used when "detectAllHandlerMappings" is turned off.
135      * @see #setDetectAllViewResolvers
136      */

137     public static final String JavaDoc HANDLER_MAPPING_BEAN_NAME = "handlerMapping";
138
139     /**
140      * Well-known name for the HandlerAdapter object in the bean factory for this namespace.
141      * Only used when "detectAllHandlerAdapters" is turned off.
142      * @see #setDetectAllHandlerAdapters
143      */

144     public static final String JavaDoc HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter";
145
146     /**
147      * Well-known name for the HandlerExceptionResolver object in the bean factory for this
148      * namespace. Only used when "detectAllHandlerExceptionResolvers" is turned off.
149      * @see #setDetectAllViewResolvers
150      */

151     public static final String JavaDoc HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver";
152
153     /**
154      * Well-known name for the ViewResolver object in the bean factory for this namespace.
155      */

156     public static final String JavaDoc VIEW_RESOLVER_BEAN_NAME = "viewResolver";
157
158     /**
159      * Default URL to ViewRendererServlet. This bridge servlet is used to convert
160      * portlet render requests to servlet requests in order to leverage the view support
161      * in the <code>org.springframework.web.view</code> package.
162      */

163     public static final String JavaDoc DEFAULT_VIEW_RENDERER_URL = "/WEB-INF/servlet/view";
164
165     /**
166      * Request attribute to hold the currently chosen HandlerExecutionChain.
167      * Only used for internal optimizations.
168      */

169     public static final String JavaDoc HANDLER_EXECUTION_CHAIN_ATTRIBUTE =
170             DispatcherPortlet.class.getName() + ".HANDLER";
171
172     /**
173      * Unlike the Servlet version of this class, we have to deal with the
174      * two-phase nature of the portlet request. To do this, we need to pass
175      * forward any exception that occurs during the action phase, so that
176      * it can be displayed in the render phase. The only direct way to pass
177      * things forward and preserve them for each render request is through
178      * render parameters, but these are limited to String objects and we need
179      * to pass the Exception itself. The only other way to do this is in the
180      * session. The bad thing about using the session is that we have no way
181      * of knowing when we are done re-rendering the request and so we don't
182      * know when we can remove the objects from the session. So we will end
183      * up polluting the session with an old exception when we finally leave
184      * the render phase of one request and move on to something else.
185      */

186     public static final String JavaDoc ACTION_EXCEPTION_SESSION_ATTRIBUTE =
187             DispatcherPortlet.class.getName() + ".ACTION_EXCEPTION";
188
189     /**
190      * This render parameter is used to indicate forward to the render phase
191      * that an exception occurred during the action phase.
192      */

193     public static final String JavaDoc ACTION_EXCEPTION_RENDER_PARAMETER = "actionException";
194
195     /**
196      * Log category to use when no mapped handler is found for a request.
197      */

198     public static final String JavaDoc PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.portlet.PageNotFound";
199
200     /**
201      * Name of the class path resource (relative to the DispatcherPortlet class)
202      * that defines DispatcherPortet's default strategy names.
203      */

204     private static final String JavaDoc DEFAULT_STRATEGIES_PATH = "DispatcherPortlet.properties";
205
206
207     /**
208      * Additional logger to use when no mapped handler is found for a request.
209      */

210     protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY);
211
212     private static final Properties JavaDoc defaultStrategies;
213
214     static {
215         // Load default strategy implementations from properties file.
216
// This is currently strictly internal and not meant to be customized
217
// by application developers.
218
try {
219             ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherPortlet.class);
220             defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
221         }
222         catch (IOException JavaDoc ex) {
223             throw new IllegalStateException JavaDoc("Could not load 'DispatcherPortlet.properties': " + ex.getMessage());
224         }
225     }
226
227
228     /** Detect all HandlerMappings or just expect "handlerMapping" bean? */
229     private boolean detectAllHandlerMappings = true;
230
231     /** Detect all HandlerAdapters or just expect "handlerAdapter" bean? */
232     private boolean detectAllHandlerAdapters = true;
233
234     /** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean? */
235     private boolean detectAllHandlerExceptionResolvers = true;
236
237     /** Detect all ViewResolvers or just expect "viewResolver" bean? */
238     private boolean detectAllViewResolvers = true;
239
240     /** URL that points to the ViewRendererServlet */
241     private String JavaDoc viewRendererUrl = DEFAULT_VIEW_RENDERER_URL;
242
243     /** Expose LocaleContext and RequestAttributes as inheritable for child threads? */
244     private boolean threadContextInheritable = false;
245
246
247     /** MultipartResolver used by this servlet */
248     private PortletMultipartResolver multipartResolver;
249
250     /** List of HandlerMappings used by this portlet */
251     private List JavaDoc handlerMappings;
252
253     /** List of HandlerAdapters used by this portlet */
254     private List JavaDoc handlerAdapters;
255
256     /** List of HandlerExceptionResolvers used by this portlet */
257     private List JavaDoc handlerExceptionResolvers;
258
259     /** List of ViewResolvers used by this portlet */
260     private List JavaDoc viewResolvers;
261
262
263     /**
264      * Set whether to detect all HandlerMapping beans in this portlet's context.
265      * Else, just a single bean with name "handlerMapping" will be expected.
266      * <p>Default is true. Turn this off if you want this portlet to use a
267      * single HandlerMapping, despite multiple HandlerMapping beans being
268      * defined in the context.
269      */

270     public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) {
271         this.detectAllHandlerMappings = detectAllHandlerMappings;
272     }
273
274     /**
275      * Set whether to detect all HandlerAdapter beans in this servlet's context.
276      * Else, just a single bean with name "handlerAdapter" will be expected.
277      * <p>Default is "true". Turn this off if you want this servlet to use a
278      * single HandlerAdapter, despite multiple HandlerAdapter beans being
279      * defined in the context.
280      */

281     public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) {
282         this.detectAllHandlerAdapters = detectAllHandlerAdapters;
283     }
284
285     /**
286      * Set whether to detect all HandlerExceptionResolver beans in this portlet's context.
287      * Else, just a single bean with name "handlerExceptionResolver" will be expected.
288      * <p>Default is true. Turn this off if you want this portlet to use a
289      * single HandlerExceptionResolver, despite multiple HandlerExceptionResolver
290      * beans being defined in the context.
291      */

292     public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) {
293         this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers;
294     }
295
296     /**
297      * Set whether to detect all ViewResolver beans in this portlet's context.
298      * Else, just a single bean with name "viewResolver" will be expected.
299      * <p>Default is true. Turn this off if you want this portlet to use a
300      * single ViewResolver, despite multiple ViewResolver beans being
301      * defined in the context.
302      */

303     public void setDetectAllViewResolvers(boolean detectAllViewResolvers) {
304         this.detectAllViewResolvers = detectAllViewResolvers;
305     }
306
307     /**
308      * Set the ViewRendererServlet. This servlet is used to ultimately render
309      * all views in the portlet application.
310      */

311     public void setViewRendererUrl(String JavaDoc viewRendererUrl) {
312         this.viewRendererUrl = viewRendererUrl;
313     }
314
315     /**
316      * Set whether to expose the LocaleContext and RequestAttributes as inheritable
317      * for child threads (using an {@link java.lang.InheritableThreadLocal}).
318      * <p>Default is "false", to avoid side effects on spawned background threads.
319      * Switch this to "true" to enable inheritance for custom child threads which
320      * are spawned during request processing and only used for this request
321      * (that is, ending after their initial task, without reuse of the thread).
322      * <p><b>WARNING:</b> Do not use inheritance for child threads if you are
323      * accessing a thread pool which is configured to potentially add new threads
324      * on demand (e.g. a JDK {@link java.util.concurrent.ThreadPoolExecutor}),
325      * since this will expose the inherited context to such a pooled thread.
326      */

327     public void setThreadContextInheritable(boolean threadContextInheritable) {
328         this.threadContextInheritable = threadContextInheritable;
329     }
330
331
332     /**
333      * Overridden method, invoked after any bean properties have been set and the
334      * PortletApplicationContext and BeanFactory for this namespace is available.
335      * <p>Loads HandlerMapping and HandlerAdapter objects, and configures a
336      * ViewResolver and a LocaleResolver.
337      */

338     protected void initFrameworkPortlet() throws PortletException, BeansException {
339         initMultipartResolver();
340         initHandlerMappings();
341         initHandlerAdapters();
342         initHandlerExceptionResolvers();
343         initViewResolvers();
344     }
345
346     /**
347      * Initialize the PortletMultipartResolver used by this class.
348      * <p>If no valid bean is defined with the given name in the BeanFactory
349      * for this namespace, no multipart handling is provided.
350      */

351     private void initMultipartResolver() {
352         try {
353             this.multipartResolver = (PortletMultipartResolver)
354                     getPortletApplicationContext().getBean(MULTIPART_RESOLVER_BEAN_NAME, PortletMultipartResolver.class);
355             if (logger.isInfoEnabled()) {
356                 logger.info("Using MultipartResolver [" + this.multipartResolver + "]");
357             }
358         }
359         catch (NoSuchBeanDefinitionException ex) {
360             // Default is no multipart resolver.
361
this.multipartResolver = null;
362             if (logger.isInfoEnabled()) {
363                 logger.info("Unable to locate PortletMultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME +
364                         "': no multipart request handling provided");
365             }
366         }
367     }
368
369     /**
370      * Initialize the HandlerMappings used by this class.
371      * <p>If no HandlerMapping beans are defined in the BeanFactory
372      * for this namespace, we default to PortletModeHandlerMapping.
373      */

374     private void initHandlerMappings() {
375         if (this.detectAllHandlerMappings) {
376             // Find all HandlerMappings in the ApplicationContext,
377
// including ancestor contexts.
378
Map JavaDoc matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
379                     getPortletApplicationContext(), HandlerMapping.class, true, false);
380             if (!matchingBeans.isEmpty()) {
381                 this.handlerMappings = new ArrayList JavaDoc(matchingBeans.values());
382                 // We keep HandlerMappings in sorted order.
383
Collections.sort(this.handlerMappings, new OrderComparator());
384             }
385         }
386         else {
387             try {
388                 Object JavaDoc hm = getPortletApplicationContext().getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
389                 this.handlerMappings = Collections.singletonList(hm);
390             }
391             catch (NoSuchBeanDefinitionException ex) {
392                 // Ignore, we'll add a default HandlerMapping later.
393
}
394         }
395
396         // Ensure we have at least one HandlerMapping, by registering
397
// a default HandlerMapping if no other mappings are found.
398
if (this.handlerMappings == null) {
399             this.handlerMappings = getDefaultStrategies(HandlerMapping.class);
400             if (logger.isInfoEnabled()) {
401                 logger.info("No HandlerMappings found in portlet '" + getPortletName() + "': using default");
402             }
403         }
404     }
405
406     /**
407      * Initialize the HandlerAdapters used by this class.
408      * <p>If no HandlerAdapter beans are defined in the BeanFactory
409      * for this namespace, we default to SimpleControllerHandlerAdapter.
410      */

411     private void initHandlerAdapters() {
412         if (this.detectAllHandlerAdapters) {
413             // Find all HandlerAdapters in the ApplicationContext,
414
// including ancestor contexts.
415
Map JavaDoc matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
416                     getPortletApplicationContext(), HandlerAdapter.class, true, false);
417             if (!matchingBeans.isEmpty()) {
418                 this.handlerAdapters = new ArrayList JavaDoc(matchingBeans.values());
419                 // We keep HandlerAdapters in sorted order.
420
Collections.sort(this.handlerAdapters, new OrderComparator());
421             }
422         }
423         else {
424             try {
425                 Object JavaDoc ha = getPortletApplicationContext().getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class);
426                 this.handlerAdapters = Collections.singletonList(ha);
427             }
428             catch (NoSuchBeanDefinitionException ex) {
429                 // Ignore, we'll add a default HandlerAdapter later.
430
}
431         }
432
433         // Ensure we have at least some HandlerAdapters, by registering
434
// default HandlerAdapters if no other adapters are found.
435
if (this.handlerAdapters == null) {
436             this.handlerAdapters = getDefaultStrategies(HandlerAdapter.class);
437             if (logger.isInfoEnabled()) {
438                 logger.info("No HandlerAdapters found in portlet '" + getPortletName() + "': using default");
439             }
440         }
441     }
442
443     /**
444      * Initialize the HandlerExceptionResolver used by this class.
445      * <p>If no bean is defined with the given name in the BeanFactory
446      * for this namespace, we default to no exception resolver.
447      */

448     private void initHandlerExceptionResolvers() {
449         if (this.detectAllHandlerExceptionResolvers) {
450             // Find all HandlerExceptionResolvers in the ApplicationContext,
451
// including ancestor contexts.
452
Map JavaDoc matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
453                     getPortletApplicationContext(), HandlerExceptionResolver.class, true, false);
454             this.handlerExceptionResolvers = new ArrayList JavaDoc(matchingBeans.values());
455             // We keep HandlerExceptionResolvers in sorted order.
456
Collections.sort(this.handlerExceptionResolvers, new OrderComparator());
457         }
458         else {
459             try {
460                 Object JavaDoc her = getPortletApplicationContext().getBean(
461                         HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class);
462                 this.handlerExceptionResolvers = Collections.singletonList(her);
463             }
464             catch (NoSuchBeanDefinitionException ex) {
465                 // Ignore, no HandlerExceptionResolver is fine too.
466
this.handlerExceptionResolvers = getDefaultStrategies(HandlerExceptionResolver.class);
467             }
468         }
469     }
470
471     /**
472      * Initialize the ViewResolvers used by this class.
473      * <p>If no ViewResolver beans are defined in the BeanFactory
474      * for this namespace, we default to InternalResourceViewResolver.
475      */

476     private void initViewResolvers() {
477         if (this.detectAllViewResolvers) {
478             // Find all ViewResolvers in the ApplicationContext,
479
// including ancestor contexts.
480
Map JavaDoc matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
481                     getPortletApplicationContext(), ViewResolver.class, true, false);
482             if (!matchingBeans.isEmpty()) {
483                 this.viewResolvers = new ArrayList JavaDoc(matchingBeans.values());
484                 // We keep ViewResolvers in sorted order.
485
Collections.sort(this.viewResolvers, new OrderComparator());
486             }
487         }
488         else {
489             try {
490                 Object JavaDoc vr = getPortletApplicationContext().getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class);
491                 this.viewResolvers = Collections.singletonList(vr);
492             }
493             catch (NoSuchBeanDefinitionException ex) {
494                 // Ignore, we'll add a default ViewResolver later.
495
}
496         }
497
498         // Ensure we have at least one ViewResolver, by registering
499
// a default ViewResolver if no other resolvers are found.
500
if (this.viewResolvers == null) {
501             this.viewResolvers = getDefaultStrategies(ViewResolver.class);
502             if (logger.isInfoEnabled()) {
503                 logger.info("No ViewResolvers found in portlet '" + getPortletName() + "': using default");
504             }
505         }
506     }
507
508
509     /**
510      * Return the default strategy object for the given strategy interface.
511      * <p>The default implementation delegates to {@link #getDefaultStrategies},
512      * expecting a single object in the list.
513      * @param strategyInterface the strategy interface
514      * @return the corresponding strategy object
515      * @throws BeansException if initialization failed
516      * @see #getDefaultStrategies
517      */

518     protected Object JavaDoc getDefaultStrategy(Class JavaDoc strategyInterface) throws BeansException {
519         List JavaDoc strategies = getDefaultStrategies(strategyInterface);
520         if (strategies.size() != 1) {
521             throw new BeanInitializationException(
522                     "DispatcherPortlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]");
523         }
524         return strategies.get(0);
525     }
526
527     /**
528      * Create a List of default strategy objects for the given strategy interface.
529      * <p>The default implementation uses the "DispatcherPortlet.properties" file
530      * (in the same package as the DispatcherPortlet class) to determine the class names.
531      * It instantiates the strategy objects and satisifies ApplicationContextAware
532      * if necessary.
533      * @param strategyInterface the strategy interface
534      * @return the List of corresponding strategy objects
535      * @throws BeansException if initialization failed
536      */

537     protected List JavaDoc getDefaultStrategies(Class JavaDoc strategyInterface) throws BeansException {
538         String JavaDoc key = strategyInterface.getName();
539         List JavaDoc strategies = null;
540         String JavaDoc value = defaultStrategies.getProperty(key);
541         if (value != null) {
542             String JavaDoc[] classNames = StringUtils.commaDelimitedListToStringArray(value);
543             strategies = new ArrayList JavaDoc(classNames.length);
544             for (int i = 0; i < classNames.length; i++) {
545                 String JavaDoc className = classNames[i];
546                 try {
547                     Class JavaDoc clazz = ClassUtils.forName(className, getClass().getClassLoader());
548                     Object JavaDoc strategy = createDefaultStrategy(clazz);
549                     strategies.add(strategy);
550                 }
551                 catch (ClassNotFoundException JavaDoc ex) {
552                     throw new BeanInitializationException(
553                             "Could not find DispatcherPortlet's default strategy class [" + className +
554                             "] for interface [" + key + "]", ex);
555                 }
556                 catch (LinkageError JavaDoc err) {
557                     throw new BeanInitializationException(
558                             "Error loading DispatcherPortlet's default strategy class [" + className +
559                             "] for interface [" + key + "]: problem with class file or dependent class", err);
560                 }
561             }
562         }
563         else {
564             strategies = Collections.EMPTY_LIST;
565         }
566         return strategies;
567     }
568
569     /**
570      * Create a default strategy.
571      * <p>The default implementation uses
572      * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}.
573      * @param clazz the strategy implementation class to instantiate
574      * @return the fully configured strategy instance
575      * @throws BeansException if initialization failed
576      * @see #getPortletApplicationContext()
577      * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory()
578      */

579     protected Object JavaDoc createDefaultStrategy(Class JavaDoc clazz) throws BeansException {
580         return getPortletApplicationContext().getAutowireCapableBeanFactory().createBean(
581                 clazz, AutowireCapableBeanFactory.AUTOWIRE_NO, false);
582     }
583
584
585     /**
586      * Processes the actual dispatching to the handler for action requests.
587      * <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
588      * The HandlerAdapter will be obtained by querying the portlet's installed
589      * HandlerAdapters to find the first that supports the handler class.
590      * @param request current portlet action request
591      * @param response current portlet Action response
592      * @throws Exception in case of any kind of processing failure
593      */

594     protected void doActionService(ActionRequest request, ActionResponse response) throws Exception JavaDoc {
595         if (logger.isDebugEnabled()) {
596             logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
597         }
598
599         // Expose current LocaleResolver and request as LocaleContext.
600
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
601         LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);
602
603         // Expose current RequestAttributes to current thread.
604
RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
605         PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
606         RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
607
608         if (logger.isDebugEnabled()) {
609             logger.debug("Bound action request context to thread: " + request);
610         }
611
612         ActionRequest processedRequest = request;
613         HandlerExecutionChain mappedHandler = null;
614         int interceptorIndex = -1;
615
616         try {
617             processedRequest = checkMultipart(request);
618
619             // Determine handler for the current request.
620
mappedHandler = getHandler(processedRequest, false);
621             if (mappedHandler == null || mappedHandler.getHandler() == null) {
622                 noHandlerFound(processedRequest, response);
623                 return;
624             }
625
626             // Apply preHandle methods of registered interceptors.
627
if (mappedHandler.getInterceptors() != null) {
628                 for (int i = 0; i < mappedHandler.getInterceptors().length; i++) {
629                     HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
630                     if (!interceptor.preHandleAction(processedRequest, response, mappedHandler.getHandler())) {
631                         triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
632                         return;
633                     }
634                     interceptorIndex = i;
635                 }
636             }
637
638             // Actually invoke the handler.
639
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
640             ha.handleAction(processedRequest, response, mappedHandler.getHandler());
641
642             // Trigger after-completion for successful outcome.
643
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
644         }
645
646         catch (Exception JavaDoc ex) {
647             // Trigger after-completion for thrown exception.
648
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
649             // Forward the exception to the render phase to be displayed.
650
logger.debug("Caught exception during action phase - forwarding to render phase", ex);
651             PortletSession session = request.getPortletSession();
652             session.setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
653             response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
654         }
655         catch (Error JavaDoc err) {
656             PortletException ex =
657                     new PortletException("Error occured during request processing: " + err.getMessage(), err);
658             // Trigger after-completion for thrown exception.
659
triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
660             throw ex;
661         }
662
663         finally {
664             // Clean up any resources used by a multipart request.
665
if (processedRequest instanceof MultipartActionRequest && processedRequest != request) {
666                 this.multipartResolver.cleanupMultipart((MultipartActionRequest) processedRequest);
667             }
668
669             // Reset thread-bound context.
670
RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);
671             LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);
672
673             // Clear request attributes.
674
requestAttributes.requestCompleted();
675             if (logger.isDebugEnabled()) {
676                 logger.debug("Cleared thread-bound action request context: " + request);
677             }
678         }
679     }
680
681     /**
682      * Processes the actual dispatching to the handler for render requests.
683      * <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
684      * The HandlerAdapter will be obtained by querying the portlet's installed
685      * HandlerAdapters to find the first that supports the handler class.
686      * @param request current portlet render request
687      * @param response current portlet render response
688      * @throws Exception in case of any kind of processing failure
689      */

690     protected void doRenderService(RenderRequest request, RenderResponse response) throws Exception JavaDoc {
691         if (logger.isDebugEnabled()) {
692             logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received render request");
693         }
694
695         // Expose current LocaleResolver and request as LocaleContext.
696
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
697         LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);
698
699         // Expose current RequestAttributes to current thread.
700
RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
701         PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
702         RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
703
704         if (logger.isDebugEnabled()) {
705             logger.debug("Bound render request context to thread: " + request);
706         }
707
708         RenderRequest processedRequest = request;
709         HandlerExecutionChain mappedHandler = null;
710         int interceptorIndex = -1;
711
712         try {
713             ModelAndView mv = null;
714             try {
715                 // Check for forwarded exception from the action phase
716
PortletSession session = request.getPortletSession(false);
717                 if (session != null) {
718                     if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
719                         Exception JavaDoc ex = (Exception JavaDoc) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
720                         if (ex != null) {
721                             logger.debug("Render phase found exception caught during action phase - rethrowing it");
722                             throw ex;
723                         }
724                     }
725                     else {
726                         session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
727                     }
728                 }
729                 
730                 // Determine handler for the current request.
731
mappedHandler = getHandler(processedRequest, false);
732                 if (mappedHandler == null || mappedHandler.getHandler() == null) {
733                     noHandlerFound(processedRequest, response);
734                     return;
735                 }
736
737                 // Apply preHandle methods of registered interceptors.
738
if (mappedHandler.getInterceptors() != null) {
739                     for (int i = 0; i < mappedHandler.getInterceptors().length; i++) {
740                         HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
741                         if (!interceptor.preHandleRender(processedRequest, response, mappedHandler.getHandler())) {
742                             triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
743                             return;
744                         }
745                         interceptorIndex = i;
746                     }
747                 }
748
749                 // Actually invoke the handler.
750
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
751                 mv = ha.handleRender(processedRequest, response, mappedHandler.getHandler());
752
753                 // Apply postHandle methods of registered interceptors.
754
if (mappedHandler.getInterceptors() != null) {
755                     for (int i = mappedHandler.getInterceptors().length - 1; i >= 0; i--) {
756                         HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
757                         interceptor.postHandleRender(processedRequest, response, mappedHandler.getHandler(), mv);
758                     }
759                 }
760             }
761             catch (ModelAndViewDefiningException ex) {
762                 logger.debug("ModelAndViewDefiningException encountered", ex);
763                 mv = ex.getModelAndView();
764             }
765             catch (Exception JavaDoc ex) {
766                 Object JavaDoc handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
767                 mv = processHandlerException(request, response, handler, ex);
768             }
769
770             // Did the handler return a view to render?
771
if (mv != null && !mv.isEmpty()) {
772                 render(mv, processedRequest, response);
773             }
774             else {
775                 if (logger.isDebugEnabled()) {
776                     logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
777                             getPortletName() + "': assuming HandlerAdapter completed request handling");
778                 }
779             }
780
781             // Trigger after-completion for successful outcome.
782
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, null);
783         }
784
785         catch (Exception JavaDoc ex) {
786             // Trigger after-completion for thrown exception.
787
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
788             throw ex;
789         }
790         catch (Error JavaDoc err) {
791             PortletException ex =
792                     new PortletException("Error occured during request processing: " + err.getMessage(), err);
793             // Trigger after-completion for thrown exception.
794
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex);
795             throw ex;
796         }
797
798         finally {
799             // Reset thread-bound context.
800
RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);
801             LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);
802
803             // Clear request attributes.
804
requestAttributes.requestCompleted();
805             if (logger.isDebugEnabled()) {
806                 logger.debug("Cleared thread-bound render request context: " + request);
807             }
808         }
809     }
810
811
812     /**
813      * Build a LocaleContext for the given request, exposing the request's
814      * primary locale as current locale.
815      * @param request current HTTP request
816      * @return the corresponding LocaleContext
817      */

818     protected LocaleContext buildLocaleContext(PortletRequest request) {
819         return new SimpleLocaleContext(request.getLocale());
820     }
821
822     /**
823      * Convert the request into a multipart request, and make multipart resolver available.
824      * If no multipart resolver is set, simply use the existing request.
825      * @param request current HTTP request
826      * @return the processed request (multipart wrapper if necessary)
827      */

828     protected ActionRequest checkMultipart(ActionRequest request) throws MultipartException {
829         if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) {
830             if (request instanceof MultipartActionRequest) {
831                 logger.debug("Request is already a MultipartActionRequest - probably in a forward");
832             }
833             else {
834                 return this.multipartResolver.resolveMultipart(request);
835             }
836         }
837         // If not returned before: return original request.
838
return request;
839     }
840
841     /**
842      * Return the HandlerExecutionChain for this request.
843      * Try all handler mappings in order.
844      * @param request current portlet request
845      * @param cache whether to cache the HandlerExecutionChain in a request attribute
846      * @return the HandlerExceutionChain, or null if no handler could be found
847      */

848     protected HandlerExecutionChain getHandler(PortletRequest request, boolean cache) throws Exception JavaDoc {
849         HandlerExecutionChain handler =
850                 (HandlerExecutionChain) request.getAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
851         if (handler != null) {
852             if (!cache) {
853                 request.removeAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE);
854             }
855             return handler;
856         }
857
858         Iterator JavaDoc it = this.handlerMappings.iterator();
859         while (it.hasNext()) {
860             HandlerMapping hm = (HandlerMapping) it.next();
861             if (logger.isDebugEnabled()) {
862                 logger.debug("Testing handler map [" + hm + "] in DispatcherPortlet with name '" +
863                         getPortletName() + "'");
864             }
865             handler = hm.getHandler(request);
866             if (handler != null) {
867                 if (cache) {
868                     request.setAttribute(HANDLER_EXECUTION_CHAIN_ATTRIBUTE, handler);
869                 }
870                 return handler;
871             }
872         }
873         return null;
874     }
875
876     /**
877      * No handler found -> throw appropriate exception.
878      * @param request current portlet request
879      * @param response current portlet response
880      */

881     protected void noHandlerFound(PortletRequest request, PortletResponse response) throws PortletException {
882         if (pageNotFoundLogger.isWarnEnabled()) {
883             pageNotFoundLogger.warn("No mapping found for current request " +
884                     "in DispatcherPortlet with name '" + getPortletName() + "'" +
885                     " mode '" + request.getPortletMode() + "'" +
886                     " type '" + (request instanceof ActionRequest ? "action" : "render") + "'" +
887                     " session '" + request.getRequestedSessionId() + "'" +
888                     " user '" + getUsernameForRequest(request) + "'");
889         }
890         throw new UnavailableException("No handler found for request");
891     }
892
893     /**
894      * Return the HandlerAdapter for this handler object.
895      * @param handler the handler object to find an adapter for
896      * @throws PortletException if no HandlerAdapter can be found for the handler.
897      * This is a fatal error.
898      */

899     protected HandlerAdapter getHandlerAdapter(Object JavaDoc handler) throws PortletException {
900         Iterator JavaDoc it = this.handlerAdapters.iterator();
901         while (it.hasNext()) {
902             HandlerAdapter ha = (HandlerAdapter) it.next();
903             if (logger.isDebugEnabled()) {
904                 logger.debug("Testing handler adapter [" + ha + "]");
905             }
906             if (ha.supports(handler)) {
907                 return ha;
908             }
909         }
910         throw new PortletException("No adapter for handler [" + handler +
911                 "]: Does your handler implement a supported interface like Controller?");
912     }
913
914     /**
915      * Determine an error ModelAndView via the registered HandlerExceptionResolvers.
916      * @param request current portlet request
917      * @param response current portlet response
918      * @param handler the executed handler, or null if none chosen at the time of
919      * the exception (for example, if multipart resolution failed)
920      * @param ex the exception that got thrown during handler execution
921      * @return a corresponding ModelAndView to forward to
922      * @throws Exception if no error ModelAndView found
923      */

924     protected ModelAndView processHandlerException(
925             RenderRequest request, RenderResponse response, Object JavaDoc handler, Exception JavaDoc ex)
926             throws Exception JavaDoc {
927
928         ModelAndView exMv = null;
929         for (Iterator JavaDoc it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
930             HandlerExceptionResolver resolver = (HandlerExceptionResolver) it.next();
931             exMv = resolver.resolveException(request, response, handler, ex);
932         }
933         if (exMv != null) {
934             if (logger.isDebugEnabled()) {
935                 logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
936             }
937             logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
938             return exMv;
939         }
940         else {
941             throw ex;
942         }
943     }
944
945     /**
946      * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
947      * Will just invoke afterCompletion for all interceptors whose preHandle
948      * invocation has successfully completed and returned true.
949      * @param mappedHandler the mapped HandlerExecutionChain
950      * @param interceptorIndex index of last interceptor that successfully completed
951      * @param ex Exception thrown on handler execution, or null if none
952      * @see HandlerInterceptor#afterRenderCompletion
953      */

954     private void triggerAfterActionCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
955             ActionRequest request, ActionResponse response, Exception JavaDoc ex)
956             throws Exception JavaDoc {
957
958         // Apply afterCompletion methods of registered interceptors.
959
if (mappedHandler != null) {
960             if (mappedHandler.getInterceptors() != null) {
961                 for (int i = interceptorIndex; i >= 0; i--) {
962                     HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
963                     try {
964                         interceptor.afterActionCompletion(request, response, mappedHandler.getHandler(), ex);
965                     }
966                     catch (Throwable JavaDoc ex2) {
967                         logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
968                     }
969                 }
970             }
971         }
972     }
973
974
975     /**
976      * Render the given ModelAndView. This is the last stage in handling a request.
977      * It may involve resolving the view by name.
978      * @param mv the ModelAndView to render
979      * @param request current portlet render request
980      * @param response current portlet render response
981      * @throws Exception if there's a problem rendering the view
982      */

983     protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception JavaDoc {
984         View view = null;
985         if (mv.isReference()) {
986             // We need to resolve the view name.
987
view = resolveViewName(mv.getViewName(), mv.getModelInternal(), request);
988             if (view == null) {
989                 throw new PortletException("Could not resolve view with name '" + mv.getViewName() +
990                         "' in portlet with name '" + getPortletName() + "'");
991             }
992         }
993         else {
994             // No need to lookup: the ModelAndView object contains the actual View object.
995
Object JavaDoc viewObject = mv.getView();
996             if (viewObject == null) {
997                 throw new PortletException("ModelAndView [" + mv + "] neither contains a view name nor a " +
998                         "View object in portlet with name '" + getPortletName() + "'");
999             }
1000            if (!(viewObject instanceof View)) {
1001                throw new PortletException(
1002                        "View object [" + viewObject + "] is not an instance of [org.springframework.web.servlet.View] - " +
1003                        "DispatcherPortlet does not support any other view types");
1004            }
1005            view = (View) viewObject;
1006        }
1007
1008        if (view == null) {
1009            throw new PortletException("Could not resolve view with name '" + mv.getViewName() +
1010                    "' in portlet with name '" + getPortletName() + "'");
1011        }
1012
1013        // Set the content type on the response if needed and if possible.
1014
// The Portlet spec requires the content type to be set on the RenderResponse;
1015
// it's not sufficient to let the View set it on the ServletResponse.
1016
if (response.getContentType() != null) {
1017            if (logger.isDebugEnabled()) {
1018                logger.debug("Portlet response content type already set to [" + response.getContentType() + "]");
1019            }
1020        }
1021        else {
1022            // No Portlet content type specified yet -> use the view-determined type.
1023
String JavaDoc contentType = view.getContentType();
1024            if (contentType != null) {
1025                if (logger.isDebugEnabled()) {
1026                    logger.debug("Setting portlet response content type to view-determined type [" + contentType + "]");
1027                }
1028                response.setContentType(contentType);
1029            }
1030        }
1031
1032        // Expose Portlet ApplicationContext to view objects.
1033
request.setAttribute(ViewRendererServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, getPortletApplicationContext());
1034
1035        // These attributes are required by the ViewRendererServlet.
1036
request.setAttribute(ViewRendererServlet.VIEW_ATTRIBUTE, view);
1037        request.setAttribute(ViewRendererServlet.MODEL_ATTRIBUTE, mv.getModel());
1038
1039        // Unclude the content of the view in the render response.
1040
getPortletContext().getRequestDispatcher(this.viewRendererUrl).include(request, response);
1041    }
1042
1043    /**
1044     * Resolve the given view name into a View object (to be rendered).
1045     * <p>Default implementations asks all ViewResolvers of this dispatcher.
1046     * Can be overridden for custom resolution strategies, potentially based
1047     * on specific model attributes or request parameters.
1048     * @param viewName the name of the view to resolve
1049     * @param model the model to be passed to the view
1050     * @param request current portlet render request
1051     * @return the View object, or null if none found
1052     * @throws Exception if the view cannot be resolved
1053     * (typically in case of problems creating an actual View object)
1054     * @see ViewResolver#resolveViewName
1055     */

1056    protected View resolveViewName(String JavaDoc viewName, Map JavaDoc model, RenderRequest request) throws Exception JavaDoc {
1057        for (Iterator JavaDoc it = this.viewResolvers.iterator(); it.hasNext();) {
1058            ViewResolver viewResolver = (ViewResolver) it.next();
1059            View view = viewResolver.resolveViewName(viewName, request.getLocale());
1060            if (view != null) {
1061                return view;
1062            }
1063        }
1064        return null;
1065    }
1066
1067    /**
1068     * Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
1069     * Will just invoke afterCompletion for all interceptors whose preHandle
1070     * invocation has successfully completed and returned true.
1071     * @param mappedHandler the mapped HandlerExecutionChain
1072     * @param interceptorIndex index of last interceptor that successfully completed
1073     * @param ex Exception thrown on handler execution, or null if none
1074     * @see HandlerInterceptor#afterRenderCompletion
1075     */

1076    private void triggerAfterRenderCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
1077            RenderRequest request, RenderResponse response, Exception JavaDoc ex)
1078            throws Exception JavaDoc {
1079
1080        // Apply afterCompletion methods of registered interceptors.
1081
if (mappedHandler != null) {
1082            if (mappedHandler.getInterceptors() != null) {
1083                for (int i = interceptorIndex; i >= 0; i--) {
1084                    HandlerInterceptor interceptor = mappedHandler.getInterceptors()[i];
1085                    try {
1086                        interceptor.afterRenderCompletion(request, response, mappedHandler.getHandler(), ex);
1087                    }
1088                    catch (Throwable JavaDoc ex2) {
1089                        logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
1090                    }
1091                }
1092            }
1093        }
1094    }
1095
1096}
1097
Popular Tags