updated Spring Portlet MVC to Portlet API 2.0

This commit is contained in:
Juergen Hoeller
2009-01-19 23:32:32 +00:00
parent 76888e243f
commit 464c7eedf2
64 changed files with 4197 additions and 1140 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,12 +26,17 @@ import java.util.Map;
import java.util.Properties;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.UnavailableException;
import org.apache.commons.logging.Log;
@@ -42,18 +47,12 @@ import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.core.OrderComparator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.portlet.context.PortletRequestAttributes;
import org.springframework.web.portlet.multipart.MultipartActionRequest;
import org.springframework.web.portlet.multipart.PortletMultipartResolver;
import org.springframework.web.servlet.View;
@@ -74,17 +73,15 @@ import org.springframework.web.servlet.ViewResolver;
*
* <li>It can use any {@link HandlerMapping} implementation - pre-built or provided
* as part of an application - to control the routing of requests to handler objects.
* Default is a {@link org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping}
* on Java 5+; there is no default on Java 1.4. HandlerMapping objects can be defined as
* beans in the portlet's application context, implementing the HandlerMapping interface,
* overriding the default HandlerMapping if present. HandlerMappings can be given any
* bean name (they are tested by type).
* Default is a {@link org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping}.
* HandlerMapping objects can be defined as beans in the portlet's application context,
* implementing the HandlerMapping interface, overriding the default HandlerMapping if present.
* HandlerMappings can be given any bean name (they are tested by type).
*
* <li>It can use any {@link HandlerAdapter}; this allows for using any handler interface.
* The default adapter is {@link org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter}
* for Spring's {@link org.springframework.web.portlet.mvc.Controller} interface.
* When running in a Java 5+ environment, a default
* {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
* A default {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter}
* will be registered as well. HandlerAdapter objects can be added as beans in the
* application context, overriding the default HandlerAdapter. Like HandlerMappings,
* HandlerAdapters can be given any bean name (they are tested by type).
@@ -253,9 +250,6 @@ public class DispatcherPortlet extends FrameworkPortlet {
/** URL that points to the ViewRendererServlet */
private String viewRendererUrl = DEFAULT_VIEW_RENDERER_URL;
/** Expose LocaleContext and RequestAttributes as inheritable for child threads? */
private boolean threadContextInheritable = false;
/** MultipartResolver used by this portlet */
private PortletMultipartResolver multipartResolver;
@@ -325,22 +319,6 @@ public class DispatcherPortlet extends FrameworkPortlet {
this.viewRendererUrl = viewRendererUrl;
}
/**
* Set whether to expose the LocaleContext and RequestAttributes as inheritable
* for child threads (using an {@link java.lang.InheritableThreadLocal}).
* <p>Default is "false", to avoid side effects on spawned background threads.
* Switch this to "true" to enable inheritance for custom child threads which
* are spawned during request processing and only used for this request
* (that is, ending after their initial task, without reuse of the thread).
* <p><b>WARNING:</b> Do not use inheritance for child threads if you are
* accessing a thread pool which is configured to potentially add new threads
* on demand (e.g. a JDK {@link java.util.concurrent.ThreadPoolExecutor}),
* since this will expose the inherited context to such a pooled thread.
*/
public void setThreadContextInheritable(boolean threadContextInheritable) {
this.threadContextInheritable = threadContextInheritable;
}
/**
* This implementation calls {@link #initStrategies}.
@@ -638,19 +616,6 @@ public class DispatcherPortlet extends FrameworkPortlet {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
}
// Expose current LocaleResolver and request as LocaleContext.
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);
// Expose current RequestAttributes to current thread.
RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
if (logger.isDebugEnabled()) {
logger.debug("Bound action request context to thread: " + request);
}
ActionRequest processedRequest = request;
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
@@ -713,16 +678,6 @@ public class DispatcherPortlet extends FrameworkPortlet {
if (processedRequest instanceof MultipartActionRequest && processedRequest != request) {
this.multipartResolver.cleanupMultipart((MultipartActionRequest) processedRequest);
}
// Reset thread-bound context.
RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);
LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);
// Clear request attributes.
requestAttributes.requestCompleted();
if (logger.isDebugEnabled()) {
logger.debug("Cleared thread-bound action request context: " + request);
}
}
}
@@ -741,19 +696,6 @@ public class DispatcherPortlet extends FrameworkPortlet {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received render request");
}
// Expose current LocaleResolver and request as LocaleContext.
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);
// Expose current RequestAttributes to current thread.
RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
if (logger.isDebugEnabled()) {
logger.debug("Bound render request context to thread: " + request);
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
@@ -843,31 +785,185 @@ public class DispatcherPortlet extends FrameworkPortlet {
triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
finally {
// Reset thread-bound context.
RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);
LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);
/**
* Processes the actual dispatching to the handler for resource requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet render request
* @param response current portlet render response
* @throws Exception in case of any kind of processing failure
*/
@Override
protected void doResourceService(ResourceRequest request, ResourceResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received resource request");
}
// Clear request attributes.
requestAttributes.requestCompleted();
if (logger.isDebugEnabled()) {
logger.debug("Cleared thread-bound render request context: " + request);
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
ModelAndView mv = null;
try {
// Check for forwarded exception from the action phase
PortletSession session = request.getPortletSession(false);
if (session != null) {
if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
Exception ex = (Exception) session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
if (ex != null) {
logger.debug("Render phase found exception caught during action phase - rethrowing it");
throw ex;
}
}
else {
session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
}
}
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleResource(request, response, mappedHandler.getHandler())) {
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
mv = ha.handleResource(request, response, mappedHandler.getHandler());
// Apply postHandle methods of registered interceptors.
if (interceptors != null) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandleResource(request, response, mappedHandler.getHandler(), mv);
}
}
}
catch (ModelAndViewDefiningException ex) {
logger.debug("ModelAndViewDefiningException encountered", ex);
mv = ex.getModelAndView();
}
catch (Exception ex) {
Object handler = (mappedHandler != null ? mappedHandler.getHandler() : null);
mv = processHandlerException(request, response, handler, ex);
}
// Did the handler return a view to render?
if (mv != null && !mv.isEmpty()) {
render(mv, request, response);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Null ModelAndView returned to DispatcherPortlet with name '" +
getPortletName() + "': assuming HandlerAdapter completed request handling");
}
}
// Trigger after-completion for successful outcome.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterResourceCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Build a LocaleContext for the given request, exposing the request's
* primary locale as current locale.
* @param request current HTTP request
* @return the corresponding LocaleContext
* Processes the actual dispatching to the handler for event requests.
* <p>The handler will be obtained by applying the portlet's HandlerMappings in order.
* The HandlerAdapter will be obtained by querying the portlet's installed
* HandlerAdapters to find the first that supports the handler class.
* @param request current portlet action request
* @param response current portlet Action response
* @throws Exception in case of any kind of processing failure
*/
protected LocaleContext buildLocaleContext(PortletRequest request) {
return new SimpleLocaleContext(request.getLocale());
@Override
protected void doEventService(EventRequest request, EventResponse response) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request");
}
HandlerExecutionChain mappedHandler = null;
int interceptorIndex = -1;
try {
// Determine handler for the current request.
mappedHandler = getHandler(request, false);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(request, response);
return;
}
// Apply preHandle methods of registered interceptors.
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = 0; i < interceptors.length; i++) {
HandlerInterceptor interceptor = interceptors[i];
if (!interceptor.preHandleEvent(request, response, mappedHandler.getHandler())) {
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, null);
return;
}
interceptorIndex = i;
}
}
// Actually invoke the handler.
HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler());
ha.handleEvent(request, response, mappedHandler.getHandler());
// Trigger after-completion for successful outcome.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, null);
}
catch (Exception ex) {
// Trigger after-completion for thrown exception.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, ex);
// Forward the exception to the render phase to be displayed.
try {
response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString());
request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex);
logger.debug("Caught exception during action phase - forwarding to render phase", ex);
}
catch (IllegalStateException ex2) {
// Probably sendRedirect called... need to rethrow exception immediately.
throw ex;
}
}
catch (Error err) {
PortletException ex =
new PortletException("Error occured during request processing: " + err.getMessage(), err);
// Trigger after-completion for thrown exception.
triggerAfterEventCompletion(mappedHandler, interceptorIndex, request, response, ex);
throw ex;
}
}
/**
* Convert the request into a multipart request, and make multipart resolver available.
* If no multipart resolver is set, simply use the existing request.
@@ -929,11 +1025,11 @@ public class DispatcherPortlet extends FrameworkPortlet {
protected void noHandlerFound(PortletRequest request, PortletResponse response) throws Exception {
if (pageNotFoundLogger.isWarnEnabled()) {
pageNotFoundLogger.warn("No mapping found for current request " +
"in DispatcherPortlet with name '" + getPortletName() + "'" +
", mode '" + request.getPortletMode() + "'" +
", type '" + (response instanceof ActionResponse ? "action" : "render") + "'" +
", session '" + request.getRequestedSessionId() + "'" +
", user '" + getUsernameForRequest(request) + "'");
"in DispatcherPortlet with name '" + getPortletName() +
"', mode '" + request.getPortletMode() +
"', phase '" + request.getAttribute(PortletRequest.LIFECYCLE_PHASE) +
"', session '" + request.getRequestedSessionId() +
"', user '" + getUsernameForRequest(request) + "'");
}
throw new UnavailableException("No handler found for request");
}
@@ -957,67 +1053,6 @@ public class DispatcherPortlet extends FrameworkPortlet {
"]: Does your handler implement a supported interface like Controller?");
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterActionCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ActionRequest request, ActionResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterActionCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Render the given ModelAndView. This is the last stage in handling a request.
@@ -1027,7 +1062,7 @@ public class DispatcherPortlet extends FrameworkPortlet {
* @param response current portlet render response
* @throws Exception if there's a problem rendering the view
*/
protected void render(ModelAndView mv, RenderRequest request, RenderResponse response) throws Exception {
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
View view = null;
if (mv.isReference()) {
// We need to resolve the view name.
@@ -1087,7 +1122,7 @@ public class DispatcherPortlet extends FrameworkPortlet {
* (typically in case of problems creating an actual View object)
* @see ViewResolver#resolveViewName
*/
protected View resolveViewName(String viewName, Map model, RenderRequest request) throws Exception {
protected View resolveViewName(String viewName, Map model, PortletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, request.getLocale());
if (view != null) {
@@ -1107,7 +1142,7 @@ public class DispatcherPortlet extends FrameworkPortlet {
* @param response current portlet render response
* @throws Exception if there's a problem rendering the view
*/
protected void doRender(View view, Map model, RenderRequest request, RenderResponse response) throws Exception {
protected void doRender(View view, Map model, PortletRequest request, MimeResponse response) throws Exception {
// Expose Portlet ApplicationContext to view objects.
request.setAttribute(ViewRendererServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, getPortletApplicationContext());
@@ -1119,6 +1154,99 @@ public class DispatcherPortlet extends FrameworkPortlet {
getPortletContext().getRequestDispatcher(this.viewRendererUrl).include(request, response);
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Determine an error ModelAndView via the registered HandlerExceptionResolvers.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to
* @throws Exception if no error ModelAndView found
*/
protected ModelAndView processHandlerException(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex)
throws Exception {
ModelAndView exMv = null;
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = it.next();
exMv = resolver.resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
logger.debug("HandlerExceptionResolver returned ModelAndView [" + exMv + "] for exception");
}
logger.warn("Handler execution resulted in exception - forwarding to resolved error view", ex);
return exMv;
}
else {
throw ex;
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterActionCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ActionRequest request, ActionResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterActionCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
@@ -1149,4 +1277,64 @@ public class DispatcherPortlet extends FrameworkPortlet {
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterResourceCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
ResourceRequest request, ResourceResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterResourceCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
/**
* Trigger afterCompletion callbacks on the mapped HandlerInterceptors.
* Will just invoke afterCompletion for all interceptors whose preHandle
* invocation has successfully completed and returned true.
* @param mappedHandler the mapped HandlerExecutionChain
* @param interceptorIndex index of last interceptor that successfully completed
* @param ex Exception thrown on handler execution, or null if none
* @see HandlerInterceptor#afterRenderCompletion
*/
private void triggerAfterEventCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex,
EventRequest request, EventResponse response, Exception ex)
throws Exception {
// Apply afterCompletion methods of registered interceptors.
if (mappedHandler != null) {
HandlerInterceptor[] interceptors = mappedHandler.getInterceptors();
if (interceptors != null) {
for (int i = interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterEventCompletion(request, response, mappedHandler.getHandler(), ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,14 +19,17 @@ package org.springframework.web.portlet;
import java.io.IOException;
import java.security.Principal;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
@@ -37,8 +40,14 @@ import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.SourceFilteringListener;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.i18n.SimpleLocaleContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.PortletApplicationContextUtils;
import org.springframework.web.portlet.context.PortletRequestAttributes;
import org.springframework.web.portlet.context.PortletRequestHandledEvent;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
@@ -136,6 +145,9 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
/** Should we publish a PortletRequestHandledEvent at the end of each request? */
private boolean publishEvents = true;
/** Expose LocaleContext and RequestAttributes as inheritable for child threads? */
private boolean threadContextInheritable = false;
/** USER_INFO attributes that may contain the username of the current user */
private String[] userinfoUsernameAttributes = DEFAULT_USERINFO_ATTRIBUTE_NAMES;
@@ -205,13 +217,6 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
this.publishContext = publishContext;
}
/**
* Return whether to publish this portlet's context as a PortletContext attribute.
*/
public boolean isPublishContext() {
return this.publishContext;
}
/**
* Set whether this portlet should publish a PortletRequestHandledEvent at the end
* of each request. Default is true; can be turned off for a slight performance
@@ -223,11 +228,19 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
}
/**
* Return whether this portlet should publish a PortletRequestHandledEvent at the end
* of each request.
* Set whether to expose the LocaleContext and RequestAttributes as inheritable
* for child threads (using an {@link java.lang.InheritableThreadLocal}).
* <p>Default is "false", to avoid side effects on spawned background threads.
* Switch this to "true" to enable inheritance for custom child threads which
* are spawned during request processing and only used for this request
* (that is, ending after their initial task, without reuse of the thread).
* <p><b>WARNING:</b> Do not use inheritance for child threads if you are
* accessing a thread pool which is configured to potentially add new threads
* on demand (e.g. a JDK {@link java.util.concurrent.ThreadPoolExecutor}),
* since this will expose the inherited context to such a pooled thread.
*/
public boolean isPublishEvents() {
return this.publishEvents;
public void setThreadContextInheritable(boolean threadContextInheritable) {
this.threadContextInheritable = threadContextInheritable;
}
/**
@@ -239,15 +252,6 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
this.userinfoUsernameAttributes = userinfoUsernameAttributes;
}
/**
* Returns the list of attributes that will be searched in the USER_INFO map
* when trying to find the username of the current user
* @see #getUsernameForRequest
*/
public String[] getUserinfoUsernameAttributes() {
return this.userinfoUsernameAttributes;
}
/**
* Overridden method of GenericPortletBean, invoked after any bean properties
@@ -297,7 +301,7 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
onRefresh(pac);
}
if (isPublishContext()) {
if (this.publishContext) {
// publish the context as a portlet context attribute
String attName = getPortletContextAttributeName();
getPortletContext().setAttribute(attName, pac);
@@ -446,6 +450,16 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
}
}
/**
* Delegate action requests to processRequest/doActionService.
*/
@Override
public final void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
processRequest(request, response);
}
/**
* Delegate render requests to processRequest/doRenderService.
*/
@@ -456,16 +470,20 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
processRequest(request, response);
}
/**
* Delegate action requests to processRequest/doActionService.
*/
@Override
public final void processAction(ActionRequest request, ActionResponse response)
public void serveResource(ResourceRequest request, ResourceResponse response)
throws PortletException, IOException {
processRequest(request, response);
}
@Override
public void processEvent(EventRequest request, EventResponse response)
throws PortletException, IOException {
processRequest(request, response);
}
/**
* Process this request, publishing an event regardless of the outcome.
* The actual event handling is performed by the abstract
@@ -479,13 +497,36 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
long startTime = System.currentTimeMillis();
Throwable failureCause = null;
// Expose current LocaleResolver and request as LocaleContext.
LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
LocaleContextHolder.setLocaleContext(buildLocaleContext(request), this.threadContextInheritable);
// Expose current RequestAttributes to current thread.
RequestAttributes previousRequestAttributes = RequestContextHolder.getRequestAttributes();
PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
if (logger.isTraceEnabled()) {
logger.trace("Bound request context to thread: " + request);
}
try {
if (request instanceof ActionRequest) {
String phase = (String) request.getAttribute(PortletRequest.LIFECYCLE_PHASE);
if (PortletRequest.ACTION_PHASE.equals(phase)) {
doActionService((ActionRequest) request, (ActionResponse) response);
}
else {
else if (PortletRequest.RENDER_PHASE.equals(phase)) {
doRenderService((RenderRequest) request, (RenderResponse) response);
}
else if (PortletRequest.RESOURCE_PHASE.equals(phase)) {
doResourceService((ResourceRequest) request, (ResourceResponse) response);
}
else if (PortletRequest.EVENT_PHASE.equals(phase)) {
doEventService((EventRequest) request, (EventResponse) response);
}
else {
throw new IllegalStateException("Invalid portlet request phase: " + phase);
}
}
catch (PortletException ex) {
failureCause = ex;
@@ -501,13 +542,23 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
}
finally {
// Reset thread-bound context.
RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable);
LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable);
// Clear request attributes.
requestAttributes.requestCompleted();
if (logger.isTraceEnabled()) {
logger.trace("Cleared thread-bound resource request context: " + request);
}
if (failureCause != null) {
logger.error("Could not complete request", failureCause);
}
else {
logger.debug("Successfully completed request");
}
if (isPublishEvents()) {
if (this.publishEvents) {
// Whether or not we succeeded, publish an event.
long processingTime = System.currentTimeMillis() - startTime;
this.portletApplicationContext.publishEvent(
@@ -520,6 +571,16 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
}
}
/**
* Build a LocaleContext for the given request, exposing the request's
* primary locale as current locale.
* @param request current HTTP request
* @return the corresponding LocaleContext
*/
protected LocaleContext buildLocaleContext(PortletRequest request) {
return new SimpleLocaleContext(request.getLocale());
}
/**
* Determine the username for the given request.
* <p>The default implementation first tries the UserPrincipal.
@@ -560,6 +621,21 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
return null;
}
/**
* Subclasses must implement this method to do the work of action request handling.
* <p>The contract is essentially the same as that for the <code>processAction</code>
* method of GenericPortlet.
* <p>This class intercepts calls to ensure that exception handling and
* event publication takes place.
* @param request current action request
* @param response current action response
* @throws Exception in case of any kind of processing failure
* @see javax.portlet.GenericPortlet#processAction
*/
protected abstract void doActionService(ActionRequest request, ActionResponse response)
throws Exception;
/**
* Subclasses must implement this method to do the work of render request handling.
* <p>The contract is essentially the same as that for the <code>doDispatch</code>
@@ -575,17 +651,31 @@ public abstract class FrameworkPortlet extends GenericPortletBean implements App
throws Exception;
/**
* Subclasses must implement this method to do the work of action request handling.
* <p>The contract is essentially the same as that for the <code>processAction</code>
* Subclasses must implement this method to do the work of resource request handling.
* <p>The contract is essentially the same as that for the <code>serveResource</code>
* method of GenericPortlet.
* <p>This class intercepts calls to ensure that exception handling and
* event publication takes place.
* @param request current action request
* @param response current action response
* @param request current resource request
* @param response current resource response
* @throws Exception in case of any kind of processing failure
* @see javax.portlet.GenericPortlet#processAction
* @see javax.portlet.GenericPortlet#serveResource
*/
protected abstract void doActionService(ActionRequest request, ActionResponse response)
protected abstract void doResourceService(ResourceRequest request, ResourceResponse response)
throws Exception;
/**
* Subclasses must implement this method to do the work of event request handling.
* <p>The contract is essentially the same as that for the <code>processEvent</code>
* method of GenericPortlet.
* <p>This class intercepts calls to ensure that exception handling and
* event publication takes place.
* @param request current event request
* @param response current event response
* @throws Exception in case of any kind of processing failure
* @see javax.portlet.GenericPortlet#processEvent
*/
protected abstract void doEventService(EventRequest request, EventResponse response)
throws Exception;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.web.portlet;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
/**
* Portlet MVC framework SPI interface, allowing parameterization of core MVC workflow.
@@ -67,6 +71,7 @@ public interface HandlerAdapter {
* to the <code>supports</code> method of this interface, which must have
* returned true.
* @throws Exception in case of errors
* @see javax.portlet.Portlet#processAction
*/
void handleAction(ActionRequest request, ActionResponse response, Object handler) throws Exception;
@@ -81,7 +86,36 @@ public interface HandlerAdapter {
* @throws Exception in case of errors
* @return ModelAndView object with the name of the view and the required
* model data, or <code>null</code> if the request has been handled directly
* @see javax.portlet.Portlet#render
*/
ModelAndView handleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception;
/**
* Use the given handler to handle this resource request.
* The workflow that is required may vary widely.
* @param request current render request
* @param response current render response
* @param handler handler to use. This object must have previously been passed
* to the <code>supports</code> method of this interface, which must have
* returned <code>true</code>.
* @throws Exception in case of errors
* @return ModelAndView object with the name of the view and the required
* model data, or <code>null</code> if the request has been handled directly
* @see javax.portlet.ResourceServingPortlet#serveResource
*/
ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler) throws Exception;
/**
* Use the given handler to handle this event request.
* The workflow that is required may vary widely.
* @param request current action request
* @param response current action response
* @param handler handler to use. This object must have previously been passed
* to the <code>supports</code> method of this interface, which must have
* returned true.
* @throws Exception in case of errors
* @see javax.portlet.EventPortlet#processEvent
*/
void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception;
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -18,6 +18,8 @@ package org.springframework.web.portlet;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
/**
* Interface to be implemented by objects than can resolve exceptions thrown
@@ -47,4 +49,17 @@ public interface HandlerExceptionResolver {
ModelAndView resolveException(
RenderRequest request, RenderResponse response, Object handler, Exception ex);
/**
* Try to resolve the given exception that got thrown during on handler execution,
* returning a ModelAndView that represents a specific error page if appropriate.
* @param request current portlet request
* @param response current portlet response
* @param handler the executed handler, or null if none chosen at the time of
* the exception (for example, if multipart resolution failed)
* @param ex the exception that got thrown during handler execution
* @return a corresponding ModelAndView to forward to, or null for default processing
*/
ModelAndView resolveException(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,10 @@ import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.EventResponse;
import javax.portlet.EventRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ResourceRequest;
/**
* Workflow interface that allows for customized handler execution chains.
@@ -130,7 +134,7 @@ public interface HandlerInterceptor {
* @throws Exception in case of errors
*/
boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler)
throws Exception;
throws Exception;
/**
* Callback after completion of request processing in the action phase, that is,
@@ -149,7 +153,7 @@ public interface HandlerInterceptor {
*/
void afterActionCompletion(
ActionRequest request, ActionResponse response, Object handler, Exception ex)
throws Exception;
throws Exception;
/**
* Intercept the execution of a handler in the render phase.
@@ -169,7 +173,7 @@ public interface HandlerInterceptor {
* @throws Exception in case of errors
*/
boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler)
throws Exception;
throws Exception;
/**
* Intercept the execution of a handler in the render phase.
@@ -208,4 +212,101 @@ public interface HandlerInterceptor {
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception;
/**
* Intercept the execution of a handler in the render phase.
* <p>Called after a HandlerMapping determines an appropriate handler object
* to handle a {@link RenderRequest}, but before said HandlerAdapter actually
* invokes the handler.
* <p>{@link DispatcherPortlet} processes a handler in an execution chain,
* consisting of any number of interceptors, with the handler itself at the end.
* With this method, each interceptor can decide to abort the execution chain,
* typically throwing an exception or writing a custom response.
* @param request current portlet render request
* @param response current portlet render response
* @param handler chosen handler to execute, for type and/or instance evaluation
* @return <code>true</code> if the execution chain should proceed with the
* next interceptor or the handler itself. Else, <code>DispatcherPortlet</code>
* assumes that this interceptor has already dealt with the response itself
* @throws Exception in case of errors
*/
boolean preHandleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception;
/**
* Intercept the execution of a handler in the render phase.
* <p>Called after a {@link HandlerAdapter} actually invoked the handler, but
* before the <code>DispatcherPortlet</code> renders the view. Can thus expose
* additional model objects to the view via the given {@link ModelAndView}.
* <p><code>DispatcherPortlet</code> processes a handler in an execution chain,
* consisting of any number of interceptors, with the handler itself at the end.
* With this method, each interceptor can post-process an execution, getting
* applied in inverse order of the execution chain.
* @param request current portlet render request
* @param response current portlet render response
* @param handler chosen handler to execute, for type and/or instance examination
* @param modelAndView the <code>ModelAndView</code> that the handler returned
* (can also be <code>null</code>)
* @throws Exception in case of errors
*/
void postHandleResource(
ResourceRequest request, ResourceResponse response, Object handler, ModelAndView modelAndView)
throws Exception;
/**
* Callback after completion of request processing, that is, after rendering
* the view. Will be called on any outcome of handler execution, thus allowing
* for proper resource cleanup.
* <p>Note: Will only be called if this interceptor's
* {@link #preHandleRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse, Object)}
* method has successfully completed and returned <code>true</code>!
* @param request current portlet render request
* @param response current portlet render response
* @param handler chosen handler to execute, for type and/or instance examination
* @param ex exception thrown on handler execution, if any
* @throws Exception in case of errors
*/
void afterResourceCompletion(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex)
throws Exception;
/**
* Intercept the execution of a handler in the action phase.
* <p>Called after a HandlerMapping determines an appropriate handler object
* to handle an {@link ActionRequest}, but before said HandlerAdapter actually
* invokes the handler.
* <p>{@link DispatcherPortlet} processes a handler in an execution chain,
* consisting of any number of interceptors, with the handler itself at the end.
* With this method, each interceptor can decide to abort the execution chain,
* typically throwing an exception or writing a custom response.
* @param request current portlet action request
* @param response current portlet action response
* @param handler chosen handler to execute, for type and/or instance evaluation
* @return <code>true</code> if the execution chain should proceed with the
* next interceptor or the handler itself. Else, <code>DispatcherPortlet</code>
* assumes that this interceptor has already dealt with the response itself
* @throws Exception in case of errors
*/
boolean preHandleEvent(EventRequest request, EventResponse response, Object handler)
throws Exception;
/**
* Callback after completion of request processing in the action phase, that is,
* after rendering the view. Will be called on any outcome of handler execution,
* thus allowing for proper resource cleanup.
* <p>Note: Will only be called if this interceptor's
* {@link #preHandleAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse, Object)}
* method has successfully completed and returned <code>true</code>!
* @param request current portlet action request
* @param response current portlet action response
* @param handler chosen handler to execute, for type and/or instance examination
* @param ex exception thrown on handler execution, if any (only included as
* additional context information for the case where a handler threw an exception;
* request execution may have failed even when this argument is <code>null</code>)
* @throws Exception in case of errors
*/
void afterEventCompletion(
EventRequest request, EventResponse response, Object handler, Exception ex)
throws Exception;
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.web.bind.annotation.Mapping;
/**
* Annotation for mapping Portlet action requests onto handler methods.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.bind.annotation.RequestMapping
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface ActionMapping {
/**
* The name of the action, according to the Portlet 2.0
* "javax.portlet.action" parameter.
* <p>If not specified, the method will be used as default handler:
* i.e. for action requests where no specific action mapping was found.
* <p>Note that all such annotated action methods only apply within the
* <code>@RequestMapping</code> constraints of the containing handler class.
* @see javax.portlet.ActionRequest#ACTION_NAME
*/
String value() default "";
/**
* The parameters of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "myParam=myValue" style
* expressions, with a request only mapped if each such parameter is found
* to have the given value. "myParam" style expressions are also supported,
* with such parameters having to be present in the request (allowed to have
* any value). Finally, "!myParam" style expressions indicate that the
* specified parameter is <i>not</i> supposed to be present in the request.
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
String[] params() default {};
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.web.bind.annotation.Mapping;
/**
* Annotation for mapping Portlet event requests onto handler methods.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.bind.annotation.RequestMapping
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface EventMapping {
/**
* The name of the event to be handled.
* <p>Typically the local name of the event, but fully qualified names
* with a "{...}" namespace part will be mapped correctly as well.
* <p>If not specified, the render method will be invoked for any
* event request within its general mapping.
* @see javax.portlet.EventRequest#getEvent()
* @see javax.portlet.Event#getName()
*/
String value();
/**
* The parameters of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "myParam=myValue" style
* expressions, with a request only mapped if each such parameter is found
* to have the given value. "myParam" style expressions are also supported,
* with such parameters having to be present in the request (allowed to have
* any value). Finally, "!myParam" style expressions indicate that the
* specified parameter is <i>not</i> supposed to be present in the request.
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
String[] params() default {};
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.web.bind.annotation.Mapping;
/**
* Annotation for mapping Portlet render requests onto handler methods.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.bind.annotation.RequestMapping
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RenderMapping {
/**
* The window state that the annotated render method applies for.
* <p>If not specified, the render method will be invoked for any
* window state within its general mapping.
* <p>Standard Portlet spec values: "NORMAL", "MAXIMIZED", "MINIMIZED".
* Custom window states can be used as well, as supported by the portal.
* @see javax.portlet.PortletRequest#getWindowState()
*/
String value() default "";
/**
* The parameters of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "myParam=myValue" style
* expressions, with a request only mapped if each such parameter is found
* to have the given value. "myParam" style expressions are also supported,
* with such parameters having to be present in the request (allowed to have
* any value). Finally, "!myParam" style expressions indicate that the
* specified parameter is <i>not</i> supposed to be present in the request.
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
String[] params() default {};
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.web.bind.annotation.Mapping;
/**
* Annotation for mapping Portlet resource requests onto handler methods.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.bind.annotation.RequestMapping
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface ResourceMapping {
/**
* The id of the resource to be handled.
* <p>If not specified, the render method will be invoked for any
* resource request within its general mapping.
* @see javax.portlet.ResourceRequest#getResourceID()
*/
String value() default "";
/**
* The parameters of the mapped request, narrowing the primary mapping.
* <p>Same format for any environment: a sequence of "myParam=myValue" style
* expressions, with a request only mapped if each such parameter is found
* to have the given value. "myParam" style expressions are also supported,
* with such parameters having to be present in the request (allowed to have
* any value). Finally, "!myParam" style expressions indicate that the
* specified parameter is <i>not</i> supposed to be present in the request.
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
String[] params() default {};
}

View File

@@ -0,0 +1,7 @@
<html>
<body>
Annotations for binding portlet requests to handler methods.
</body>
</html>

View File

@@ -22,6 +22,7 @@ import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import org.springframework.beans.BeansException;
@@ -80,6 +81,7 @@ public abstract class AbstractMapBasedHandlerMapping<K> extends AbstractHandlerM
Collections.sort(predicates);
for (PortletRequestMappingPredicate predicate : predicates) {
if (predicate.match(request)) {
predicate.validate(request);
return predicateMap.get(predicate);
}
}
@@ -187,6 +189,13 @@ public abstract class AbstractMapBasedHandlerMapping<K> extends AbstractHandlerM
* @param request current portlet request
*/
boolean match(PortletRequest request);
/**
* Validate this predicate's mapping against the current request.
* @param request current portlet request
* @throws PortletException if validation failed
*/
void validate(PortletRequest request) throws PortletException;
}
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,21 +16,22 @@
package org.springframework.web.portlet.handler;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.web.portlet.HandlerInterceptor;
import org.springframework.web.portlet.ModelAndView;
/**
* Abstract adapter class for the HandlerInterceptor interface,
* Abstract adapter class for the {@link HandlerInterceptor} interface,
* for simplified implementation of pre-only/post-only interceptors.
*
* @author Juergen Hoeller
@@ -40,29 +41,31 @@ import org.springframework.web.portlet.ModelAndView;
public abstract class HandlerInterceptorAdapter implements HandlerInterceptor {
/**
* This implementation delegates to <code>preHandle</code>.
* @see #preHandle
* This implementation delegates to {@link #preHandle}.
*/
public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) throws Exception {
public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler)
throws Exception {
return preHandle(request, response, handler);
}
/**
* This implementation delegates to <code>afterCompletion</code>.
* @see #afterCompletion
* This implementation delegates to {@link #afterCompletion}.
*/
public void afterActionCompletion(
ActionRequest request, ActionResponse response, Object handler, Exception ex) throws Exception {
ActionRequest request, ActionResponse response, Object handler, Exception ex)
throws Exception {
afterCompletion(request, response, handler, ex);
}
/**
* This implementation delegates to <code>preHandle</code>.
* @see #preHandle
* This implementation delegates to {@link #preHandle}.
*/
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception {
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler)
throws Exception {
return preHandle(request, response, handler);
}
@@ -70,26 +73,72 @@ public abstract class HandlerInterceptorAdapter implements HandlerInterceptor {
* This implementation is empty.
*/
public void postHandleRender(
RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView) throws Exception {
RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
/**
* This implementation delegates to <code>afterCompletion</code>.
* @see #afterCompletion
* This implementation delegates to {@link #afterCompletion}.
*/
public void afterRenderCompletion(
RenderRequest request, RenderResponse response, Object handler, Exception ex) throws Exception {
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception {
afterCompletion(request, response, handler, ex);
}
/**
* Default callback that both <code>preHandleRender</code>
* and <code>preHandleAction</code> delegate to.
* This implementation delegates to {@link #preHandle}.
*/
public boolean preHandleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception {
return preHandle(request, response, handler);
}
/**
* This implementation is empty.
*/
public void postHandleResource(
ResourceRequest request, ResourceResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
}
/**
* This implementation delegates to {@link #afterCompletion}.
*/
public void afterResourceCompletion(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex)
throws Exception {
afterCompletion(request, response, handler, ex);
}
/**
* This implementation delegates to {@link #preHandle}.
*/
public boolean preHandleEvent(EventRequest request, EventResponse response, Object handler)
throws Exception {
return preHandle(request, response, handler);
}
/**
* This implementation delegates to {@link #afterCompletion}.
*/
public void afterEventCompletion(
EventRequest request, EventResponse response, Object handler, Exception ex)
throws Exception {
afterCompletion(request, response, handler, ex);
}
/**
* Default callback that all "pre*" methods delegate to.
* <p>This implementation always returns <code>true</code>.
* @see #preHandleRender
* @see #preHandleAction
*/
protected boolean preHandle(PortletRequest request, PortletResponse response, Object handler)
throws Exception {
@@ -98,14 +147,12 @@ public abstract class HandlerInterceptorAdapter implements HandlerInterceptor {
}
/**
* Default callback that both <code>preHandleRender</code>
* and <code>preHandleAction</code> delegate to.
* Default callback that all "after*" methods delegate to.
* <p>This implementation is empty.
* @see #afterRenderCompletion
* @see #afterActionCompletion
*/
protected void afterCompletion(
PortletRequest request, PortletResponse response, Object handler, Exception ex) throws Exception {
PortletRequest request, PortletResponse response, Object handler, Exception ex)
throws Exception {
}

View File

@@ -16,11 +16,10 @@
package org.springframework.web.portlet.handler;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.web.portlet.context.PortletApplicationObjectSupport;
@@ -102,7 +101,7 @@ public abstract class PortletContentGenerator extends PortletApplicationObjectSu
* @param response current portlet response
* @throws PortletException if the request cannot be handled because a check failed
*/
protected final void checkAndPrepare(RenderRequest request, RenderResponse response)
protected final void checkAndPrepare(PortletRequest request, MimeResponse response)
throws PortletException {
checkAndPrepare(request, response, this.cacheSeconds);
@@ -118,8 +117,7 @@ public abstract class PortletContentGenerator extends PortletApplicationObjectSu
* response should be cacheable for, 0 to prevent caching
* @throws PortletException if the request cannot be handled because a check failed
*/
protected final void checkAndPrepare(
RenderRequest request, RenderResponse response, int cacheSeconds)
protected final void checkAndPrepare(PortletRequest request, MimeResponse response, int cacheSeconds)
throws PortletException {
check(request, response);
@@ -129,7 +127,7 @@ public abstract class PortletContentGenerator extends PortletApplicationObjectSu
/**
* Prevent the render response from being cached.
*/
protected final void preventCaching(RenderResponse response) {
protected final void preventCaching(MimeResponse response) {
cacheForSeconds(response, 0);
}
@@ -139,8 +137,8 @@ public abstract class PortletContentGenerator extends PortletApplicationObjectSu
* @param seconds number of seconds into the future that the response
* should be cacheable for
*/
protected final void cacheForSeconds(RenderResponse response, int seconds) {
response.setProperty(RenderResponse.EXPIRATION_CACHE, Integer.toString(seconds));
protected final void cacheForSeconds(MimeResponse response, int seconds) {
response.setProperty(MimeResponse.EXPIRATION_CACHE, Integer.toString(seconds));
}
/**
@@ -149,7 +147,7 @@ public abstract class PortletContentGenerator extends PortletApplicationObjectSu
* @param seconds positive number of seconds into the future that the
* response should be cacheable for, 0 to prevent caching
*/
protected final void applyCacheSeconds(RenderResponse response, int seconds) {
protected final void applyCacheSeconds(MimeResponse response, int seconds) {
if (seconds > 0) {
cacheForSeconds(response, seconds);
}

View File

@@ -0,0 +1,82 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import javax.portlet.PortletException;
import org.springframework.util.StringUtils;
/**
* Exception thrown when a request handler does not support a
* specific request method.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class PortletRequestMethodNotSupportedException extends PortletException {
private String method;
private String[] supportedMethods;
/**
* Create a new PortletRequestMethodNotSupportedException.
* @param method the unsupported HTTP request method
*/
public PortletRequestMethodNotSupportedException(String method) {
this(method, null);
}
/**
* Create a new PortletRequestMethodNotSupportedException.
* @param method the unsupported HTTP request method
* @param supportedMethods the actually supported HTTP methods
*/
public PortletRequestMethodNotSupportedException(String method, String[] supportedMethods) {
super("Request method '" + method + "' not supported by mapped handler");
this.method = method;
this.supportedMethods = supportedMethods;
}
/**
* Create a new PortletRequestMethodNotSupportedException.
* @param method the unsupported HTTP request method
* @param supportedMethods the actually supported HTTP methods
*/
public PortletRequestMethodNotSupportedException(String[] supportedMethods) {
super("Mapped handler only supports client data requests with methods " +
StringUtils.arrayToCommaDelimitedString(supportedMethods));
this.supportedMethods = supportedMethods;
}
/**
* Return the HTTP request method that caused the failure.
*/
public String getMethod() {
return this.method;
}
/**
* Return the actually supported HTTP methods, if known.
*/
public String[] getSupportedMethods() {
return this.supportedMethods;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,9 +19,12 @@ package org.springframework.web.portlet.handler;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Set;
import javax.portlet.MimeResponse;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.WindowState;
import org.apache.commons.logging.Log;
@@ -190,6 +193,18 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
}
}
public ModelAndView resolveException(
ResourceRequest request, ResourceResponse response, Object handler, Exception ex) {
if (shouldApplyTo(request, handler)) {
return doResolveException(request, response, handler, ex);
}
else {
return null;
}
}
/**
* Check whether this resolver is supposed to apply to the given handler.
* <p>The default implementation checks against the specified mapped handlers
@@ -203,19 +218,19 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
* @see #setMappedHandlers
* @see #setMappedHandlerClasses
*/
protected boolean shouldApplyTo(RenderRequest request, Object handler) {
protected boolean shouldApplyTo(PortletRequest request, Object handler) {
// If the portlet is minimized and we don't want to render then return null.
if (WindowState.MINIMIZED.equals(request.getWindowState()) && !this.renderWhenMinimized) {
return false;
}
// Check mapped handlers...
if (handler != null) {
if (this.mappedHandlers != null && this.mappedHandlers.contains(handler)) {
return true;
}
if (this.mappedHandlerClasses != null) {
for (int i = 0; i < this.mappedHandlerClasses.length; i++) {
if (this.mappedHandlerClasses[i].isInstance(handler)) {
for (Class mappedClass : this.mappedHandlerClasses) {
if (mappedClass.isInstance(handler)) {
return true;
}
}
@@ -236,7 +251,7 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
* @return a corresponding ModelAndView to forward to, or null for default processing
*/
protected ModelAndView doResolveException(
RenderRequest request, RenderResponse response, Object handler, Exception ex) {
PortletRequest request, MimeResponse response, Object handler, Exception ex) {
// Log exception, both at debug log level and at warn level, if desired.
if (logger.isDebugEnabled()) {
@@ -266,7 +281,7 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
* @see #buildLogMessage
* @see org.apache.commons.logging.Log#warn(Object, Throwable)
*/
protected void logException(Exception ex, RenderRequest request) {
protected void logException(Exception ex, PortletRequest request) {
if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) {
this.warnLogger.warn(buildLogMessage(ex, request), ex);
}
@@ -279,7 +294,7 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
* @param request current portlet request (useful for obtaining metadata)
* @return the log message to use
*/
protected String buildLogMessage(Exception ex, RenderRequest request) {
protected String buildLogMessage(Exception ex, PortletRequest request) {
return "Handler execution resulted in exception";
}
@@ -292,7 +307,7 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
* @param request current portlet request (useful for obtaining metadata)
* @return the resolved view name, or <code>null</code> if none found
*/
protected String determineViewName(Exception ex, RenderRequest request) {
protected String determineViewName(Exception ex, PortletRequest request) {
String viewName = null;
// Check for specific exception mappings.
if (this.exceptionMappings != null) {
@@ -348,7 +363,7 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
}
private int getDepth(String exceptionMapping, Class exceptionClass, int depth) {
if (exceptionClass.getName().indexOf(exceptionMapping) != -1) {
if (exceptionClass.getName().contains(exceptionMapping)) {
// Found it!
return depth;
}
@@ -369,7 +384,7 @@ public class SimpleMappingExceptionResolver implements HandlerExceptionResolver,
* @return the ModelAndView instance
* @see #getModelAndView(String, Exception)
*/
protected ModelAndView getModelAndView(String viewName, Exception ex, RenderRequest request) {
protected ModelAndView getModelAndView(String viewName, Exception ex, PortletRequest request) {
return getModelAndView(viewName, ex);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,21 @@ package org.springframework.web.portlet.handler;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventPortlet;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ResourceServingPortlet;
import org.springframework.web.portlet.HandlerAdapter;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.context.PortletContextAware;
/**
* Adapter to use the Portlet interface with the generic DispatcherPortlet.
@@ -49,8 +58,16 @@ import org.springframework.web.portlet.ModelAndView;
* @see SimplePortletPostProcessor
* @see org.springframework.web.portlet.mvc.PortletWrappingController
*/
public class SimplePortletHandlerAdapter implements HandlerAdapter {
public class SimplePortletHandlerAdapter implements HandlerAdapter, PortletContextAware {
private PortletContext portletContext;
public void setPortletContext(PortletContext portletContext) {
this.portletContext = portletContext;
}
public boolean supports(Object handler) {
return (handler instanceof Portlet);
}
@@ -68,4 +85,32 @@ public class SimplePortletHandlerAdapter implements HandlerAdapter {
return null;
}
public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception {
if (handler instanceof ResourceServingPortlet) {
((ResourceServingPortlet) handler).serveResource(request, response);
}
else {
// equivalent to Portlet 2.0 GenericPortlet
if (request.getResourceID() != null) {
PortletRequestDispatcher rd = this.portletContext.getRequestDispatcher(request.getResourceID());
if (rd != null) {
rd.forward(request, response);
}
}
}
return null;
}
public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception {
if (handler instanceof EventPortlet) {
((EventPortlet) handler).processEvent(request, response);
}
else {
// if no event processing method was found just keep render params
response.setRenderParameters(request);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,13 +18,16 @@ package org.springframework.web.portlet.handler;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
@@ -144,23 +147,47 @@ public class SimplePortletPostProcessor
}
public String getPortletName() {
return portletName;
return this.portletName;
}
public PortletContext getPortletContext() {
return portletContext;
return this.portletContext;
}
public String getInitParameter(String paramName) {
return null;
}
public Enumeration getInitParameterNames() {
return Collections.enumeration(Collections.EMPTY_SET);
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(new HashSet<String>());
}
public ResourceBundle getResourceBundle(Locale locale) {
return portletConfig == null ? null : portletConfig.getResourceBundle(locale);
return (this.portletConfig != null ? this.portletConfig.getResourceBundle(locale) : null);
}
public Enumeration<String> getPublicRenderParameterNames() {
return Collections.enumeration(new HashSet<String>());
}
public String getDefaultNamespace() {
return XMLConstants.NULL_NS_URI;
}
public Enumeration<QName> getPublishingEventQNames() {
return Collections.enumeration(new HashSet<QName>());
}
public Enumeration<QName> getProcessingEventQNames() {
return Collections.enumeration(new HashSet<QName>());
}
public Enumeration<Locale> getSupportedLocales() {
return Collections.enumeration(new HashSet<Locale>());
}
public Map<String, String[]> getContainerRuntimeOptions() {
return (this.portletConfig != null ? this.portletConfig.getContainerRuntimeOptions() : null);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,8 +51,8 @@ public class UserRoleAuthorizationInterceptor extends HandlerInterceptorAdapter
throws PortletException, IOException {
if (this.authorizedRoles != null) {
for (int i = 0; i < this.authorizedRoles.length; i++) {
if (request.isUserInRole(this.authorizedRoles[i])) {
for (String role : this.authorizedRoles) {
if (request.isUserInRole(role)) {
return true;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,12 @@ package org.springframework.web.portlet.handler;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.util.Assert;
import org.springframework.web.context.request.WebRequestInterceptor;
@@ -105,4 +109,35 @@ public class WebRequestHandlerInterceptorAdapter implements HandlerInterceptor {
this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex);
}
public boolean preHandleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception {
this.requestInterceptor.preHandle(new PortletWebRequest(request));
return true;
}
public void postHandleResource(ResourceRequest request, ResourceResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
this.requestInterceptor.postHandle(new PortletWebRequest(request),
(modelAndView != null ? modelAndView.getModelMap() : null));
}
public void afterResourceCompletion(ResourceRequest request, ResourceResponse response, Object handler,
Exception ex) throws Exception {
this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex);
}
public boolean preHandleEvent(EventRequest request, EventResponse response, Object handler) throws Exception {
this.requestInterceptor.preHandle(new PortletWebRequest(request));
return true;
}
public void afterEventCompletion(EventRequest request, EventResponse response, Object handler, Exception ex)
throws Exception {
this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex);
}
}

View File

@@ -24,9 +24,9 @@ import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.portlet.ActionRequest;
import javax.portlet.filter.ActionRequestWrapper;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.portlet.util.ActionRequestWrapper;
/**
* Default implementation of the {@link MultipartActionRequest} interface.

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -122,6 +122,8 @@ import org.springframework.web.portlet.util.PortletUtils;
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
* @see ResourceAwareController
* @see EventAwareController
*/
public abstract class AbstractController extends PortletContentGenerator implements Controller {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,15 +45,7 @@ import org.springframework.web.portlet.ModelAndView;
* request and - if applicable - returning an appropriate ModelAndView.
* So actually, these method are the main entrypoint for the
* {@link org.springframework.web.portlet.DispatcherPortlet DispatcherPortlet}
* which delegates requests to controllers. These method - and also this interface -
* should preferrably not be implemented by custom controllers <i>directly</i>, since
* abstract controllers also provided by this package already provide a lot of
* functionality for typical use cases in portlet applications. A few examples of
* those controllers:
* {@link AbstractController AbstractController},
* {@link AbstractCommandController AbstractCommandController},
* {@link AbstractFormController AbstractFormController},
* {@link SimpleFormController SimpleFormController}.</p>
* which delegates requests to controllers.</p>
*
* <p>So basically any <i>direct</i> implementation of the Controller interface
* just handles RenderRequests/ActionRequests and should return a ModelAndView, to be
@@ -64,19 +56,16 @@ import org.springframework.web.portlet.ModelAndView;
* @author William G. Thompson, Jr.
* @author John A. Lewis
* @since 2.0
* @see ResourceAwareController
* @see EventAwareController
* @see SimpleControllerHandlerAdapter
* @see AbstractController
* @see AbstractCommandController
* @see AbstractFormController
* @see SimpleFormController
* @see org.springframework.context.ApplicationContextAware
* @see org.springframework.context.ResourceLoaderAware
* @see org.springframework.web.portlet.context.PortletContextAware
*/
public interface Controller {
/**
* Process the action request. There is nothing to return.
* Process the action request. There is nothing to return.
* @param request current portlet action request
* @param response current portlet action response
* @throws Exception in case of errors

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.mvc;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
/**
* Extension of the Portlet {@link Controller} interface that allows
* for handling Portlet 2.0 event requests as well. Can also be
* implemented by {@link AbstractController} subclasses.
*
* @author Juergen Hoeller
* @since 3.0
* @see javax.portlet.EventPortlet
* @see Controller
* @see ResourceAwareController
*/
public interface EventAwareController {
/**
* Process the event request. There is nothing to return.
* @param request current portlet event request
* @param response current portlet event response
* @throws Exception in case of errors
*/
void handleEventRequest(EventRequest request, EventResponse response) throws Exception;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,13 @@
package org.springframework.web.portlet.mvc;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Properties;
import java.util.Map;
import java.util.ResourceBundle;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
@@ -28,6 +30,8 @@ import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
@@ -79,7 +83,7 @@ public class PortletWrappingController extends AbstractController
private String portletName;
private Properties initParameters = new Properties();
private Map<String, String> initParameters = new LinkedHashMap<String, String>();
private String beanName;
@@ -128,7 +132,7 @@ public class PortletWrappingController extends AbstractController
* Specify init parameters for the portlet to wrap,
* as name-value pairs.
*/
public void setInitParameters(Properties initParameters) {
public void setInitParameters(Map<String, String> initParameters) {
this.initParameters = initParameters;
}
@@ -195,17 +199,40 @@ public class PortletWrappingController extends AbstractController
}
public String getInitParameter(String paramName) {
return initParameters.getProperty(paramName);
return initParameters.get(paramName);
}
public Enumeration getInitParameterNames() {
return initParameters.keys();
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(initParameters.keySet());
}
public ResourceBundle getResourceBundle(Locale locale) {
return (portletConfig != null ? portletConfig.getResourceBundle(locale) : null);
}
public Enumeration<String> getPublicRenderParameterNames() {
return Collections.enumeration(new HashSet<String>());
}
public String getDefaultNamespace() {
return XMLConstants.NULL_NS_URI;
}
public Enumeration<QName> getPublishingEventQNames() {
return Collections.enumeration(new HashSet<QName>());
}
public Enumeration<QName> getProcessingEventQNames() {
return Collections.enumeration(new HashSet<QName>());
}
public Enumeration<Locale> getSupportedLocales() {
return Collections.enumeration(new HashSet<Locale>());
}
public Map<String, String[]> getContainerRuntimeOptions() {
return (portletConfig != null ? portletConfig.getContainerRuntimeOptions() : null);
}
}
}

View File

@@ -0,0 +1,48 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.mvc;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* Extension of the Portlet {@link Controller} interface that allows
* for handling Portlet 2.0 resource requests as well. Can also be
* implemented by {@link AbstractController} subclasses.
*
* @author Juergen Hoeller
* @since 3.0
* @see javax.portlet.ResourceServingPortlet
* @see Controller
* @see EventAwareController
*/
public interface ResourceAwareController {
/**
* Process the resource request and return a ModelAndView object which the DispatcherPortlet
* will render. A <code>null</code> return value is not an error: It indicates that this
* object completed request processing itself, thus there is no ModelAndView to render.
* @param request current portlet resource request
* @param response current portlet resource response
* @return a ModelAndView to render, or null if handled directly
* @throws Exception in case of errors
*/
ModelAndView handleResourceRequest(ResourceRequest request, ResourceResponse response) throws Exception;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,24 +18,42 @@ package org.springframework.web.portlet.mvc;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.web.portlet.HandlerAdapter;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.context.PortletContextAware;
/**
* Adapter to use the Controller workflow interface with the generic DispatcherPortlet.
*
* <p>This is an SPI class, not used directly by application code.
*
* @author Juergen Hoeller
* @author John A. Lewis
* @since 2.0
* @see org.springframework.web.portlet.DispatcherPortlet
* @see Controller
*/
public class SimpleControllerHandlerAdapter implements HandlerAdapter {
* @see ResourceAwareController
* @see EventAwareController
*/
public class SimpleControllerHandlerAdapter implements HandlerAdapter, PortletContextAware {
private PortletContext portletContext;
public void setPortletContext(PortletContext portletContext) {
this.portletContext = portletContext;
}
public boolean supports(Object handler) {
return (handler instanceof Controller);
}
@@ -52,4 +70,32 @@ public class SimpleControllerHandlerAdapter implements HandlerAdapter {
return ((Controller) handler).handleRenderRequest(request, response);
}
public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception {
if (handler instanceof ResourceAwareController) {
return ((ResourceAwareController) handler).handleResourceRequest(request, response);
}
else {
// equivalent to Portlet 2.0 GenericPortlet
if (request.getResourceID() != null) {
PortletRequestDispatcher rd = this.portletContext.getRequestDispatcher(request.getResourceID());
if (rd != null) {
rd.forward(request, response);
}
}
return null;
}
}
public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception {
if (handler instanceof EventAwareController) {
((EventAwareController) handler).handleEventRequest(request, response);
}
else {
// if no event processing method was found just keep render params
response.setRenderParameters(request);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,13 +23,20 @@ import java.io.Writer;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.ClientDataRequest;
import javax.portlet.Event;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortalContext;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
@@ -39,6 +46,8 @@ import javax.portlet.PortletResponse;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.UnavailableException;
import javax.portlet.WindowState;
@@ -54,11 +63,14 @@ import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.support.BindingAwareModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.annotation.support.HandlerMethodInvoker;
@@ -72,6 +84,10 @@ import org.springframework.web.portlet.HandlerAdapter;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.MissingPortletRequestParameterException;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.EventMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;
import org.springframework.web.portlet.context.PortletWebRequest;
import org.springframework.web.portlet.handler.PortletContentGenerator;
import org.springframework.web.portlet.handler.PortletSessionRequiredException;
@@ -218,14 +234,25 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
return doHandle(request, response, handler);
}
public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler) throws Exception {
checkAndPrepare(request, response);
return doHandle(request, response, handler);
}
public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception {
Object returnValue = doHandle(request, response, handler);
if (returnValue != null) {
throw new IllegalStateException("Invalid action method return value: " + returnValue);
}
}
protected ModelAndView doHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception {
ExtendedModelMap implicitModel = null;
if (request instanceof RenderRequest && response instanceof RenderResponse) {
RenderRequest renderRequest = (RenderRequest) request;
RenderResponse renderResponse = (RenderResponse) response;
if (response instanceof MimeResponse) {
MimeResponse mimeResponse = (MimeResponse) response;
// Detect implicit model from associated action phase.
if (renderRequest.getParameter(IMPLICIT_MODEL_ATTRIBUTE) != null) {
if (request.getParameter(IMPLICIT_MODEL_ATTRIBUTE) != null) {
PortletSession session = request.getPortletSession(false);
if (session != null) {
implicitModel = (ExtendedModelMap) session.getAttribute(IMPLICIT_MODEL_ATTRIBUTE);
@@ -233,11 +260,11 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
}
if (handler.getClass().getAnnotation(SessionAttributes.class) != null) {
// Always prevent caching in case of session attribute management.
checkAndPrepare(renderRequest, renderResponse, this.cacheSecondsForSessionAttributeHandlers);
checkAndPrepare(request, mimeResponse, this.cacheSecondsForSessionAttributeHandlers);
}
else {
// Uses configured default cacheSeconds setting.
checkAndPrepare(renderRequest, renderResponse);
checkAndPrepare(request, mimeResponse);
}
}
@@ -265,7 +292,7 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
PortletWebRequest webRequest = new PortletWebRequest(request, response);
PortletHandlerMethodResolver methodResolver = getMethodResolver(handler);
Method handlerMethod = methodResolver.resolveHandlerMethod(request, response);
Method handlerMethod = methodResolver.resolveHandlerMethod(request);
PortletHandlerMethodInvoker methodInvoker = new PortletHandlerMethodInvoker(methodResolver);
Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel);
@@ -324,42 +351,51 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
private static class PortletHandlerMethodResolver extends HandlerMethodResolver {
private final Map<Method, RequestMappingInfo> mappings = new HashMap<Method, RequestMappingInfo>();
public PortletHandlerMethodResolver(Class<?> handlerType) {
super(handlerType);
init(handlerType);
}
public Method resolveHandlerMethod(PortletRequest request, PortletResponse response) throws PortletException {
String lookupMode = request.getPortletMode().toString();
@Override
protected boolean isHandlerMethod(Method method) {
RequestMappingInfo mappingInfo = new RequestMappingInfo();
RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class);
ActionMapping actionMapping = AnnotationUtils.findAnnotation(method, ActionMapping.class);
RenderMapping renderMapping = AnnotationUtils.findAnnotation(method, RenderMapping.class);
ResourceMapping resourceMapping = AnnotationUtils.findAnnotation(method, ResourceMapping.class);
EventMapping eventMapping = AnnotationUtils.findAnnotation(method, EventMapping.class);
if (actionMapping != null) {
mappingInfo.initPhaseMapping(PortletRequest.ACTION_PHASE, actionMapping.value(), actionMapping.params());
}
if (renderMapping != null) {
mappingInfo.initPhaseMapping(PortletRequest.RENDER_PHASE, renderMapping.value(), renderMapping.params());
}
if (resourceMapping != null) {
mappingInfo.initPhaseMapping(PortletRequest.RESOURCE_PHASE, resourceMapping.value(), resourceMapping.params());
}
if (eventMapping != null) {
mappingInfo.initPhaseMapping(PortletRequest.EVENT_PHASE, eventMapping.value(), eventMapping.params());
}
if (requestMapping != null) {
mappingInfo.initStandardMapping(requestMapping.value(), requestMapping.method(), requestMapping.params());
if (mappingInfo.phase == null) {
mappingInfo.phase = determineDefaultPhase(method);
}
}
this.mappings.put(method, mappingInfo);
return (mappingInfo.phase != null);
}
public Method resolveHandlerMethod(PortletRequest request) throws PortletException {
Map<RequestMappingInfo, Method> targetHandlerMethods = new LinkedHashMap<RequestMappingInfo, Method>();
for (Method handlerMethod : getHandlerMethods()) {
RequestMapping mapping = AnnotationUtils.findAnnotation(handlerMethod, RequestMapping.class);
RequestMappingInfo mappingInfo = new RequestMappingInfo();
mappingInfo.modes = mapping.value();
mappingInfo.params = mapping.params();
mappingInfo.action = isActionMethod(handlerMethod);
mappingInfo.render = isRenderMethod(handlerMethod);
boolean match = false;
if (mappingInfo.modes.length > 0) {
for (String mappedMode : mappingInfo.modes) {
if (mappedMode.equalsIgnoreCase(lookupMode)) {
if (checkParameters(request, response, mappingInfo)) {
match = true;
}
else {
break;
}
}
}
}
else {
// No modes specified: parameter match sufficient.
match = checkParameters(request, response, mappingInfo);
}
if (match) {
RequestMappingInfo mappingInfo = this.mappings.get(handlerMethod);
if (mappingInfo.match(request)) {
Method oldMappedMethod = targetHandlerMethods.put(mappingInfo, handlerMethod);
if (oldMappedMethod != null && oldMappedMethod != handlerMethod) {
throw new IllegalStateException("Ambiguous handler methods mapped for portlet mode '" +
lookupMode + "': {" + oldMappedMethod + ", " + handlerMethod +
request.getPortletMode() + "': {" + oldMappedMethod + ", " + handlerMethod +
"}. If you intend to handle the same mode in multiple methods, then factor " +
"them out into a dedicated handler class with that mode mapped at the type level!");
}
@@ -376,8 +412,7 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
bestMappingMatch = mapping;
}
else {
if ((bestMappingMatch.modes.length == 0 && mapping.modes.length > 0) ||
bestMappingMatch.params.length < mapping.params.length) {
if (mapping.isBetterMatchThan(bestMappingMatch)) {
bestMappingMatch = mapping;
}
}
@@ -386,50 +421,123 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
}
}
else {
throw new UnavailableException("No matching handler method found for portlet request: mode '" +
request.getPortletMode() + "', type '" + (response instanceof ActionResponse ? "action" : "render") +
throw new UnavailableException(
"No matching handler method found for portlet request: mode '" + request.getPortletMode() +
"', phase '" + request.getAttribute(PortletRequest.LIFECYCLE_PHASE) +
"', parameters " + StylerUtils.style(request.getParameterMap()));
}
}
private boolean checkParameters(PortletRequest request, PortletResponse response, RequestMappingInfo mapping) {
if (response instanceof RenderResponse) {
if (mapping.action) {
return false;
}
}
else if (response instanceof ActionResponse) {
if (mapping.render) {
return false;
}
}
return PortletAnnotationMappingUtils.checkParameters(mapping.params, request);
}
private boolean isActionMethod(Method handlerMethod) {
private String determineDefaultPhase(Method handlerMethod) {
if (!void.class.equals(handlerMethod.getReturnType())) {
return false;
return PortletRequest.RENDER_PHASE;
}
for (Class<?> argType : handlerMethod.getParameterTypes()) {
if (ActionRequest.class.isAssignableFrom(argType) || ActionResponse.class.isAssignableFrom(argType) ||
InputStream.class.isAssignableFrom(argType) || Reader.class.isAssignableFrom(argType)) {
return true;
return PortletRequest.ACTION_PHASE;
}
else if (RenderRequest.class.isAssignableFrom(argType) || RenderResponse.class.isAssignableFrom(argType) ||
OutputStream.class.isAssignableFrom(argType) || Writer.class.isAssignableFrom(argType)) {
return PortletRequest.RENDER_PHASE;
}
else if (ResourceRequest.class.isAssignableFrom(argType) || ResourceResponse.class.isAssignableFrom(argType)) {
return PortletRequest.RESOURCE_PHASE;
}
else if (EventRequest.class.isAssignableFrom(argType) || EventResponse.class.isAssignableFrom(argType)) {
return PortletRequest.EVENT_PHASE;
}
}
return false;
return "";
}
}
private static class RequestMappingInfo {
public Set<PortletMode> modes = new HashSet<PortletMode>();
public String phase;
public String value;
public Set<String> methods = new HashSet<String>();
public String[] params = new String[0];
public void initStandardMapping(String[] modes, RequestMethod[] methods, String[] params) {
for (String mode : modes) {
this.modes.add(new PortletMode(mode));
}
for (RequestMethod method : methods) {
this.methods.add(method.name());
}
this.params = StringUtils.mergeStringArrays(this.params, params);
}
private boolean isRenderMethod(Method handlerMethod) {
if (!void.class.equals(handlerMethod.getReturnType())) {
return true;
public void initPhaseMapping(String phase, String value, String[] params) {
if (this.phase != null) {
throw new IllegalStateException(
"Invalid mapping - more than one phase specified: '" + this.phase + "', '" + phase + "'");
}
for (Class<?> argType : handlerMethod.getParameterTypes()) {
if (RenderRequest.class.isAssignableFrom(argType) || RenderResponse.class.isAssignableFrom(argType) ||
OutputStream.class.isAssignableFrom(argType) || Writer.class.isAssignableFrom(argType)) {
return true;
this.phase = phase;
this.value = value;
this.params = StringUtils.mergeStringArrays(this.params, params);
}
public boolean match(PortletRequest request) {
if (!this.modes.isEmpty() && !this.modes.contains(request.getPortletMode())) {
return false;
}
if (StringUtils.hasLength(this.phase) &&
!this.phase.equals(request.getAttribute(PortletRequest.LIFECYCLE_PHASE))) {
return false;
}
if (StringUtils.hasLength(this.value)) {
if (this.phase.equals(PortletRequest.ACTION_PHASE) &&
!this.value.equals(request.getParameter(ActionRequest.ACTION_NAME))) {
return false;
}
else if (this.phase.equals(PortletRequest.RENDER_PHASE) &&
!(new WindowState(this.value)).equals(request.getWindowState())) {
return false;
}
else if (this.phase.equals(PortletRequest.RESOURCE_PHASE) &&
!this.value.equals(((ResourceRequest) request).getResourceID())) {
return false;
}
else if (this.phase.equals(PortletRequest.EVENT_PHASE)) {
Event event = ((EventRequest) request).getEvent();
if (!this.value.equals(event.getName()) && !this.value.equals(event.getQName().toString())) {
return false;
}
}
}
return false;
return PortletAnnotationMappingUtils.checkRequestMethod(this.methods, request) &&
PortletAnnotationMappingUtils.checkParameters(this.params, request);
}
public boolean isBetterMatchThan(RequestMappingInfo other) {
return ((!this.modes.isEmpty() && other.modes.isEmpty()) ||
(StringUtils.hasLength(this.phase) && !StringUtils.hasLength(other.phase)) ||
(StringUtils.hasLength(this.value) && !StringUtils.hasLength(other.value)) ||
(!this.methods.isEmpty() && other.methods.isEmpty()) ||
this.params.length > other.params.length);
}
@Override
public boolean equals(Object obj) {
RequestMappingInfo other = (RequestMappingInfo) obj;
return (this.modes.equals(other.modes) &&
ObjectUtils.nullSafeEquals(this.phase, other.phase) &&
ObjectUtils.nullSafeEquals(this.value, other.value) &&
this.methods.equals(other.methods) &&
Arrays.equals(this.params, other.params));
}
@Override
public int hashCode() {
return (ObjectUtils.nullSafeHashCode(this.modes) * 29 + this.phase.hashCode());
}
}
@@ -505,28 +613,34 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
return request.getLocale();
}
else if (InputStream.class.isAssignableFrom(parameterType)) {
if (!(request instanceof ActionRequest)) {
throw new IllegalStateException("InputStream can only get obtained for ActionRequest");
if (!(request instanceof ClientDataRequest)) {
throw new IllegalStateException("InputStream can only get obtained for Action/ResourceRequest");
}
return ((ActionRequest) request).getPortletInputStream();
return ((ClientDataRequest) request).getPortletInputStream();
}
else if (Reader.class.isAssignableFrom(parameterType)) {
if (!(request instanceof ActionRequest)) {
throw new IllegalStateException("Reader can only get obtained for ActionRequest");
if (!(request instanceof ClientDataRequest)) {
throw new IllegalStateException("Reader can only get obtained for Action/ResourceRequest");
}
return ((ActionRequest) request).getReader();
return ((ClientDataRequest) request).getReader();
}
else if (OutputStream.class.isAssignableFrom(parameterType)) {
if (!(response instanceof RenderResponse)) {
throw new IllegalStateException("OutputStream can only get obtained for RenderResponse");
if (!(response instanceof MimeResponse)) {
throw new IllegalStateException("OutputStream can only get obtained for Render/ResourceResponse");
}
return ((RenderResponse) response).getPortletOutputStream();
return ((MimeResponse) response).getPortletOutputStream();
}
else if (Writer.class.isAssignableFrom(parameterType)) {
if (!(response instanceof RenderResponse)) {
throw new IllegalStateException("Writer can only get obtained for RenderResponse");
if (!(response instanceof MimeResponse)) {
throw new IllegalStateException("Writer can only get obtained for Render/ResourceResponse");
}
return ((RenderResponse) response).getWriter();
return ((MimeResponse) response).getWriter();
}
else if (Event.class.equals(parameterType)) {
if (!(request instanceof EventRequest)) {
throw new IllegalStateException("Event can only get obtained from EventRequest");
}
return ((EventRequest) request).getEvent();
}
return super.resolveStandardArgument(parameterType, webRequest);
}
@@ -581,28 +695,4 @@ public class AnnotationMethodHandlerAdapter extends PortletContentGenerator impl
}
}
private static class RequestMappingInfo {
public String[] modes = new String[0];
public String[] params = new String[0];
private boolean action = false;
private boolean render = false;
@Override
public boolean equals(Object obj) {
RequestMappingInfo other = (RequestMappingInfo) obj;
return (this.action == other.action && this.render == other.render &&
Arrays.equals(this.modes, other.modes) && Arrays.equals(this.params, other.params));
}
@Override
public int hashCode() {
return (Arrays.hashCode(this.modes) * 29 + Arrays.hashCode(this.params));
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,12 @@
package org.springframework.web.portlet.mvc.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
@@ -28,8 +31,11 @@ import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.handler.AbstractMapBasedHandlerMapping;
import org.springframework.web.portlet.handler.PortletRequestMethodNotSupportedException;
/**
* Implementation of the {@link org.springframework.web.portlet.HandlerMapping}
@@ -99,12 +105,13 @@ public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapp
if (mapping != null) {
String[] modeKeys = mapping.value();
String[] params = mapping.params();
RequestMethod[] methods = mapping.method();
boolean registerHandlerType = true;
if (modeKeys.length == 0 || params.length == 0) {
registerHandlerType = !detectHandlerMethods(handlerType, beanName, mapping);
}
if (registerHandlerType) {
ParameterMappingPredicate predicate = new ParameterMappingPredicate(params);
ParameterMappingPredicate predicate = new ParameterMappingPredicate(params, methods);
for (String modeKey : modeKeys) {
registerHandler(new PortletMode(modeKey), beanName, predicate);
}
@@ -128,9 +135,20 @@ public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapp
final Set<Boolean> handlersRegistered = new HashSet<Boolean>(1);
ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() {
public void doWith(Method method) {
RequestMapping mapping = method.getAnnotation(RequestMapping.class);
if (mapping != null) {
String[] modeKeys = mapping.value();
boolean mappingFound = false;
String[] modeKeys = new String[0];
String[] params = new String[0];
for (Annotation ann : method.getAnnotations()) {
if (AnnotationUtils.findAnnotation(ann.getClass(), Mapping.class) != null) {
mappingFound = true;
if (ann instanceof RequestMapping) {
modeKeys = (String[]) AnnotationUtils.getValue(ann);
}
String[] specificParams = (String[]) AnnotationUtils.getValue(ann, "params");
params = StringUtils.mergeStringArrays(params, specificParams);
}
}
if (mappingFound) {
if (modeKeys.length == 0) {
if (typeMapping != null) {
modeKeys = typeMapping.value();
@@ -140,7 +158,6 @@ public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapp
"No portlet mode mappings specified - neither at type nor method level");
}
}
String[] params = mapping.params();
if (typeMapping != null) {
PortletAnnotationMappingUtils.validateModeMapping(modeKeys, typeMapping.value());
params = StringUtils.mergeStringArrays(typeMapping.params(), params);
@@ -172,14 +189,35 @@ public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapp
private final String[] params;
private ParameterMappingPredicate(String[] params) {
private final Set<String> methods = new HashSet<String>();
public ParameterMappingPredicate(String[] params) {
this.params = params;
}
public ParameterMappingPredicate(String[] params, RequestMethod[] methods) {
this.params = params;
for (RequestMethod method : methods) {
this.methods.add(method.name());
}
}
public boolean match(PortletRequest request) {
return PortletAnnotationMappingUtils.checkParameters(this.params, request);
}
public void validate(PortletRequest request) throws PortletException {
if (!this.methods.isEmpty()) {
if (!(request instanceof ClientDataRequest)) {
throw new PortletRequestMethodNotSupportedException(StringUtils.toStringArray(this.methods));
}
String method = ((ClientDataRequest) request).getMethod();
if (!this.methods.contains(method)) {
throw new PortletRequestMethodNotSupportedException(method, StringUtils.toStringArray(this.methods));
}
}
}
public int compareTo(Object other) {
if (other instanceof PortletRequestMappingPredicate) {
return new Integer(((ParameterMappingPredicate) other).params.length).compareTo(this.params.length);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.web.portlet.mvc.annotation;
import java.util.Set;
import javax.portlet.ClientDataRequest;
import javax.portlet.PortletRequest;
import org.springframework.util.ObjectUtils;
@@ -30,7 +32,7 @@ import org.springframework.web.portlet.util.PortletUtils;
abstract class PortletAnnotationMappingUtils {
/**
* Check whether the given request matches the specified request methods.
* Check whether the given portlet modes matches the specified type-level modes.
* @param modes the mapped portlet modes to check
* @param typeLevelModes the type-level mode mappings to check against
*/
@@ -51,11 +53,29 @@ abstract class PortletAnnotationMappingUtils {
return true;
}
/**
* Check whether the given request matches the specified request methods.
* @param methods the request methods to check against
* @param request the current request to check
*/
public static boolean checkRequestMethod(Set<String> methods, PortletRequest request) {
if (!methods.isEmpty()) {
if (!(request instanceof ClientDataRequest)) {
return false;
}
String method = ((ClientDataRequest) request).getMethod();
if (!methods.contains(method)) {
return false;
}
}
return true;
}
/**
* Check whether the given request matches the specified parameter conditions.
* @param params the parameter conditions, following
* {@link org.springframework.web.bind.annotation.RequestMapping#params()}
* @param request the current HTTP request to check
* @param request the current request to check
*/
public static boolean checkParameters(String[] params, PortletRequest request) {
if (!ObjectUtils.isEmpty(params)) {

View File

@@ -1,78 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import javax.portlet.ActionRequest;
/**
* Simple wrapper for a Portlet {@link javax.portlet.ActionRequest},
* delegating all calls to the underlying request.
*
* <p>(In the style of the Servlet API's {@link javax.servlet.http.HttpServletRequestWrapper}.)
*
* @author Juergen Hoeller
* @since 2.0
* @see ActionRequestWrapper
* @see javax.servlet.http.HttpServletRequestWrapper
*/
public class ActionRequestWrapper extends PortletRequestWrapper implements ActionRequest {
/** Original request that we're delegating to */
private final ActionRequest actionRequest;
/**
* Create a ActionRequestWrapper for the given request.
* @param request the original request to wrap
* @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
*/
public ActionRequestWrapper(ActionRequest request) {
super(request);
this.actionRequest = request;
}
public InputStream getPortletInputStream() throws IOException {
return this.actionRequest.getPortletInputStream();
}
public void setCharacterEncoding(String enc) throws UnsupportedEncodingException {
this.actionRequest.setCharacterEncoding(enc);
}
public BufferedReader getReader() throws IOException {
return this.actionRequest.getReader();
}
public String getCharacterEncoding() {
return this.actionRequest.getCharacterEncoding();
}
public String getContentType() {
return this.actionRequest.getContentType();
}
public int getContentLength() {
return this.actionRequest.getContentLength();
}
}

View File

@@ -1,197 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.util;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.security.Principal;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.WindowState;
import org.springframework.util.Assert;
/**
* Simple wrapper for a {@link javax.portlet.PortletRequest}, delegating all
* calls to the underlying request.
*
* <p>(In the style of the Servlet API's {@link javax.servlet.ServletRequestWrapper}.)
*
* @author Juergen Hoeller
* @since 2.0
* @see ActionRequestWrapper
* @see javax.servlet.ServletRequestWrapper
*/
public class PortletRequestWrapper implements PortletRequest {
/** Original request that we're delegating to */
private final PortletRequest portletRequest;
/**
* Create a PortletRequestWrapper for the given {@link javax.portlet.PortletRequest}.
* @param request the original {@link javax.portlet.PortletRequest} to wrap
* @throws IllegalArgumentException if the supplied <code>request</code> is <code>null</code>
*/
public PortletRequestWrapper(PortletRequest request) {
Assert.notNull(request, "Request is required");
this.portletRequest = request;
}
public boolean isWindowStateAllowed(WindowState state) {
return this.portletRequest.isWindowStateAllowed(state);
}
public boolean isPortletModeAllowed(PortletMode mode) {
return this.portletRequest.isPortletModeAllowed(mode);
}
public PortletMode getPortletMode() {
return this.portletRequest.getPortletMode();
}
public WindowState getWindowState() {
return this.portletRequest.getWindowState();
}
public PortletPreferences getPreferences() {
return this.portletRequest.getPreferences();
}
public PortletSession getPortletSession() {
return this.portletRequest.getPortletSession();
}
public PortletSession getPortletSession(boolean create) {
return this.portletRequest.getPortletSession(create);
}
public String getProperty(String name) {
return this.portletRequest.getProperty(name);
}
public Enumeration getProperties(String name) {
return this.portletRequest.getProperties(name);
}
public Enumeration getPropertyNames() {
return this.portletRequest.getPropertyNames();
}
public PortalContext getPortalContext() {
return this.portletRequest.getPortalContext();
}
public String getAuthType() {
return this.portletRequest.getAuthType();
}
public String getContextPath() {
return this.portletRequest.getContextPath();
}
public String getRemoteUser() {
return this.portletRequest.getRemoteUser();
}
public Principal getUserPrincipal() {
return this.portletRequest.getUserPrincipal();
}
public boolean isUserInRole(String role) {
return this.portletRequest.isUserInRole(role);
}
public Object getAttribute(String name) {
return this.portletRequest.getAttribute(name);
}
public Enumeration getAttributeNames() {
return this.portletRequest.getAttributeNames();
}
public String getParameter(String name) {
return this.portletRequest.getParameter(name);
}
public Enumeration getParameterNames() {
return this.portletRequest.getParameterNames();
}
public String[] getParameterValues(String name) {
return this.portletRequest.getParameterValues(name);
}
public Map getParameterMap() {
return this.portletRequest.getParameterMap();
}
public boolean isSecure() {
return this.portletRequest.isSecure();
}
public void setAttribute(String name, Object value) {
this.portletRequest.setAttribute(name, value);
}
public void removeAttribute(String name) {
this.portletRequest.removeAttribute(name);
}
public String getRequestedSessionId() {
return this.portletRequest.getRequestedSessionId();
}
public boolean isRequestedSessionIdValid() {
return this.portletRequest.isRequestedSessionIdValid();
}
public String getResponseContentType() {
return this.portletRequest.getResponseContentType();
}
public Enumeration getResponseContentTypes() {
return this.portletRequest.getResponseContentTypes();
}
public Locale getLocale() {
return this.portletRequest.getLocale();
}
public Enumeration getLocales() {
return this.portletRequest.getLocales();
}
public String getScheme() {
return this.portletRequest.getScheme();
}
public String getServerName() {
return this.portletRequest.getServerName();
}
public int getServerPort() {
return this.portletRequest.getServerPort();
}
}