From 2b3445df8134e2b0c4e4a4c4136cbaf9d58b7fc4 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 4 Jul 2016 23:33:45 +0200 Subject: [PATCH] Drop Portlet MVC support This commit also removes the corresponding deprecated Servlet MVC variant and updates DispatcherServlet.properties to point to RequestMappingHandlerMapping/Adapter by default. Issue: SPR-14129 --- ...ctRefreshableConfigApplicationContext.java | 5 +- .../java/org/springframework/ui/ModelMap.java | 8 +- .../validation/DataBinder.java | 5 +- .../core/io/ContextResource.java | 9 +- .../mock/web/portlet/MockActionRequest.java | 86 - .../mock/web/portlet/MockActionResponse.java | 129 - .../mock/web/portlet/MockBaseURL.java | 161 - .../mock/web/portlet/MockCacheControl.java | 78 - .../web/portlet/MockClientDataRequest.java | 135 - .../mock/web/portlet/MockEvent.java | 91 - .../mock/web/portlet/MockEventRequest.java | 90 - .../mock/web/portlet/MockEventResponse.java | 35 - .../mock/web/portlet/MockMimeResponse.java | 256 -- .../portlet/MockMultipartActionRequest.java | 101 - .../mock/web/portlet/MockPortalContext.java | 106 - .../mock/web/portlet/MockPortletConfig.java | 194 - .../mock/web/portlet/MockPortletContext.java | 298 -- .../web/portlet/MockPortletPreferences.java | 123 - .../mock/web/portlet/MockPortletRequest.java | 569 --- .../portlet/MockPortletRequestDispatcher.java | 87 - .../mock/web/portlet/MockPortletResponse.java | 202 - .../mock/web/portlet/MockPortletSession.java | 250 -- .../mock/web/portlet/MockPortletURL.java | 121 - .../mock/web/portlet/MockRenderRequest.java | 94 - .../mock/web/portlet/MockRenderResponse.java | 90 - .../mock/web/portlet/MockResourceRequest.java | 132 - .../web/portlet/MockResourceResponse.java | 41 - .../mock/web/portlet/MockResourceURL.java | 73 - .../web/portlet/MockStateAwareResponse.java | 165 - .../ServletWrappingPortletContext.java | 161 - .../mock/web/portlet/package-info.java | 10 - .../web/bind/annotation/CookieValue.java | 7 +- .../web/bind/annotation/ExceptionHandler.java | 44 +- .../web/bind/annotation/RequestHeader.java | 4 +- .../web/bind/annotation/RequestMapping.java | 74 +- .../web/bind/annotation/RequestParam.java | 5 +- .../HandlerMethodInvocationException.java | 44 - .../support/HandlerMethodInvoker.java | 901 ----- .../support/HandlerMethodResolver.java | 172 - .../bind/annotation/support/package-info.java | 4 - .../web/bind/support/WebArgumentResolver.java | 1 - .../web/context/WebApplicationContext.java | 8 +- .../request/FacesRequestAttributes.java | 87 +- .../web/context/request/FacesWebRequest.java | 7 +- .../web/context/request/NativeWebRequest.java | 10 +- .../context/request/RequestAttributes.java | 13 +- .../context/request/RequestContextHolder.java | 8 +- .../web/context/request/RequestScope.java | 8 +- .../web/context/request/SessionScope.java | 41 +- .../request/WebRequestInterceptor.java | 7 +- .../support/WebApplicationContextUtils.java | 3 +- .../web/multipart/MultipartRequest.java | 8 +- .../commons/CommonsFileUploadSupport.java | 8 +- .../commons/CommonsMultipartResolver.java | 1 - .../ServletRequestAttributesTests.java | 25 - .../web/portlet/DispatcherPortlet.java | 1381 ------- .../web/portlet/FrameworkPortlet.java | 712 ---- .../web/portlet/GenericPortletBean.java | 244 -- .../web/portlet/HandlerAdapter.java | 121 - .../web/portlet/HandlerExceptionResolver.java | 67 - .../web/portlet/HandlerExecutionChain.java | 123 - .../web/portlet/HandlerInterceptor.java | 301 -- .../web/portlet/HandlerMapping.java | 75 - .../web/portlet/ModelAndView.java | 305 -- .../ModelAndViewDefiningException.java | 58 - .../web/portlet/NoHandlerFoundException.java | 54 - ...ssingPortletRequestParameterException.java | 64 - .../bind/PortletRequestBindingException.java | 49 - .../bind/PortletRequestDataBinder.java | 124 - ...PortletRequestParameterPropertyValues.java | 82 - .../web/portlet/bind/PortletRequestUtils.java | 711 ---- .../bind/annotation/ActionMapping.java | 75 - .../portlet/bind/annotation/EventMapping.java | 52 - .../bind/annotation/RenderMapping.java | 74 - .../bind/annotation/ResourceMapping.java | 49 - .../portlet/bind/annotation/package-info.java | 4 - .../web/portlet/bind/package-info.java | 4 - ...tRefreshablePortletApplicationContext.java | 209 - ...ConfigurablePortletApplicationContext.java | 120 - .../PortletApplicationContextUtils.java | 316 -- .../PortletApplicationObjectSupport.java | 80 - .../portlet/context/PortletConfigAware.java | 44 - .../context/PortletConfigPropertySource.java | 48 - .../portlet/context/PortletContextAware.java | 45 - .../context/PortletContextAwareProcessor.java | 88 - .../context/PortletContextPropertySource.java | 48 - .../context/PortletContextResource.java | 220 -- .../context/PortletContextResourceLoader.java | 61 - ...PortletContextResourcePatternResolver.java | 119 - .../portlet/context/PortletContextScope.java | 117 - .../context/PortletRequestAttributes.java | 320 -- .../context/PortletRequestHandledEvent.java | 133 - .../portlet/context/PortletWebRequest.java | 199 - .../context/StandardPortletEnvironment.java | 108 - .../StaticPortletApplicationContext.java | 204 - .../context/XmlPortletApplicationContext.java | 145 - .../web/portlet/context/package-info.java | 5 - .../AbstractHandlerExceptionResolver.java | 224 -- .../handler/AbstractHandlerMapping.java | 262 -- .../AbstractMapBasedHandlerMapping.java | 204 - .../handler/HandlerInterceptorAdapter.java | 169 - .../handler/ParameterHandlerMapping.java | 104 - .../handler/ParameterMappingInterceptor.java | 77 - .../handler/PortletContentGenerator.java | 160 - .../handler/PortletModeHandlerMapping.java | 104 - .../PortletModeParameterHandlerMapping.java | 200 - .../PortletModeParameterLookupKey.java | 64 - ...letRequestMethodNotSupportedException.java | 82 - .../PortletSessionRequiredException.java | 39 - .../SimpleMappingExceptionResolver.java | 233 -- .../handler/SimplePortletHandlerAdapter.java | 117 - .../handler/SimplePortletPostProcessor.java | 216 -- .../UserRoleAuthorizationInterceptor.java | 80 - .../WebRequestHandlerInterceptorAdapter.java | 153 - .../web/portlet/handler/package-info.java | 5 - .../CommonsPortletMultipartResolver.java | 194 - .../DefaultMultipartActionRequest.java | 228 -- .../multipart/MultipartActionRequest.java | 41 - .../multipart/PortletMultipartResolver.java | 114 - .../web/portlet/multipart/package-info.java | 7 - .../web/portlet/mvc/AbstractController.java | 256 -- .../web/portlet/mvc/Controller.java | 86 - .../web/portlet/mvc/EventAwareController.java | 43 - .../mvc/ParameterizableViewController.java | 97 - .../mvc/PortletModeNameViewController.java | 53 - .../mvc/PortletWrappingController.java | 319 -- .../portlet/mvc/ResourceAwareController.java | 48 - .../mvc/SimpleControllerHandlerAdapter.java | 102 - .../AnnotationMethodHandlerAdapter.java | 846 ----- ...otationMethodHandlerExceptionResolver.java | 408 -- .../DefaultAnnotationHandlerMapping.java | 472 --- .../PortletAnnotationMappingUtils.java | 184 - .../portlet/mvc/annotation/package-info.java | 4 - .../web/portlet/mvc/package-info.java | 5 - .../web/portlet/package-info.java | 6 - .../web/portlet/util/PortletUtils.java | 539 --- .../web/portlet/util/package-info.java | 4 - .../src/main/java/overview.html | 7 - .../web/portlet/DispatcherPortlet.properties | 12 - .../springframework/context/ACATester.java | 49 - .../context/BeanThatBroadcasts.java | 37 - .../context/BeanThatListens.java | 62 - .../context/LifecycleContextBean.java | 40 - .../springframework/context/TestListener.java | 42 - .../mock/web/portlet/MockActionRequest.java | 86 - .../mock/web/portlet/MockActionResponse.java | 129 - .../mock/web/portlet/MockBaseURL.java | 161 - .../mock/web/portlet/MockCacheControl.java | 78 - .../web/portlet/MockClientDataRequest.java | 135 - .../mock/web/portlet/MockEvent.java | 91 - .../mock/web/portlet/MockEventRequest.java | 90 - .../mock/web/portlet/MockEventResponse.java | 35 - .../mock/web/portlet/MockMimeResponse.java | 259 -- .../portlet/MockMultipartActionRequest.java | 101 - .../mock/web/portlet/MockPortalContext.java | 106 - .../mock/web/portlet/MockPortletConfig.java | 194 - .../mock/web/portlet/MockPortletContext.java | 285 -- .../web/portlet/MockPortletPreferences.java | 123 - .../mock/web/portlet/MockPortletRequest.java | 565 --- .../portlet/MockPortletRequestDispatcher.java | 87 - .../mock/web/portlet/MockPortletResponse.java | 202 - .../mock/web/portlet/MockPortletSession.java | 249 -- .../mock/web/portlet/MockPortletURL.java | 121 - .../mock/web/portlet/MockRenderRequest.java | 94 - .../mock/web/portlet/MockRenderResponse.java | 90 - .../mock/web/portlet/MockResourceRequest.java | 132 - .../web/portlet/MockResourceResponse.java | 41 - .../mock/web/portlet/MockResourceURL.java | 73 - .../web/portlet/MockStateAwareResponse.java | 165 - .../ServletWrappingPortletContext.java | 161 - .../mock/web/portlet/package-info.java | 11 - .../ComplexPortletApplicationContext.java | 548 --- .../web/portlet/DispatcherPortletTests.java | 758 ---- .../web/portlet/GenericPortletBeanTests.java | 176 - .../bind/PortletRequestDataBinderTests.java | 227 -- ...etRequestParameterPropertyValuesTests.java | 69 - .../bind/PortletRequestUtilsTests.java | 458 --- ...AbstractXmlWebApplicationContextTests.java | 143 - .../PortletApplicationContextScopeTests.java | 129 - .../context/PortletConfigAwareBean.java | 36 - .../context/PortletContextAwareBean.java | 36 - .../PortletContextAwareProcessorTests.java | 152 - .../PortletRequestAttributesTests.java | 169 - .../context/PortletWebRequestTests.java | 113 - .../XmlPortletApplicationContextTests.java | 151 - .../handler/ParameterHandlerMappingTests.java | 98 - .../ParameterMappingInterceptorTests.java | 120 - .../PortletModeHandlerMappingTests.java | 86 - ...rtletModeParameterHandlerMappingTests.java | 105 - .../SimpleMappingExceptionResolverTests.java | 303 -- ...UserRoleAuthorizationInterceptorTests.java | 91 - .../ParameterizableViewControllerTests.java | 65 - .../PortletModeNameViewControllerTests.java | 71 - .../mvc/PortletWrappingControllerTests.java | 201 - ...onMethodHandlerExceptionResolverTests.java | 171 - .../Portlet20AnnotationControllerTests.java | 1316 ------- .../PortletAnnotationControllerTests.java | 874 ----- .../web/portlet/util/PortletUtilsTests.java | 503 --- .../src/test/resources/log4j.properties | 10 - .../context/WEB-INF/applicationContext.xml | 81 - .../WEB-INF/context-messages.properties | 6 - .../WEB-INF/context-messages_en_GB.properties | 2 - .../WEB-INF/context-messages_en_US.properties | 5 - .../context/WEB-INF/contextInclude.xml | 6 - .../portlet/context/WEB-INF/empty-portlet.xml | 12 - .../WEB-INF/more-context-messages.properties | 2 - .../context/WEB-INF/myoverride.properties | 3 - .../context/WEB-INF/myplaceholder.properties | 4 - .../WEB-INF/resources/messageSource.xml | 24 - .../context/WEB-INF/resources/themeSource.xml | 12 - .../portlet/context/WEB-INF/test-portlet.xml | 12 - .../portlet/context/WEB-INF/test-servlet.xml | 59 - .../web/portlet/handler/parameterMapping.xml | 19 - .../portlet/handler/portletModeMapping.xml | 22 - .../handler/portletModeParameterMapping.xml | 30 - .../web/servlet/ViewRendererServlet.java | 117 - .../AnnotationMethodHandlerAdapter.java | 1294 ------- ...otationMethodHandlerExceptionResolver.java | 452 --- .../DefaultAnnotationHandlerMapping.java | 275 -- .../ServletAnnotationMappingUtils.java | 161 - .../web/servlet/DispatcherServlet.properties | 6 +- .../HandlerMappingIntrospectorTests.java | 3 +- ...onMethodHandlerExceptionResolverTests.java | 244 -- ...estSpecificMappingInfoComparatorTests.java | 135 - .../ServletAnnotationControllerTests.java | 3356 ----------------- .../ServletAnnotationMappingUtilsTests.java | 189 - .../mvc/annotation/Spr7766Controller.java | 20 - .../servlet/mvc/annotation/Spr7766Tests.java | 55 - .../servlet/mvc/annotation/Spr7839Tests.java | 274 -- ...plateServletAnnotationControllerTests.java | 713 ---- ...nnotationControllerHandlerMethodTests.java | 3 - src/asciidoc/core-beans.adoc | 81 +- src/asciidoc/web-portlet.adoc | 1521 -------- src/asciidoc/web.adoc | 5 - .../EnvironmentSystemIntegrationTests.java | 44 +- 235 files changed, 94 insertions(+), 39747 deletions(-) delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockBaseURL.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockCacheControl.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockMimeResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceRequest.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceURL.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java delete mode 100644 spring-test/src/main/java/org/springframework/mock/web/portlet/package-info.java delete mode 100644 spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvocationException.java delete mode 100644 spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java delete mode 100644 spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodResolver.java delete mode 100644 spring-web/src/main/java/org/springframework/web/bind/annotation/support/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/GenericPortletBean.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerAdapter.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExceptionResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerInterceptor.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndViewDefiningException.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/NoHandlerFoundException.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/MissingPortletRequestParameterException.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestBindingException.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValues.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestUtils.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ActionMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/EventMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/RenderMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ResourceMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/ConfigurablePortletApplicationContext.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationObjectSupport.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigAware.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigPropertySource.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAware.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAwareProcessor.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextPropertySource.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResource.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourceLoader.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextScope.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StandardPortletEnvironment.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/XmlPortletApplicationContext.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerExceptionResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/HandlerInterceptorAdapter.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterMappingInterceptor.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletContentGenerator.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletRequestMethodNotSupportedException.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletSessionRequiredException.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletHandlerAdapter.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletPostProcessor.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptor.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/WebRequestHandlerInterceptorAdapter.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/MultipartActionRequest.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/PortletMultipartResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractController.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/Controller.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/EventAwareController.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ParameterizableViewController.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletModeNameViewController.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletWrappingController.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ResourceAwareController.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleControllerHandlerAdapter.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationMappingUtils.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java delete mode 100644 spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/package-info.java delete mode 100644 spring-webmvc-portlet/src/main/java/overview.html delete mode 100644 spring-webmvc-portlet/src/main/resources/org/springframework/web/portlet/DispatcherPortlet.properties delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/context/ACATester.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatBroadcasts.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockBaseURL.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockCacheControl.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockClientDataRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEvent.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMimeResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortalContext.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletConfig.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletContext.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletPreferences.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletURL.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceRequest.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceURL.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/package-info.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletConfigAwareBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java delete mode 100644 spring-webmvc-portlet/src/test/resources/log4j.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_GB.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_US.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/contextInclude.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/empty-portlet.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/more-context-messages.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myoverride.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myplaceholder.properties delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/messageSource.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/themeSource.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/parameterMapping.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeMapping.xml delete mode 100644 spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeParameterMapping.xml delete mode 100644 spring-webmvc/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java delete mode 100644 spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java delete mode 100644 spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java delete mode 100644 spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java delete mode 100644 spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtils.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/RequestSpecificMappingInfoComparatorTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtilsTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Controller.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Tests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java delete mode 100644 src/asciidoc/web-portlet.adoc diff --git a/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java b/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java index cd32b7278c..0775e5782d 100644 --- a/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java +++ b/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 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. @@ -27,8 +27,7 @@ import org.springframework.util.StringUtils; * of specified config locations. Serves as base class for XML-based application * context implementations such as {@link ClassPathXmlApplicationContext} and * {@link FileSystemXmlApplicationContext}, as well as - * {@link org.springframework.web.context.support.XmlWebApplicationContext} and - * {@link org.springframework.web.portlet.context.XmlPortletApplicationContext}. + * {@link org.springframework.web.context.support.XmlWebApplicationContext}. * * @author Juergen Hoeller * @since 2.5.2 diff --git a/spring-context/src/main/java/org/springframework/ui/ModelMap.java b/spring-context/src/main/java/org/springframework/ui/ModelMap.java index 5db8b7fb7b..dad6b113b6 100644 --- a/spring-context/src/main/java/org/springframework/ui/ModelMap.java +++ b/spring-context/src/main/java/org/springframework/ui/ModelMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2016 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. @@ -27,16 +27,14 @@ import org.springframework.util.Assert; * Implementation of {@link java.util.Map} for use when building model data for use * with UI tools. Supports chained calls and generation of model attribute names. * - *

This class serves as generic model holder for both Servlet and Portlet MVC, - * but is not tied to either of those. Check out the {@link Model} interface for - * a Java-5-based interface variant that serves the same purpose. + *

This class serves as generic model holder for Servlet MVC but is not tied to it. + * Check out the {@link Model} interface for an interface variant. * * @author Rob Harrop * @author Juergen Hoeller * @since 2.0 * @see Conventions#getVariableName * @see org.springframework.web.servlet.ModelAndView - * @see org.springframework.web.portlet.ModelAndView */ @SuppressWarnings("serial") public class ModelMap extends LinkedHashMap { diff --git a/spring-context/src/main/java/org/springframework/validation/DataBinder.java b/spring-context/src/main/java/org/springframework/validation/DataBinder.java index b80bce63cf..3aceff41ba 100644 --- a/spring-context/src/main/java/org/springframework/validation/DataBinder.java +++ b/spring-context/src/main/java/org/springframework/validation/DataBinder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -92,8 +92,7 @@ import org.springframework.util.StringUtils; * *

This generic data binder can be used in any kind of environment. * It is typically used by Spring web MVC controllers, via the web-specific - * subclasses {@link org.springframework.web.bind.ServletRequestDataBinder} - * and {@link org.springframework.web.portlet.bind.PortletRequestDataBinder}. + * subclass {@link org.springframework.web.bind.ServletRequestDataBinder}. * * @author Rod Johnson * @author Juergen Hoeller diff --git a/spring-core/src/main/java/org/springframework/core/io/ContextResource.java b/spring-core/src/main/java/org/springframework/core/io/ContextResource.java index 0493cfa7a0..5f4e807db0 100644 --- a/spring-core/src/main/java/org/springframework/core/io/ContextResource.java +++ b/spring-core/src/main/java/org/springframework/core/io/ContextResource.java @@ -18,15 +18,14 @@ package org.springframework.core.io; /** * Extended interface for a resource that is loaded from an enclosing - * 'context', e.g. from a {@link javax.servlet.ServletContext} or a - * {@link javax.portlet.PortletContext} but also from plain classpath paths - * or relative file system paths (specified without an explicit prefix, - * hence applying relative to the local {@link ResourceLoader}'s context). + * 'context', e.g. from a {@link javax.servlet.ServletContext} but also + * from plain classpath paths or relative file system paths (specified + * without an explicit prefix, hence applying relative to the local + * {@link ResourceLoader}'s context). * * @author Juergen Hoeller * @since 2.5 * @see org.springframework.web.context.support.ServletContextResource - * @see org.springframework.web.portlet.context.PortletContextResource */ public interface ContextResource extends Resource { diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionRequest.java deleted file mode 100644 index a687ccb671..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionRequest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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.mock.web.portlet; - -import javax.portlet.ActionRequest; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; - -/** - * Mock implementation of the {@link javax.portlet.ActionRequest} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockActionRequest extends MockClientDataRequest implements ActionRequest { - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - * @see org.springframework.mock.web.portlet.MockPortletContext - */ - public MockActionRequest() { - super(); - } - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param actionName the name of the action to trigger - */ - public MockActionRequest(String actionName) { - super(); - setParameter(ActionRequest.ACTION_NAME, actionName); - } - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param portletMode the mode that the portlet runs in - */ - public MockActionRequest(PortletMode portletMode) { - super(); - setPortletMode(portletMode); - } - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockActionRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockActionRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockActionRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - @Override - protected String getLifecyclePhase() { - return ACTION_PHASE; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java deleted file mode 100644 index 423cbb0c34..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockActionResponse.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import java.util.Map; -import javax.portlet.ActionResponse; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletModeException; -import javax.portlet.WindowState; -import javax.portlet.WindowStateException; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.ActionResponse} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockActionResponse extends MockStateAwareResponse implements ActionResponse { - - private boolean redirectAllowed = true; - - private String redirectedUrl; - - - /** - * Create a new MockActionResponse with a default {@link MockPortalContext}. - * @see MockPortalContext - */ - public MockActionResponse() { - super(); - } - - /** - * Create a new MockActionResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockActionResponse(PortalContext portalContext) { - super(portalContext); - } - - - @Override - public void setWindowState(WindowState windowState) throws WindowStateException { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set WindowState after sendRedirect has been called"); - } - super.setWindowState(windowState); - this.redirectAllowed = false; - } - - @Override - public void setPortletMode(PortletMode portletMode) throws PortletModeException { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set PortletMode after sendRedirect has been called"); - } - super.setPortletMode(portletMode); - this.redirectAllowed = false; - } - - @Override - public void setRenderParameters(Map parameters) { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called"); - } - super.setRenderParameters(parameters); - this.redirectAllowed = false; - } - - @Override - public void setRenderParameter(String key, String value) { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called"); - } - super.setRenderParameter(key, value); - this.redirectAllowed = false; - } - - @Override - public void setRenderParameter(String key, String[] values) { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called"); - } - super.setRenderParameter(key, values); - this.redirectAllowed = false; - } - - @Override - public void sendRedirect(String location) throws IOException { - if (!this.redirectAllowed) { - throw new IllegalStateException( - "Cannot call sendRedirect after windowState, portletMode, or renderParameters have been set"); - } - Assert.notNull(location, "Redirect URL must not be null"); - this.redirectedUrl = location; - } - - @Override - public void sendRedirect(String location, String renderUrlParamName) throws IOException { - sendRedirect(location); - if (renderUrlParamName != null) { - setRenderParameter(renderUrlParamName, location); - } - } - - public String getRedirectedUrl() { - return this.redirectedUrl; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockBaseURL.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockBaseURL.java deleted file mode 100644 index 28662358c0..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockBaseURL.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import javax.portlet.BaseURL; -import javax.portlet.PortletSecurityException; - -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * Mock implementation of the {@link javax.portlet.BaseURL} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public abstract class MockBaseURL implements BaseURL { - - public static final String URL_TYPE_RENDER = "render"; - - public static final String URL_TYPE_ACTION = "action"; - - private static final String ENCODING = "UTF-8"; - - - protected final Map parameters = new LinkedHashMap(); - - private boolean secure = false; - - private final Map properties = new LinkedHashMap(); - - - //--------------------------------------------------------------------- - // BaseURL methods - //--------------------------------------------------------------------- - - @Override - public void setParameter(String key, String value) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(value, "Parameter value must not be null"); - this.parameters.put(key, new String[] {value}); - } - - @Override - public void setParameter(String key, String[] values) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(values, "Parameter values must not be null"); - this.parameters.put(key, values); - } - - @Override - public void setParameters(Map parameters) { - Assert.notNull(parameters, "Parameters Map must not be null"); - this.parameters.clear(); - this.parameters.putAll(parameters); - } - - public Set getParameterNames() { - return this.parameters.keySet(); - } - - public String getParameter(String name) { - String[] arr = this.parameters.get(name); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public String[] getParameterValues(String name) { - return this.parameters.get(name); - } - - @Override - public Map getParameterMap() { - return Collections.unmodifiableMap(this.parameters); - } - - @Override - public void setSecure(boolean secure) throws PortletSecurityException { - this.secure = secure; - } - - public boolean isSecure() { - return this.secure; - } - - @Override - public void write(Writer out) throws IOException { - out.write(toString()); - } - - @Override - public void write(Writer out, boolean escapeXML) throws IOException { - out.write(toString()); - } - - @Override - public void addProperty(String key, String value) { - String[] values = this.properties.get(key); - if (values != null) { - this.properties.put(key, StringUtils.addStringToArray(values, value)); - } - else { - this.properties.put(key, new String[] {value}); - } - } - - @Override - public void setProperty(String key, String value) { - this.properties.put(key, new String[] {value}); - } - - public Map getProperties() { - return Collections.unmodifiableMap(this.properties); - } - - - protected String encodeParameter(String name, String value) { - try { - return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING); - } - catch (UnsupportedEncodingException ex) { - return null; - } - } - - protected String encodeParameter(String name, String[] values) { - try { - StringBuilder sb = new StringBuilder(); - for (int i = 0, n = values.length; i < n; i++) { - sb.append(i > 0 ? ";" : "").append(URLEncoder.encode(name, ENCODING)).append("=") - .append(URLEncoder.encode(values[i], ENCODING)); - } - return sb.toString(); - } - catch (UnsupportedEncodingException ex) { - return null; - } - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockCacheControl.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockCacheControl.java deleted file mode 100644 index 109133a2b6..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockCacheControl.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.CacheControl; - -/** - * Mock implementation of the {@link javax.portlet.CacheControl} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockCacheControl implements CacheControl { - - private int expirationTime = 0; - - private boolean publicScope = false; - - private String etag; - - private boolean useCachedContent = false; - - - @Override - public int getExpirationTime() { - return this.expirationTime; - } - - @Override - public void setExpirationTime(int time) { - this.expirationTime = time; - } - - @Override - public boolean isPublicScope() { - return this.publicScope; - } - - @Override - public void setPublicScope(boolean publicScope) { - this.publicScope = publicScope; - } - - @Override - public String getETag() { - return this.etag; - } - - @Override - public void setETag(String token) { - this.etag = token; - } - - @Override - public boolean useCachedContent() { - return this.useCachedContent; - } - - @Override - public void setUseCachedContent(boolean useCachedContent) { - this.useCachedContent = useCachedContent; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java deleted file mode 100644 index 15f6f59c94..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import javax.portlet.ClientDataRequest; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; - -/** - * Mock implementation of the {@link javax.portlet.ClientDataRequest} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockClientDataRequest extends MockPortletRequest implements ClientDataRequest { - - private String characterEncoding; - - private byte[] content; - - private String contentType; - - private String method; - - - /** - * Create a new MockClientDataRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - * @see org.springframework.mock.web.portlet.MockPortletContext - */ - public MockClientDataRequest() { - super(); - } - - /** - * Create a new MockClientDataRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockClientDataRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockClientDataRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockClientDataRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - public void setContent(byte[] content) { - this.content = content; - } - - @Override - public InputStream getPortletInputStream() throws IOException { - if (this.content != null) { - return new ByteArrayInputStream(this.content); - } - else { - return null; - } - } - - @Override - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - } - - @Override - public BufferedReader getReader() throws UnsupportedEncodingException { - if (this.content != null) { - InputStream sourceStream = new ByteArrayInputStream(this.content); - Reader sourceReader = (this.characterEncoding != null) ? - new InputStreamReader(sourceStream, this.characterEncoding) : new InputStreamReader(sourceStream); - return new BufferedReader(sourceReader); - } - else { - return null; - } - } - - @Override - public String getCharacterEncoding() { - return this.characterEncoding; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @Override - public String getContentType() { - return this.contentType; - } - - @Override - public int getContentLength() { - return (this.content != null ? content.length : -1); - } - - public void setMethod(String method) { - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java deleted file mode 100644 index d9d139b010..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.Serializable; -import javax.portlet.Event; -import javax.xml.namespace.QName; - -/** - * Mock implementation of the {@link javax.portlet.Event} interface. - * - * @author Juergen Hoeller - * @since 3.0 - * @see MockEventRequest - */ -public class MockEvent implements Event { - - private final QName name; - - private final Serializable value; - - - /** - * Create a new MockEvent with the given name. - * @param name the name of the event - */ - public MockEvent(QName name) { - this.name = name; - this.value = null; - } - - /** - * Create a new MockEvent with the given name and value. - * @param name the name of the event - * @param value the associated payload of the event - */ - public MockEvent(QName name, Serializable value) { - this.name = name; - this.value = value; - } - - /** - * Create a new MockEvent with the given name. - * @param name the name of the event - */ - public MockEvent(String name) { - this.name = new QName(name); - this.value = null; - } - - /** - * Create a new MockEvent with the given name and value. - * @param name the name of the event - * @param value the associated payload of the event - */ - public MockEvent(String name, Serializable value) { - this.name = new QName(name); - this.value = value; - } - - - @Override - public QName getQName() { - return this.name; - } - - @Override - public String getName() { - return this.name.getLocalPart(); - } - - @Override - public Serializable getValue() { - return this.value; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java deleted file mode 100644 index 1690ace066..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.Event; -import javax.portlet.EventRequest; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; - -/** - * Mock implementation of the {@link javax.portlet.EventRequest} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockEventRequest extends MockPortletRequest implements EventRequest { - - private final Event event; - - private String method; - - - /** - * Create a new MockEventRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param event the event that this request wraps - * @see MockEvent - */ - public MockEventRequest(Event event) { - super(); - this.event = event; - } - - /** - * Create a new MockEventRequest with a default {@link MockPortalContext}. - * @param event the event that this request wraps - * @param portletContext the PortletContext that the request runs in - * @see MockEvent - */ - public MockEventRequest(Event event, PortletContext portletContext) { - super(portletContext); - this.event = event; - } - - /** - * Create a new MockEventRequest. - * @param event the event that this request wraps - * @param portalContext the PortletContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockEventRequest(Event event, PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - this.event = event; - } - - - @Override - protected String getLifecyclePhase() { - return EVENT_PHASE; - } - - @Override - public Event getEvent() { - return this.event; - } - - public void setMethod(String method) { - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventResponse.java deleted file mode 100644 index 1114d0081b..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.EventRequest; -import javax.portlet.EventResponse; - -/** - * Mock implementation of the {@link javax.portlet.EventResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockEventResponse extends MockStateAwareResponse implements EventResponse { - - @Override - public void setRenderParameters(EventRequest request) { - setRenderParameters(request.getParameterMap()); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockMimeResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockMimeResponse.java deleted file mode 100644 index 3a45fcf209..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockMimeResponse.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright 2002-2014 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.mock.web.portlet; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Locale; -import javax.portlet.CacheControl; -import javax.portlet.MimeResponse; -import javax.portlet.PortalContext; -import javax.portlet.PortletRequest; -import javax.portlet.PortletURL; -import javax.portlet.ResourceURL; - -import org.springframework.util.CollectionUtils; -import org.springframework.web.util.WebUtils; - -/** - * Mock implementation of the {@link javax.portlet.MimeResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockMimeResponse extends MockPortletResponse implements MimeResponse { - - private PortletRequest request; - - private String contentType; - - private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; - - private PrintWriter writer; - - private Locale locale = Locale.getDefault(); - - private int bufferSize = 4096; - - private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); - - private final CacheControl cacheControl = new MockCacheControl(); - - private boolean committed; - - private String includedUrl; - - private String forwardedUrl; - - - /** - * Create a new MockMimeResponse with a default {@link MockPortalContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - */ - public MockMimeResponse() { - super(); - } - - /** - * Create a new MockMimeResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockMimeResponse(PortalContext portalContext) { - super(portalContext); - } - - /** - * Create a new MockMimeResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - * @param request the corresponding render/resource request that this response - * is being generated for - */ - public MockMimeResponse(PortalContext portalContext, PortletRequest request) { - super(portalContext); - this.request = request; - } - - - //--------------------------------------------------------------------- - // RenderResponse methods - //--------------------------------------------------------------------- - - @Override - public void setContentType(String contentType) { - if (this.request != null) { - Enumeration supportedTypes = this.request.getResponseContentTypes(); - if (!CollectionUtils.contains(supportedTypes, contentType)) { - throw new IllegalArgumentException("Content type [" + contentType + "] not in supported list: " + - Collections.list(supportedTypes)); - } - } - this.contentType = contentType; - } - - @Override - public String getContentType() { - return this.contentType; - } - - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - } - - @Override - public String getCharacterEncoding() { - return this.characterEncoding; - } - - @Override - public PrintWriter getWriter() throws UnsupportedEncodingException { - if (this.writer == null) { - Writer targetWriter = (this.characterEncoding != null ? - new OutputStreamWriter(this.outputStream, this.characterEncoding) : - new OutputStreamWriter(this.outputStream)); - this.writer = new PrintWriter(targetWriter); - } - return this.writer; - } - - public byte[] getContentAsByteArray() { - flushBuffer(); - return this.outputStream.toByteArray(); - } - - public String getContentAsString() throws UnsupportedEncodingException { - flushBuffer(); - return (this.characterEncoding != null ? - this.outputStream.toString(this.characterEncoding) : this.outputStream.toString()); - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - @Override - public Locale getLocale() { - return this.locale; - } - - @Override - public void setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - } - - @Override - public int getBufferSize() { - return this.bufferSize; - } - - @Override - public void flushBuffer() { - if (this.writer != null) { - this.writer.flush(); - } - try { - this.outputStream.flush(); - } - catch (IOException ex) { - throw new IllegalStateException("Could not flush OutputStream: " + ex.getMessage()); - } - this.committed = true; - } - - @Override - public void resetBuffer() { - if (this.committed) { - throw new IllegalStateException("Cannot reset buffer - response is already committed"); - } - this.outputStream.reset(); - } - - public void setCommitted(boolean committed) { - this.committed = committed; - } - - @Override - public boolean isCommitted() { - return this.committed; - } - - @Override - public void reset() { - resetBuffer(); - this.characterEncoding = null; - this.contentType = null; - this.locale = null; - } - - @Override - public OutputStream getPortletOutputStream() throws IOException { - return this.outputStream; - } - - @Override - public PortletURL createRenderURL() { - return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_RENDER); - } - - @Override - public PortletURL createActionURL() { - return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_ACTION); - } - - @Override - public ResourceURL createResourceURL() { - return new MockResourceURL(); - } - - @Override - public CacheControl getCacheControl() { - return this.cacheControl; - } - - - //--------------------------------------------------------------------- - // Methods for MockPortletRequestDispatcher - //--------------------------------------------------------------------- - - public void setIncludedUrl(String includedUrl) { - this.includedUrl = includedUrl; - } - - public String getIncludedUrl() { - return this.includedUrl; - } - - public void setForwardedUrl(String forwardedUrl) { - this.forwardedUrl = forwardedUrl; - } - - public String getForwardedUrl() { - return this.forwardedUrl; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java deleted file mode 100644 index e269a621e1..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.springframework.util.Assert; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.portlet.multipart.MultipartActionRequest; - -/** - * Mock implementation of the - * {@link org.springframework.web.portlet.multipart.MultipartActionRequest} interface. - * - *

Useful for testing application controllers that access multipart uploads. - * The {@link org.springframework.mock.web.MockMultipartFile} can be used to - * populate these mock requests with files. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @since 2.0 - * @see org.springframework.mock.web.MockMultipartFile - */ -public class MockMultipartActionRequest extends MockActionRequest implements MultipartActionRequest { - - private final MultiValueMap multipartFiles = - new LinkedMultiValueMap(); - - - /** - * Add a file to this request. The parameter name from the multipart - * form is taken from the {@link org.springframework.web.multipart.MultipartFile#getName()}. - * @param file multipart file to be added - */ - public void addFile(MultipartFile file) { - Assert.notNull(file, "MultipartFile must not be null"); - this.multipartFiles.add(file.getName(), file); - } - - @Override - public Iterator getFileNames() { - return this.multipartFiles.keySet().iterator(); - } - - @Override - public MultipartFile getFile(String name) { - return this.multipartFiles.getFirst(name); - } - - @Override - public List getFiles(String name) { - List multipartFiles = this.multipartFiles.get(name); - if (multipartFiles != null) { - return multipartFiles; - } - else { - return Collections.emptyList(); - } - } - - @Override - public Map getFileMap() { - return this.multipartFiles.toSingleValueMap(); - } - - @Override - public MultiValueMap getMultiFileMap() { - return new LinkedMultiValueMap(this.multipartFiles); - } - - @Override - public String getMultipartContentType(String paramOrFileName) { - MultipartFile file = getFile(paramOrFileName); - if (file != null) { - return file.getContentType(); - } - else { - return null; - } - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java deleted file mode 100644 index 824df6f70d..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortalContext.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.WindowState; - -/** - * Mock implementation of the {@link javax.portlet.PortalContext} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortalContext implements PortalContext { - - private final Map properties = new HashMap(); - - private final List portletModes; - - private final List windowStates; - - - /** - * Create a new MockPortalContext - * with default PortletModes (VIEW, EDIT, HELP) - * and default WindowStates (NORMAL, MAXIMIZED, MINIMIZED). - * @see javax.portlet.PortletMode - * @see javax.portlet.WindowState - */ - public MockPortalContext() { - this.portletModes = new ArrayList(3); - this.portletModes.add(PortletMode.VIEW); - this.portletModes.add(PortletMode.EDIT); - this.portletModes.add(PortletMode.HELP); - - this.windowStates = new ArrayList(3); - this.windowStates.add(WindowState.NORMAL); - this.windowStates.add(WindowState.MAXIMIZED); - this.windowStates.add(WindowState.MINIMIZED); - } - - /** - * Create a new MockPortalContext with the given PortletModes and WindowStates. - * @param supportedPortletModes the List of supported PortletMode instances - * @param supportedWindowStates the List of supported WindowState instances - * @see javax.portlet.PortletMode - * @see javax.portlet.WindowState - */ - public MockPortalContext(List supportedPortletModes, List supportedWindowStates) { - this.portletModes = new ArrayList(supportedPortletModes); - this.windowStates = new ArrayList(supportedWindowStates); - } - - - @Override - public String getPortalInfo() { - return "MockPortal/1.0"; - } - - public void setProperty(String name, String value) { - this.properties.put(name, value); - } - - @Override - public String getProperty(String name) { - return this.properties.get(name); - } - - @Override - public Enumeration getPropertyNames() { - return Collections.enumeration(this.properties.keySet()); - } - - @Override - public Enumeration getSupportedPortletModes() { - return Collections.enumeration(this.portletModes); - } - - @Override - public Enumeration getSupportedWindowStates() { - return Collections.enumeration(this.windowStates); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java deleted file mode 100644 index cf7f48bb17..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletConfig.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.Set; -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletConfig} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletConfig implements PortletConfig { - - private final PortletContext portletContext; - - private final String portletName; - - private final Map resourceBundles = new HashMap(); - - private final Map initParameters = new LinkedHashMap(); - - private final Set publicRenderParameterNames = new LinkedHashSet(); - - private String defaultNamespace = XMLConstants.NULL_NS_URI; - - private final Set publishingEventQNames = new LinkedHashSet(); - - private final Set processingEventQNames = new LinkedHashSet(); - - private final Set supportedLocales = new LinkedHashSet(); - - private final Map containerRuntimeOptions = new LinkedHashMap(); - - - /** - * Create a new MockPortletConfig with a default {@link MockPortletContext}. - */ - public MockPortletConfig() { - this(null, ""); - } - - /** - * Create a new MockPortletConfig with a default {@link MockPortletContext}. - * @param portletName the name of the portlet - */ - public MockPortletConfig(String portletName) { - this(null, portletName); - } - - /** - * Create a new MockPortletConfig. - * @param portletContext the PortletContext that the portlet runs in - */ - public MockPortletConfig(PortletContext portletContext) { - this(portletContext, ""); - } - - /** - * Create a new MockPortletConfig. - * @param portletContext the PortletContext that the portlet runs in - * @param portletName the name of the portlet - */ - public MockPortletConfig(PortletContext portletContext, String portletName) { - this.portletContext = (portletContext != null ? portletContext : new MockPortletContext()); - this.portletName = portletName; - } - - - @Override - public String getPortletName() { - return this.portletName; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - public void setResourceBundle(Locale locale, ResourceBundle resourceBundle) { - Assert.notNull(locale, "Locale must not be null"); - this.resourceBundles.put(locale, resourceBundle); - } - - @Override - public ResourceBundle getResourceBundle(Locale locale) { - Assert.notNull(locale, "Locale must not be null"); - return this.resourceBundles.get(locale); - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - - public void addPublicRenderParameterName(String name) { - this.publicRenderParameterNames.add(name); - } - - @Override - public Enumeration getPublicRenderParameterNames() { - return Collections.enumeration(this.publicRenderParameterNames); - } - - public void setDefaultNamespace(String defaultNamespace) { - this.defaultNamespace = defaultNamespace; - } - - @Override - public String getDefaultNamespace() { - return this.defaultNamespace; - } - - public void addPublishingEventQName(QName name) { - this.publishingEventQNames.add(name); - } - - @Override - public Enumeration getPublishingEventQNames() { - return Collections.enumeration(this.publishingEventQNames); - } - - public void addProcessingEventQName(QName name) { - this.processingEventQNames.add(name); - } - - @Override - public Enumeration getProcessingEventQNames() { - return Collections.enumeration(this.processingEventQNames); - } - - public void addSupportedLocale(Locale locale) { - this.supportedLocales.add(locale); - } - - @Override - public Enumeration getSupportedLocales() { - return Collections.enumeration(this.supportedLocales); - } - - public void addContainerRuntimeOption(String key, String value) { - this.containerRuntimeOptions.put(key, new String[] {value}); - } - - public void addContainerRuntimeOption(String key, String[] values) { - this.containerRuntimeOptions.put(key, values); - } - - @Override - public Map getContainerRuntimeOptions() { - return Collections.unmodifiableMap(this.containerRuntimeOptions); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java deleted file mode 100644 index bf1e6f0975..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright 2002-2013 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.mock.web.portlet; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import javax.activation.FileTypeMap; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequestDispatcher; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.util.Assert; -import org.springframework.web.util.WebUtils; - -/** - * Mock implementation of the {@link javax.portlet.PortletContext} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletContext implements PortletContext { - - private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir"; - - - private final Log logger = LogFactory.getLog(getClass()); - - private final String resourceBasePath; - - private final ResourceLoader resourceLoader; - - private final Map attributes = new LinkedHashMap(); - - private final Map initParameters = new LinkedHashMap(); - - private String portletContextName = "MockPortletContext"; - - private Set containerRuntimeOptions = new LinkedHashSet(); - - - /** - * Create a new MockPortletContext with no base path and a - * DefaultResourceLoader (i.e. the classpath root as WAR root). - * @see org.springframework.core.io.DefaultResourceLoader - */ - public MockPortletContext() { - this("", null); - } - - /** - * Create a new MockPortletContext using a DefaultResourceLoader. - * @param resourceBasePath the WAR root directory (should not end with a slash) - * @see org.springframework.core.io.DefaultResourceLoader - */ - public MockPortletContext(String resourceBasePath) { - this(resourceBasePath, null); - } - - /** - * Create a new MockPortletContext, using the specified ResourceLoader - * and no base path. - * @param resourceLoader the ResourceLoader to use (or null for the default) - */ - public MockPortletContext(ResourceLoader resourceLoader) { - this("", resourceLoader); - } - - /** - * Create a new MockPortletContext. - * @param resourceBasePath the WAR root directory (should not end with a slash) - * @param resourceLoader the ResourceLoader to use (or null for the default) - */ - public MockPortletContext(String resourceBasePath, ResourceLoader resourceLoader) { - this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : ""); - this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); - - // Use JVM temp dir as PortletContext temp dir. - String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY); - if (tempDir != null) { - this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir)); - } - } - - /** - * Build a full resource location for the given path, - * prepending the resource base path of this MockPortletContext. - * @param path the path as specified - * @return the full resource path - */ - protected String getResourceLocation(String path) { - if (!path.startsWith("/")) { - path = "/" + path; - } - return this.resourceBasePath + path; - } - - - @Override - public String getServerInfo() { - return "MockPortal/1.0"; - } - - @Override - public PortletRequestDispatcher getRequestDispatcher(String path) { - if (!path.startsWith("/")) { - throw new IllegalArgumentException( - "PortletRequestDispatcher path at PortletContext level must start with '/'"); - } - return new MockPortletRequestDispatcher(path); - } - - @Override - public PortletRequestDispatcher getNamedDispatcher(String path) { - return null; - } - - @Override - public InputStream getResourceAsStream(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getInputStream(); - } - catch (IOException ex) { - logger.info("Couldn't open InputStream for " + resource, ex); - return null; - } - } - - @Override - public int getMajorVersion() { - return 2; - } - - @Override - public int getMinorVersion() { - return 0; - } - - @Override - public String getMimeType(String filePath) { - return MimeTypeResolver.getMimeType(filePath); - } - - @Override - public String getRealPath(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getFile().getAbsolutePath(); - } - catch (IOException ex) { - logger.info("Couldn't determine real path of resource " + resource, ex); - return null; - } - } - - @Override - public Set getResourcePaths(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - File file = resource.getFile(); - String[] fileList = file.list(); - String prefix = (path.endsWith("/") ? path : path + "/"); - Set resourcePaths = new HashSet(fileList.length); - for (String fileEntry : fileList) { - resourcePaths.add(prefix + fileEntry); - } - return resourcePaths; - } - catch (IOException ex) { - logger.info("Couldn't get resource paths for " + resource, ex); - return null; - } - } - - @Override - public URL getResource(String path) throws MalformedURLException { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getURL(); - } - catch (IOException ex) { - logger.info("Couldn't get URL for " + resource, ex); - return null; - } - } - - @Override - public Object getAttribute(String name) { - return this.attributes.get(name); - } - - @Override - public Enumeration getAttributeNames() { - return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); - } - - @Override - public void setAttribute(String name, Object value) { - if (value != null) { - this.attributes.put(name, value); - } - else { - this.attributes.remove(name); - } - } - - @Override - public void removeAttribute(String name) { - this.attributes.remove(name); - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - - @Override - public void log(String message) { - logger.info(message); - } - - @Override - public void log(String message, Throwable t) { - logger.info(message, t); - } - - public void setPortletContextName(String portletContextName) { - this.portletContextName = portletContextName; - } - - @Override - public String getPortletContextName() { - return this.portletContextName; - } - - public void addContainerRuntimeOption(String key) { - this.containerRuntimeOptions.add(key); - } - - @Override - public Enumeration getContainerRuntimeOptions() { - return Collections.enumeration(this.containerRuntimeOptions); - } - - - /** - * Inner factory class used to just introduce a Java Activation Framework - * dependency when actually asked to resolve a MIME type. - */ - private static class MimeTypeResolver { - - public static String getMimeType(String filePath) { - return FileTypeMap.getDefaultFileTypeMap().getContentType(filePath); - } - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java deleted file mode 100644 index 3af2d6e97a..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletPreferences.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortletPreferences; -import javax.portlet.PreferencesValidator; -import javax.portlet.ReadOnlyException; -import javax.portlet.ValidatorException; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletPreferences} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletPreferences implements PortletPreferences { - - private PreferencesValidator preferencesValidator; - - private final Map preferences = new LinkedHashMap(); - - private final Set readOnly = new HashSet(); - - - public void setReadOnly(String key, boolean readOnly) { - Assert.notNull(key, "Key must not be null"); - if (readOnly) { - this.readOnly.add(key); - } - else { - this.readOnly.remove(key); - } - } - - @Override - public boolean isReadOnly(String key) { - Assert.notNull(key, "Key must not be null"); - return this.readOnly.contains(key); - } - - @Override - public String getValue(String key, String def) { - Assert.notNull(key, "Key must not be null"); - String[] values = this.preferences.get(key); - return (values != null && values.length > 0 ? values[0] : def); - } - - @Override - public String[] getValues(String key, String[] def) { - Assert.notNull(key, "Key must not be null"); - String[] values = this.preferences.get(key); - return (values != null && values.length > 0 ? values : def); - } - - @Override - public void setValue(String key, String value) throws ReadOnlyException { - setValues(key, new String[] {value}); - } - - @Override - public void setValues(String key, String[] values) throws ReadOnlyException { - Assert.notNull(key, "Key must not be null"); - if (isReadOnly(key)) { - throw new ReadOnlyException("Preference '" + key + "' is read-only"); - } - this.preferences.put(key, values); - } - - @Override - public Enumeration getNames() { - return Collections.enumeration(this.preferences.keySet()); - } - - @Override - public Map getMap() { - return Collections.unmodifiableMap(this.preferences); - } - - @Override - public void reset(String key) throws ReadOnlyException { - Assert.notNull(key, "Key must not be null"); - if (isReadOnly(key)) { - throw new ReadOnlyException("Preference '" + key + "' is read-only"); - } - this.preferences.remove(key); - } - - public void setPreferencesValidator(PreferencesValidator preferencesValidator) { - this.preferencesValidator = preferencesValidator; - } - - @Override - public void store() throws IOException, ValidatorException { - if (this.preferencesValidator != null) { - this.preferencesValidator.validate(this); - } - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java deleted file mode 100644 index 649bafe6f6..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java +++ /dev/null @@ -1,569 +0,0 @@ -/* - * Copyright 2002-2013 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.mock.web.portlet; - -import java.security.Principal; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletPreferences; -import javax.portlet.PortletRequest; -import javax.portlet.PortletSession; -import javax.portlet.WindowState; -import javax.servlet.http.Cookie; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Mock implementation of the {@link javax.portlet.PortletRequest} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletRequest implements PortletRequest { - - private boolean active = true; - - private final PortalContext portalContext; - - private final PortletContext portletContext; - - private PortletSession session; - - private WindowState windowState = WindowState.NORMAL; - - private PortletMode portletMode = PortletMode.VIEW; - - private PortletPreferences portletPreferences = new MockPortletPreferences(); - - private final Map> properties = new LinkedHashMap>(); - - private final Map attributes = new LinkedHashMap(); - - private final Map parameters = new LinkedHashMap(); - - private String authType = null; - - private String contextPath = ""; - - private String remoteUser = null; - - private Principal userPrincipal = null; - - private final Set userRoles = new HashSet(); - - private boolean secure = false; - - private boolean requestedSessionIdValid = true; - - private final List responseContentTypes = new LinkedList(); - - private final List locales = new LinkedList(); - - private String scheme = "http"; - - private String serverName = "localhost"; - - private int serverPort = 80; - - private String windowID; - - private Cookie[] cookies; - - private final Set publicParameterNames = new HashSet(); - - - /** - * Create a new MockPortletRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * - * @see MockPortalContext - * @see MockPortletContext - */ - public MockPortletRequest() { - this(null, null); - } - - /** - * Create a new MockPortletRequest with a default {@link MockPortalContext}. - * - * @param portletContext the PortletContext that the request runs in - * @see MockPortalContext - */ - public MockPortletRequest(PortletContext portletContext) { - this(null, portletContext); - } - - /** - * Create a new MockPortletRequest. - * - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockPortletRequest(PortalContext portalContext, PortletContext portletContext) { - this.portalContext = (portalContext != null ? portalContext : new MockPortalContext()); - this.portletContext = (portletContext != null ? portletContext : new MockPortletContext()); - this.responseContentTypes.add("text/html"); - this.locales.add(Locale.ENGLISH); - this.attributes.put(LIFECYCLE_PHASE, getLifecyclePhase()); - } - - // --------------------------------------------------------------------- - // Lifecycle methods - // --------------------------------------------------------------------- - - /** - * Return the Portlet 2.0 lifecycle id for the current phase. - */ - protected String getLifecyclePhase() { - return null; - } - - /** - * Return whether this request is still active (that is, not completed yet). - */ - public boolean isActive() { - return this.active; - } - - /** - * Mark this request as completed. - */ - public void close() { - this.active = false; - } - - /** - * Check whether this request is still active (that is, not completed yet), - * throwing an IllegalStateException if not active anymore. - */ - protected void checkActive() throws IllegalStateException { - if (!this.active) { - throw new IllegalStateException("Request is not active anymore"); - } - } - - // --------------------------------------------------------------------- - // PortletRequest methods - // --------------------------------------------------------------------- - - @Override - public boolean isWindowStateAllowed(WindowState windowState) { - return CollectionUtils.contains(this.portalContext.getSupportedWindowStates(), windowState); - } - - @Override - public boolean isPortletModeAllowed(PortletMode portletMode) { - return CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode); - } - - public void setPortletMode(PortletMode portletMode) { - Assert.notNull(portletMode, "PortletMode must not be null"); - this.portletMode = portletMode; - } - - @Override - public PortletMode getPortletMode() { - return this.portletMode; - } - - public void setWindowState(WindowState windowState) { - Assert.notNull(windowState, "WindowState must not be null"); - this.windowState = windowState; - } - - @Override - public WindowState getWindowState() { - return this.windowState; - } - - public void setPreferences(PortletPreferences preferences) { - Assert.notNull(preferences, "PortletPreferences must not be null"); - this.portletPreferences = preferences; - } - - @Override - public PortletPreferences getPreferences() { - return this.portletPreferences; - } - - public void setSession(PortletSession session) { - this.session = session; - if (session instanceof MockPortletSession) { - MockPortletSession mockSession = ((MockPortletSession) session); - mockSession.access(); - } - } - - @Override - public PortletSession getPortletSession() { - return getPortletSession(true); - } - - @Override - public PortletSession getPortletSession(boolean create) { - checkActive(); - // Reset session if invalidated. - if (this.session instanceof MockPortletSession && ((MockPortletSession) this.session).isInvalid()) { - this.session = null; - } - // Create new session if necessary. - if (this.session == null && create) { - this.session = new MockPortletSession(this.portletContext); - } - return this.session; - } - - /** - * Set a single value for the specified property. - *

- * If there are already one or more values registered for the given property - * key, they will be replaced. - */ - public void setProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - List list = new LinkedList(); - list.add(value); - this.properties.put(key, list); - } - - /** - * Add a single value for the specified property. - *

- * If there are already one or more values registered for the given property - * key, the given value will be added to the end of the list. - */ - public void addProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - List oldList = this.properties.get(key); - if (oldList != null) { - oldList.add(value); - } - else { - List list = new LinkedList(); - list.add(value); - this.properties.put(key, list); - } - } - - @Override - public String getProperty(String key) { - Assert.notNull(key, "Property key must not be null"); - List list = this.properties.get(key); - return (list != null && list.size() > 0 ? list.get(0) : null); - } - - @Override - public Enumeration getProperties(String key) { - Assert.notNull(key, "property key must not be null"); - return Collections.enumeration(this.properties.get(key)); - } - - @Override - public Enumeration getPropertyNames() { - return Collections.enumeration(this.properties.keySet()); - } - - @Override - public PortalContext getPortalContext() { - return this.portalContext; - } - - public void setAuthType(String authType) { - this.authType = authType; - } - - @Override - public String getAuthType() { - return this.authType; - } - - public void setContextPath(String contextPath) { - this.contextPath = contextPath; - } - - @Override - public String getContextPath() { - return this.contextPath; - } - - public void setRemoteUser(String remoteUser) { - this.remoteUser = remoteUser; - } - - @Override - public String getRemoteUser() { - return this.remoteUser; - } - - public void setUserPrincipal(Principal userPrincipal) { - this.userPrincipal = userPrincipal; - } - - @Override - public Principal getUserPrincipal() { - return this.userPrincipal; - } - - public void addUserRole(String role) { - this.userRoles.add(role); - } - - @Override - public boolean isUserInRole(String role) { - return this.userRoles.contains(role); - } - - @Override - public Object getAttribute(String name) { - checkActive(); - return this.attributes.get(name); - } - - @Override - public Enumeration getAttributeNames() { - checkActive(); - return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); - } - - public void setParameters(Map parameters) { - Assert.notNull(parameters, "Parameters Map must not be null"); - this.parameters.clear(); - this.parameters.putAll(parameters); - } - - public void setParameter(String key, String value) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(value, "Parameter value must not be null"); - this.parameters.put(key, new String[] { value }); - } - - public void setParameter(String key, String[] values) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(values, "Parameter values must not be null"); - this.parameters.put(key, values); - } - - public void addParameter(String name, String value) { - addParameter(name, new String[] { value }); - } - - public void addParameter(String name, String[] values) { - String[] oldArr = this.parameters.get(name); - if (oldArr != null) { - String[] newArr = new String[oldArr.length + values.length]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - System.arraycopy(values, 0, newArr, oldArr.length, values.length); - this.parameters.put(name, newArr); - } - else { - this.parameters.put(name, values); - } - } - - @Override - public String getParameter(String name) { - String[] arr = this.parameters.get(name); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - @Override - public Enumeration getParameterNames() { - return Collections.enumeration(this.parameters.keySet()); - } - - @Override - public String[] getParameterValues(String name) { - return this.parameters.get(name); - } - - @Override - public Map getParameterMap() { - return Collections.unmodifiableMap(this.parameters); - } - - public void setSecure(boolean secure) { - this.secure = secure; - } - - @Override - public boolean isSecure() { - return this.secure; - } - - @Override - public void setAttribute(String name, Object value) { - checkActive(); - if (value != null) { - this.attributes.put(name, value); - } - else { - this.attributes.remove(name); - } - } - - @Override - public void removeAttribute(String name) { - checkActive(); - this.attributes.remove(name); - } - - @Override - public String getRequestedSessionId() { - PortletSession session = this.getPortletSession(); - return (session != null ? session.getId() : null); - } - - public void setRequestedSessionIdValid(boolean requestedSessionIdValid) { - this.requestedSessionIdValid = requestedSessionIdValid; - } - - @Override - public boolean isRequestedSessionIdValid() { - return this.requestedSessionIdValid; - } - - public void addResponseContentType(String responseContentType) { - this.responseContentTypes.add(responseContentType); - } - - public void addPreferredResponseContentType(String responseContentType) { - this.responseContentTypes.add(0, responseContentType); - } - - @Override - public String getResponseContentType() { - return this.responseContentTypes.get(0); - } - - @Override - public Enumeration getResponseContentTypes() { - return Collections.enumeration(this.responseContentTypes); - } - - public void addLocale(Locale locale) { - this.locales.add(locale); - } - - public void addPreferredLocale(Locale locale) { - this.locales.add(0, locale); - } - - @Override - public Locale getLocale() { - return this.locales.get(0); - } - - @Override - public Enumeration getLocales() { - return Collections.enumeration(this.locales); - } - - public void setScheme(String scheme) { - this.scheme = scheme; - } - - @Override - public String getScheme() { - return this.scheme; - } - - public void setServerName(String serverName) { - this.serverName = serverName; - } - - @Override - public String getServerName() { - return this.serverName; - } - - public void setServerPort(int serverPort) { - this.serverPort = serverPort; - } - - @Override - public int getServerPort() { - return this.serverPort; - } - - public void setWindowID(String windowID) { - this.windowID = windowID; - } - - @Override - public String getWindowID() { - return this.windowID; - } - - public void setCookies(Cookie... cookies) { - this.cookies = cookies; - } - - @Override - public Cookie[] getCookies() { - return this.cookies; - } - - @Override - public Map getPrivateParameterMap() { - if (!this.publicParameterNames.isEmpty()) { - Map filtered = new LinkedHashMap(); - for (String key : this.parameters.keySet()) { - if (!this.publicParameterNames.contains(key)) { - filtered.put(key, this.parameters.get(key)); - } - } - return filtered; - } - else { - return Collections.unmodifiableMap(this.parameters); - } - } - - @Override - public Map getPublicParameterMap() { - if (!this.publicParameterNames.isEmpty()) { - Map filtered = new LinkedHashMap(); - for (String key : this.parameters.keySet()) { - if (this.publicParameterNames.contains(key)) { - filtered.put(key, this.parameters.get(key)); - } - } - return filtered; - } - else { - return Collections.emptyMap(); - } - } - - public void registerPublicParameter(String name) { - this.publicParameterNames.add(name); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java deleted file mode 100644 index f4e0dc98fd..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.PortletResponse; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletRequestDispatcher} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletRequestDispatcher implements PortletRequestDispatcher { - - private final Log logger = LogFactory.getLog(getClass()); - - private final String url; - - - /** - * Create a new MockPortletRequestDispatcher for the given URL. - * @param url the URL to dispatch to. - */ - public MockPortletRequestDispatcher(String url) { - Assert.notNull(url, "URL must not be null"); - this.url = url; - } - - - @Override - public void include(RenderRequest request, RenderResponse response) throws PortletException, IOException { - include((PortletRequest) request, (PortletResponse) response); - } - - @Override - public void include(PortletRequest request, PortletResponse response) throws PortletException, IOException { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - if (!(response instanceof MockMimeResponse)) { - throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse"); - } - ((MockMimeResponse) response).setIncludedUrl(this.url); - if (logger.isDebugEnabled()) { - logger.debug("MockPortletRequestDispatcher: including URL [" + this.url + "]"); - } - } - - @Override - public void forward(PortletRequest request, PortletResponse response) throws PortletException, IOException { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - if (!(response instanceof MockMimeResponse)) { - throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse"); - } - ((MockMimeResponse) response).setForwardedUrl(this.url); - if (logger.isDebugEnabled()) { - logger.debug("MockPortletRequestDispatcher: forwarding to URL [" + this.url + "]"); - } - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java deleted file mode 100644 index 513a6c8c9c..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletResponse.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortalContext; -import javax.portlet.PortletResponse; -import javax.servlet.http.Cookie; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletResponse} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletResponse implements PortletResponse { - - private final PortalContext portalContext; - - private final Map properties = new LinkedHashMap(); - - private String namespace = ""; - - private final Set cookies = new LinkedHashSet(); - - private final Map xmlProperties = new LinkedHashMap(); - - private Document xmlDocument; - - - /** - * Create a new MockPortletResponse with a default {@link MockPortalContext}. - * @see MockPortalContext - */ - public MockPortletResponse() { - this(null); - } - - /** - * Create a new MockPortletResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockPortletResponse(PortalContext portalContext) { - this.portalContext = (portalContext != null ? portalContext : new MockPortalContext()); - } - - /** - * Return the PortalContext that this MockPortletResponse runs in, - * defining the supported PortletModes and WindowStates. - */ - public PortalContext getPortalContext() { - return this.portalContext; - } - - - //--------------------------------------------------------------------- - // PortletResponse methods - //--------------------------------------------------------------------- - - @Override - public void addProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - String[] oldArr = this.properties.get(key); - if (oldArr != null) { - String[] newArr = new String[oldArr.length + 1]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - newArr[oldArr.length] = value; - this.properties.put(key, newArr); - } - else { - this.properties.put(key, new String[] {value}); - } - } - - @Override - public void setProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - this.properties.put(key, new String[] {value}); - } - - public Set getPropertyNames() { - return Collections.unmodifiableSet(this.properties.keySet()); - } - - public String getProperty(String key) { - Assert.notNull(key, "Property key must not be null"); - String[] arr = this.properties.get(key); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public String[] getProperties(String key) { - Assert.notNull(key, "Property key must not be null"); - return this.properties.get(key); - } - - @Override - public String encodeURL(String path) { - return path; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - @Override - public String getNamespace() { - return this.namespace; - } - - @Override - public void addProperty(Cookie cookie) { - Assert.notNull(cookie, "Cookie must not be null"); - this.cookies.add(cookie); - } - - public Cookie[] getCookies() { - return this.cookies.toArray(new Cookie[this.cookies.size()]); - } - - public Cookie getCookie(String name) { - Assert.notNull(name, "Cookie name must not be null"); - for (Cookie cookie : this.cookies) { - if (name.equals(cookie.getName())) { - return cookie; - } - } - return null; - } - - @Override - public void addProperty(String key, Element value) { - Assert.notNull(key, "Property key must not be null"); - Element[] oldArr = this.xmlProperties.get(key); - if (oldArr != null) { - Element[] newArr = new Element[oldArr.length + 1]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - newArr[oldArr.length] = value; - this.xmlProperties.put(key, newArr); - } - else { - this.xmlProperties.put(key, new Element[] {value}); - } - } - - - public Set getXmlPropertyNames() { - return Collections.unmodifiableSet(this.xmlProperties.keySet()); - } - - public Element getXmlProperty(String key) { - Assert.notNull(key, "Property key must not be null"); - Element[] arr = this.xmlProperties.get(key); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public Element[] getXmlProperties(String key) { - Assert.notNull(key, "Property key must not be null"); - return this.xmlProperties.get(key); - } - - @Override - public Element createElement(String tagName) throws DOMException { - if (this.xmlDocument == null) { - try { - this.xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - } - catch (ParserConfigurationException ex) { - throw new DOMException(DOMException.INVALID_STATE_ERR, ex.toString()); - } - } - return this.xmlDocument.createElement(tagName); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java deleted file mode 100644 index fac33bacc4..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright 2002-2013 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.mock.web.portlet; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import javax.portlet.PortletContext; -import javax.portlet.PortletSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.springframework.mock.web.MockHttpSession; - -/** - * Mock implementation of the {@link javax.portlet.PortletSession} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletSession implements PortletSession { - - private static int nextId = 1; - - - private final String id = Integer.toString(nextId++); - - private final long creationTime = System.currentTimeMillis(); - - private int maxInactiveInterval; - - private long lastAccessedTime = System.currentTimeMillis(); - - private final PortletContext portletContext; - - private final Map portletAttributes = new LinkedHashMap(); - - private final Map applicationAttributes = new LinkedHashMap(); - - private boolean invalid = false; - - private boolean isNew = true; - - - /** - * Create a new MockPortletSession with a default {@link MockPortletContext}. - * @see MockPortletContext - */ - public MockPortletSession() { - this(null); - } - - /** - * Create a new MockPortletSession. - * @param portletContext the PortletContext that the session runs in - */ - public MockPortletSession(PortletContext portletContext) { - this.portletContext = (portletContext != null ? portletContext : new MockPortletContext()); - } - - - @Override - public Object getAttribute(String name) { - return this.portletAttributes.get(name); - } - - @Override - public Object getAttribute(String name, int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - return this.portletAttributes.get(name); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - return this.applicationAttributes.get(name); - } - return null; - } - - @Override - public Enumeration getAttributeNames() { - return Collections.enumeration(new LinkedHashSet(this.portletAttributes.keySet())); - } - - @Override - public Enumeration getAttributeNames(int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - return Collections.enumeration(new LinkedHashSet(this.portletAttributes.keySet())); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - return Collections.enumeration(new LinkedHashSet(this.applicationAttributes.keySet())); - } - return null; - } - - @Override - public long getCreationTime() { - return this.creationTime; - } - - @Override - public String getId() { - return this.id; - } - - public void access() { - this.lastAccessedTime = System.currentTimeMillis(); - setNew(false); - } - - @Override - public long getLastAccessedTime() { - return this.lastAccessedTime; - } - - @Override - public int getMaxInactiveInterval() { - return this.maxInactiveInterval; - } - - /** - * Clear all of this session's attributes. - */ - public void clearAttributes() { - doClearAttributes(this.portletAttributes); - doClearAttributes(this.applicationAttributes); - } - - protected void doClearAttributes(Map attributes) { - for (Iterator> it = attributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - String name = entry.getKey(); - Object value = entry.getValue(); - it.remove(); - if (value instanceof HttpSessionBindingListener) { - ((HttpSessionBindingListener) value).valueUnbound( - new HttpSessionBindingEvent(new MockHttpSession(), name, value)); - } - } - } - - @Override - public void invalidate() { - this.invalid = true; - clearAttributes(); - } - - public boolean isInvalid() { - return this.invalid; - } - - public void setNew(boolean value) { - this.isNew = value; - } - - @Override - public boolean isNew() { - return this.isNew; - } - - @Override - public void removeAttribute(String name) { - this.portletAttributes.remove(name); - } - - @Override - public void removeAttribute(String name, int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - this.portletAttributes.remove(name); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - this.applicationAttributes.remove(name); - } - } - - @Override - public void setAttribute(String name, Object value) { - if (value != null) { - this.portletAttributes.put(name, value); - } - else { - this.portletAttributes.remove(name); - } - } - - @Override - public void setAttribute(String name, Object value, int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - if (value != null) { - this.portletAttributes.put(name, value); - } - else { - this.portletAttributes.remove(name); - } - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - if (value != null) { - this.applicationAttributes.put(name, value); - } - else { - this.applicationAttributes.remove(name); - } - } - } - - @Override - public void setMaxInactiveInterval(int interval) { - this.maxInactiveInterval = interval; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - @Override - public Map getAttributeMap() { - return Collections.unmodifiableMap(this.portletAttributes); - } - - @Override - public Map getAttributeMap(int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - return Collections.unmodifiableMap(this.portletAttributes); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - return Collections.unmodifiableMap(this.applicationAttributes); - } - else { - return Collections.emptyMap(); - } - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java deleted file mode 100644 index c7eff5a528..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletURL.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletModeException; -import javax.portlet.PortletURL; -import javax.portlet.WindowState; -import javax.portlet.WindowStateException; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Mock implementation of the {@link javax.portlet.PortletURL} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletURL extends MockBaseURL implements PortletURL { - - public static final String URL_TYPE_RENDER = "render"; - - public static final String URL_TYPE_ACTION = "action"; - - - private final PortalContext portalContext; - - private final String urlType; - - private WindowState windowState; - - private PortletMode portletMode; - - - /** - * Create a new MockPortletURL for the given URL type. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - * @param urlType the URL type, for example "render" or "action" - * @see #URL_TYPE_RENDER - * @see #URL_TYPE_ACTION - */ - public MockPortletURL(PortalContext portalContext, String urlType) { - Assert.notNull(portalContext, "PortalContext is required"); - this.portalContext = portalContext; - this.urlType = urlType; - } - - - //--------------------------------------------------------------------- - // PortletURL methods - //--------------------------------------------------------------------- - - @Override - public void setWindowState(WindowState windowState) throws WindowStateException { - if (!CollectionUtils.contains(this.portalContext.getSupportedWindowStates(), windowState)) { - throw new WindowStateException("WindowState not supported", windowState); - } - this.windowState = windowState; - } - - @Override - public WindowState getWindowState() { - return this.windowState; - } - - @Override - public void setPortletMode(PortletMode portletMode) throws PortletModeException { - if (!CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode)) { - throw new PortletModeException("PortletMode not supported", portletMode); - } - this.portletMode = portletMode; - } - - @Override - public PortletMode getPortletMode() { - return this.portletMode; - } - - @Override - public void removePublicRenderParameter(String name) { - this.parameters.remove(name); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(encodeParameter("urlType", this.urlType)); - if (this.windowState != null) { - sb.append(";").append(encodeParameter("windowState", this.windowState.toString())); - } - if (this.portletMode != null) { - sb.append(";").append(encodeParameter("portletMode", this.portletMode.toString())); - } - for (Map.Entry entry : this.parameters.entrySet()) { - sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue())); - } - return (isSecure() ? "https:" : "http:") + - "//localhost/mockportlet?" + sb.toString(); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderRequest.java deleted file mode 100644 index 8b9ed2e41a..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderRequest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; -import javax.portlet.RenderRequest; -import javax.portlet.WindowState; - -/** - * Mock implementation of the {@link javax.portlet.RenderRequest} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockRenderRequest extends MockPortletRequest implements RenderRequest { - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see MockPortalContext - * @see MockPortletContext - */ - public MockRenderRequest() { - super(); - } - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param portletMode the mode that the portlet runs in - */ - public MockRenderRequest(PortletMode portletMode) { - super(); - setPortletMode(portletMode); - } - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param portletMode the mode that the portlet runs in - * @param windowState the window state to run the portlet in - */ - public MockRenderRequest(PortletMode portletMode, WindowState windowState) { - super(); - setPortletMode(portletMode); - setWindowState(windowState); - } - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockRenderRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockRenderRequest. - * @param portalContext the PortletContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockRenderRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - @Override - protected String getLifecyclePhase() { - return RENDER_PHASE; - } - - @Override - public String getETag() { - return getProperty(RenderRequest.ETAG); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderResponse.java deleted file mode 100644 index e359b0b52c..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockRenderResponse.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collection; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -/** - * Mock implementation of the {@link javax.portlet.RenderResponse} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockRenderResponse extends MockMimeResponse implements RenderResponse { - - private String title; - - private Collection nextPossiblePortletModes; - - - /** - * Create a new MockRenderResponse with a default {@link MockPortalContext}. - * @see MockPortalContext - */ - public MockRenderResponse() { - super(); - } - - /** - * Create a new MockRenderResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockRenderResponse(PortalContext portalContext) { - super(portalContext); - } - - /** - * Create a new MockRenderResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - * @param request the corresponding render request that this response - * is generated for - */ - public MockRenderResponse(PortalContext portalContext, RenderRequest request) { - super(portalContext, request); - } - - - //--------------------------------------------------------------------- - // RenderResponse methods - //--------------------------------------------------------------------- - - @Override - public void setTitle(String title) { - this.title = title; - } - - public String getTitle() { - return this.title; - } - - @Override - public void setNextPossiblePortletModes(Collection portletModes) { - this.nextPossiblePortletModes = portletModes; - } - - public Collection getNextPossiblePortletModes() { - return this.nextPossiblePortletModes; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceRequest.java deleted file mode 100644 index 5878e7b96e..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceRequest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.RenderRequest; -import javax.portlet.ResourceRequest; - -/** - * Mock implementation of the {@link javax.portlet.ResourceRequest} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockResourceRequest extends MockClientDataRequest implements ResourceRequest { - - private String resourceID; - - private String cacheability; - - private final Map privateRenderParameterMap = new LinkedHashMap(); - - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - * @see org.springframework.mock.web.portlet.MockPortletContext - */ - public MockResourceRequest() { - super(); - } - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param resourceID the resource id for this request - */ - public MockResourceRequest(String resourceID) { - super(); - this.resourceID = resourceID; - } - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param url the resource URL for this request - */ - public MockResourceRequest(MockResourceURL url) { - super(); - this.resourceID = url.getResourceID(); - this.cacheability = url.getCacheability(); - } - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockResourceRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockResourceRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockResourceRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - @Override - protected String getLifecyclePhase() { - return RESOURCE_PHASE; - } - - public void setResourceID(String resourceID) { - this.resourceID = resourceID; - } - - @Override - public String getResourceID() { - return this.resourceID; - } - - public void setCacheability(String cacheLevel) { - this.cacheability = cacheLevel; - } - - @Override - public String getCacheability() { - return this.cacheability; - } - - @Override - public String getETag() { - return getProperty(RenderRequest.ETAG); - } - - public void addPrivateRenderParameter(String key, String value) { - this.privateRenderParameterMap.put(key, new String[] {value}); - } - - public void addPrivateRenderParameter(String key, String[] values) { - this.privateRenderParameterMap.put(key, values); - } - - @Override - public Map getPrivateRenderParameterMap() { - return Collections.unmodifiableMap(this.privateRenderParameterMap); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceResponse.java deleted file mode 100644 index 4c7f45279b..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceResponse.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.ResourceResponse; - -/** - * Mock implementation of the {@link javax.portlet.ResourceResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockResourceResponse extends MockMimeResponse implements ResourceResponse { - - private int contentLength = 0; - - - @Override - public void setContentLength(int len) { - this.contentLength = len; - } - - public int getContentLength() { - return this.contentLength; - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceURL.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceURL.java deleted file mode 100644 index b7aab871df..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockResourceURL.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Map; -import javax.portlet.ResourceURL; - -/** - * Mock implementation of the {@link javax.portlet.ResourceURL} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockResourceURL extends MockBaseURL implements ResourceURL { - - private String resourceID; - - private String cacheability; - - - //--------------------------------------------------------------------- - // ResourceURL methods - //--------------------------------------------------------------------- - - @Override - public void setResourceID(String resourceID) { - this.resourceID = resourceID; - } - - public String getResourceID() { - return this.resourceID; - } - - @Override - public void setCacheability(String cacheLevel) { - this.cacheability = cacheLevel; - } - - @Override - public String getCacheability() { - return this.cacheability; - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(encodeParameter("resourceID", this.resourceID)); - if (this.cacheability != null) { - sb.append(";").append(encodeParameter("cacheability", this.cacheability)); - } - for (Map.Entry entry : this.parameters.entrySet()) { - sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue())); - } - return (isSecure() ? "https:" : "http:") + - "//localhost/mockportlet?" + sb.toString(); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java deleted file mode 100644 index 007204ce98..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletModeException; -import javax.portlet.StateAwareResponse; -import javax.portlet.WindowState; -import javax.portlet.WindowStateException; -import javax.xml.namespace.QName; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Mock implementation of the {@link javax.portlet.StateAwareResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockStateAwareResponse extends MockPortletResponse implements StateAwareResponse { - - private WindowState windowState; - - private PortletMode portletMode; - - private final Map renderParameters = new LinkedHashMap(); - - private final Map events = new HashMap(); - - - /** - * Create a new MockActionResponse with a default {@link MockPortalContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - */ - public MockStateAwareResponse() { - super(); - } - - /** - * Create a new MockActionResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockStateAwareResponse(PortalContext portalContext) { - super(portalContext); - } - - - @Override - public void setWindowState(WindowState windowState) throws WindowStateException { - if (!CollectionUtils.contains(getPortalContext().getSupportedWindowStates(), windowState)) { - throw new WindowStateException("WindowState not supported", windowState); - } - this.windowState = windowState; - } - - @Override - public WindowState getWindowState() { - return this.windowState; - } - - @Override - public void setPortletMode(PortletMode portletMode) throws PortletModeException { - if (!CollectionUtils.contains(getPortalContext().getSupportedPortletModes(), portletMode)) { - throw new PortletModeException("PortletMode not supported", portletMode); - } - this.portletMode = portletMode; - } - - @Override - public PortletMode getPortletMode() { - return this.portletMode; - } - - @Override - public void setRenderParameters(Map parameters) { - Assert.notNull(parameters, "Parameters Map must not be null"); - this.renderParameters.clear(); - this.renderParameters.putAll(parameters); - } - - @Override - public void setRenderParameter(String key, String value) { - Assert.notNull(key, "Parameter key must not be null"); - Assert.notNull(value, "Parameter value must not be null"); - this.renderParameters.put(key, new String[] {value}); - } - - @Override - public void setRenderParameter(String key, String[] values) { - Assert.notNull(key, "Parameter key must not be null"); - Assert.notNull(values, "Parameter values must not be null"); - this.renderParameters.put(key, values); - } - - public String getRenderParameter(String key) { - Assert.notNull(key, "Parameter key must not be null"); - String[] arr = this.renderParameters.get(key); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public String[] getRenderParameterValues(String key) { - Assert.notNull(key, "Parameter key must not be null"); - return this.renderParameters.get(key); - } - - public Iterator getRenderParameterNames() { - return this.renderParameters.keySet().iterator(); - } - - @Override - public Map getRenderParameterMap() { - return Collections.unmodifiableMap(this.renderParameters); - } - - @Override - public void removePublicRenderParameter(String name) { - this.renderParameters.remove(name); - } - - @Override - public void setEvent(QName name, Serializable value) { - this.events.put(name, value); - } - - @Override - public void setEvent(String name, Serializable value) { - this.events.put(new QName(name), value); - } - - public Iterator getEventNames() { - return this.events.keySet().iterator(); - } - - public Serializable getEvent(QName name) { - return this.events.get(name); - } - - public Serializable getEvent(String name) { - return this.events.get(new QName(name)); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java deleted file mode 100644 index 716f71b0ef..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2002-2016 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.mock.web.portlet; - -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Set; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequestDispatcher; -import javax.servlet.ServletContext; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletContext} interface, - * wrapping an underlying {@link javax.servlet.ServletContext}. - * - * @author Juergen Hoeller - * @since 3.0 - * @see MockPortletContext - */ -public class ServletWrappingPortletContext implements PortletContext { - - private final ServletContext servletContext; - - - /** - * Create a new PortletContext wrapping the given ServletContext. - * @param servletContext the ServletContext to wrap - */ - public ServletWrappingPortletContext(ServletContext servletContext) { - Assert.notNull(servletContext, "ServletContext must not be null"); - this.servletContext = servletContext; - } - - /** - * Return the underlying ServletContext that this PortletContext wraps. - */ - public final ServletContext getServletContext() { - return this.servletContext; - } - - - @Override - public String getServerInfo() { - return this.servletContext.getServerInfo(); - } - - @Override - public PortletRequestDispatcher getRequestDispatcher(String path) { - return null; - } - - @Override - public PortletRequestDispatcher getNamedDispatcher(String name) { - return null; - } - - @Override - public InputStream getResourceAsStream(String path) { - return this.servletContext.getResourceAsStream(path); - } - - @Override - public int getMajorVersion() { - return 2; - } - - @Override - public int getMinorVersion() { - return 0; - } - - @Override - public String getMimeType(String file) { - return this.servletContext.getMimeType(file); - } - - @Override - public String getRealPath(String path) { - return this.servletContext.getRealPath(path); - } - - @Override - public Set getResourcePaths(String path) { - return this.servletContext.getResourcePaths(path); - } - - @Override - public URL getResource(String path) throws MalformedURLException { - return this.servletContext.getResource(path); - } - - @Override - public Object getAttribute(String name) { - return this.servletContext.getAttribute(name); - } - - @Override - public Enumeration getAttributeNames() { - return this.servletContext.getAttributeNames(); - } - - @Override - public String getInitParameter(String name) { - return this.servletContext.getInitParameter(name); - } - - @Override - public Enumeration getInitParameterNames() { - return this.servletContext.getInitParameterNames(); - } - - @Override - public void log(String msg) { - this.servletContext.log(msg); - } - - @Override - public void log(String message, Throwable throwable) { - this.servletContext.log(message, throwable); - } - - @Override - public void removeAttribute(String name) { - this.servletContext.removeAttribute(name); - } - - @Override - public void setAttribute(String name, Object object) { - this.servletContext.setAttribute(name, object); - } - - @Override - public String getPortletContextName() { - return this.servletContext.getServletContextName(); - } - - @Override - public Enumeration getContainerRuntimeOptions() { - return Collections.enumeration(Collections.emptySet()); - } - -} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/package-info.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/package-info.java deleted file mode 100644 index 526481c681..0000000000 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * A comprehensive set of Portlet API 2.0 mock objects, - * targeted at usage with Spring's Web MVC framework. - * Useful for testing web contexts and controllers. - * - *

More convenient to use than dynamic mock objects - * (EasyMock) or - * existing Portlet API mock objects. - */ -package org.springframework.mock.web.portlet; diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java index 41aafefa42..e9b7231baf 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -27,8 +27,6 @@ import org.springframework.core.annotation.AliasFor; /** * Annotation which indicates that a method parameter should be bound to an HTTP cookie. * - *

Supported for annotated handler methods in Servlet and Portlet environments. - * *

The method parameter may be declared as type {@link javax.servlet.http.Cookie} * or as cookie value type (String, int, etc.). * @@ -39,9 +37,6 @@ import org.springframework.core.annotation.AliasFor; * @see RequestParam * @see RequestHeader * @see org.springframework.web.bind.annotation.RequestMapping - * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandler.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandler.java index 98cbd6a895..943b81995c 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandler.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/ExceptionHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -24,8 +24,7 @@ import java.lang.annotation.Target; /** * Annotation for handling exceptions in specific handler classes and/or - * handler methods. Provides consistent style between Servlet and Portlet - * environments, with the semantics adapting to the concrete environment. + * handler methods. * *

Handler methods which are annotated with this annotation are allowed to * have very flexible signatures. They may have parameters of the following @@ -34,16 +33,10 @@ import java.lang.annotation.Target; *

  • An exception argument: declared as a general Exception or as a more * specific exception. This also serves as a mapping hint if the annotation * itself does not narrow the exception types through its {@link #value()}. - *
  • Request and/or response objects (Servlet API or Portlet API). + *
  • Request and/or response objects (typically from the Servlet API). * You may choose any specific request/response type, e.g. - * {@link javax.servlet.ServletRequest} / {@link javax.servlet.http.HttpServletRequest} - * or {@link javax.portlet.PortletRequest} / {@link javax.portlet.ActionRequest} / - * {@link javax.portlet.RenderRequest}. Note that in the Portlet case, - * an explicitly declared action/render argument is also used for mapping - * specific request types onto a handler method (in case of no other - * information given that differentiates between action and render requests). - *
  • Session object (Servlet API or Portlet API): either - * {@link javax.servlet.http.HttpSession} or {@link javax.portlet.PortletSession}. + * {@link javax.servlet.ServletRequest} / {@link javax.servlet.http.HttpServletRequest}. + *
  • Session object: typically {@link javax.servlet.http.HttpSession}. * An argument of this type will enforce the presence of a corresponding session. * As a consequence, such an argument will never be {@code null}. * Note that session access may not be thread-safe, in particular in a @@ -54,17 +47,17 @@ import java.lang.annotation.Target; *
  • {@link org.springframework.web.context.request.WebRequest} or * {@link org.springframework.web.context.request.NativeWebRequest}. * Allows for generic request parameter access as well as request/session - * attribute access, without ties to the native Servlet/Portlet API. + * attribute access, without ties to the native Servlet API. *
  • {@link java.util.Locale} for the current request locale * (determined by the most specific locale resolver available, * i.e. the configured {@link org.springframework.web.servlet.LocaleResolver} - * in a Servlet environment and the portal locale in a Portlet environment). + * in a Servlet environment). *
  • {@link java.io.InputStream} / {@link java.io.Reader} for access * to the request's content. This will be the raw InputStream/Reader as - * exposed by the Servlet/Portlet API. + * exposed by the Servlet API. *
  • {@link java.io.OutputStream} / {@link java.io.Writer} for generating * the response's content. This will be the raw OutputStream/Writer as - * exposed by the Servlet/Portlet API. + * exposed by the Servlet API. *
  • {@link org.springframework.ui.Model} as an alternative to returning * a model map from the handler method. Note that the provided model is not * pre-populated with regular model attributes and therefore always empty, @@ -73,7 +66,7 @@ import java.lang.annotation.Target; * *

    The following return types are supported for handler methods: *

      - *
    • A {@code ModelAndView} object (Servlet MVC or Portlet MVC). + *
    • A {@code ModelAndView} object (from Servlet MVC). *
    • A {@link org.springframework.ui.Model} object, with the view name implicitly * determined through a {@link org.springframework.web.servlet.RequestToViewNameTranslator}. *
    • A {@link java.util.Map} object for exposing a model, @@ -93,30 +86,19 @@ import java.lang.annotation.Target; *
    • {@code void} if the method handles the response itself (by * writing the response content directly, declaring an argument of type * {@link javax.servlet.ServletResponse} / {@link javax.servlet.http.HttpServletResponse} - * / {@link javax.portlet.RenderResponse} for that purpose) - * or if the view name is supposed to be implicitly determined through a - * {@link org.springframework.web.servlet.RequestToViewNameTranslator} - * (not declaring a response argument in the handler method signature; - * only applicable in a Servlet environment). + * for that purpose) or if the view name is supposed to be implicitly determined + * through a {@link org.springframework.web.servlet.RequestToViewNameTranslator} + * (not declaring a response argument in the handler method signature). *
    * *

    In Servlet environments, you can combine the {@code ExceptionHandler} annotation * with {@link ResponseStatus @ResponseStatus}, to define the response status * for the HTTP response. * - *

    Note: In Portlet environments, {@code ExceptionHandler} annotated methods - * will only be called during the render and resource phases - just like - * {@link org.springframework.web.portlet.HandlerExceptionResolver} beans would. - * Exceptions carried over from the action and event phases will be invoked during - * the render phase as well, with exception handler methods having to be present - * on the controller class that defines the applicable render method. - * * @author Arjen Poutsma * @author Juergen Hoeller * @since 3.0 * @see org.springframework.web.context.request.WebRequest - * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java index b7203f2fe2..a01ad44a2c 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -40,8 +40,6 @@ import org.springframework.core.annotation.AliasFor; * @see RequestMapping * @see RequestParam * @see CookieValue - * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java index cda331c4b8..0e756a2c1e 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java @@ -27,34 +27,17 @@ import org.springframework.core.annotation.AliasFor; /** * Annotation for mapping web requests onto specific handler classes and/or - * handler methods. Provides a consistent style between Servlet and Portlet - * environments, with the semantics adapting to the concrete environment. - * - *

    NOTE: The set of features supported for Servlets is a superset - * of the set of features supported for Portlets. The places where this applies - * are marked with the label "Servlet-only" in this source file. For Servlet - * environments there are some further distinctions depending on whether an - * application is configured with {@literal "@MVC 3.0"} or - * {@literal "@MVC 3.1"} support classes. The places where this applies are - * marked with {@literal "@MVC 3.1-only"} in this source file. For more - * details see the note on the new support classes added in Spring MVC 3.1 - * further below. + * handler methods. * *

    Handler methods which are annotated with this annotation are allowed to * have very flexible signatures. They may have parameters of the following * types, in arbitrary order (except for validation results, which need to * follow right after the corresponding command object, if desired): *

      - *
    • Request and/or response objects (Servlet API or Portlet API). + *
    • Request and/or response objects (typically from the Servlet API). * You may choose any specific request/response type, e.g. - * {@link javax.servlet.ServletRequest} / {@link javax.servlet.http.HttpServletRequest} - * or {@link javax.portlet.PortletRequest} / {@link javax.portlet.ActionRequest} / - * {@link javax.portlet.RenderRequest}. Note that in the Portlet case, - * an explicitly declared action/render argument is also used for mapping - * specific request types onto a handler method (in case of no other - * information given that differentiates between action and render requests). - *
    • Session object (Servlet API or Portlet API): either - * {@link javax.servlet.http.HttpSession} or {@link javax.portlet.PortletSession}. + * {@link javax.servlet.ServletRequest} / {@link javax.servlet.http.HttpServletRequest}. + *
    • Session object: typically {@link javax.servlet.http.HttpSession}. * An argument of this type will enforce the presence of a corresponding session. * As a consequence, such an argument will never be {@code null}. * Note that session access may not be thread-safe, in particular in a @@ -65,17 +48,17 @@ import org.springframework.core.annotation.AliasFor; *
    • {@link org.springframework.web.context.request.WebRequest} or * {@link org.springframework.web.context.request.NativeWebRequest}. * Allows for generic request parameter access as well as request/session - * attribute access, without ties to the native Servlet/Portlet API. + * attribute access, without ties to the native Servlet API. *
    • {@link java.util.Locale} for the current request locale * (determined by the most specific locale resolver available, * i.e. the configured {@link org.springframework.web.servlet.LocaleResolver} - * in a Servlet environment and the portal locale in a Portlet environment). + * in a Servlet environment). *
    • {@link java.io.InputStream} / {@link java.io.Reader} for access * to the request's content. This will be the raw InputStream/Reader as - * exposed by the Servlet/Portlet API. + * exposed by the Servlet API. *
    • {@link java.io.OutputStream} / {@link java.io.Writer} for generating * the response's content. This will be the raw OutputStream/Writer as - * exposed by the Servlet/Portlet API. + * exposed by the Servlet API. *
    • {@link org.springframework.http.HttpMethod} for the HTTP request method
    • *
    • {@link PathVariable @PathVariable} annotated parameters (Servlet-only) * for access to URI template values (i.e. /hotels/{hotel}). Variable values will be @@ -94,13 +77,13 @@ import org.springframework.core.annotation.AliasFor; * {@link java.util.Map Map<String, String>} to gain access to all * matrix variables in the URL or to those in a specific path variable. *
    • {@link RequestParam @RequestParam} annotated parameters for access to - * specific Servlet/Portlet request parameters. Parameter values will be + * specific Servlet request parameters. Parameter values will be * converted to the declared method argument type. Additionally, * {@code @RequestParam} can be used on a {@link java.util.Map Map<String, String>} or * {@link org.springframework.util.MultiValueMap MultiValueMap<String, String>} * method parameter to gain access to all request parameters. *
    • {@link RequestHeader @RequestHeader} annotated parameters for access to - * specific Servlet/Portlet request HTTP headers. Parameter values will be + * specific Servlet request HTTP headers. Parameter values will be * converted to the declared method argument type. Additionally, * {@code @RequestHeader} can be used on a {@link java.util.Map Map<String, String>}, * {@link org.springframework.util.MultiValueMap MultiValueMap<String, String>}, or @@ -177,7 +160,7 @@ import org.springframework.core.annotation.AliasFor; * *

      The following return types are supported for handler methods: *

        - *
      • A {@code ModelAndView} object (Servlet MVC or Portlet MVC), + *
      • A {@code ModelAndView} object (from Servlet MVC), * with the model implicitly enriched with command objects and the results * of {@link ModelAttribute @ModelAttribute} annotated reference data accessor methods. *
      • A {@link org.springframework.ui.Model Model} object, with the view name implicitly @@ -238,11 +221,9 @@ import org.springframework.core.annotation.AliasFor; *
      • {@code void} if the method handles the response itself (by * writing the response content directly, declaring an argument of type * {@link javax.servlet.ServletResponse} / {@link javax.servlet.http.HttpServletResponse} - * / {@link javax.portlet.RenderResponse} for that purpose) - * or if the view name is supposed to be implicitly determined through a - * {@link org.springframework.web.servlet.RequestToViewNameTranslator} - * (not declaring a response argument in the handler method signature; - * only applicable in a Servlet environment). + * for that purpose) or if the view name is supposed to be implicitly determined + * through a {@link org.springframework.web.servlet.RequestToViewNameTranslator} + * (not declaring a response argument in the handler method signature). *
      • Any other return type will be considered as single model attribute * to be exposed to the view, using the attribute name specified through * {@link ModelAttribute @ModelAttribute} at the method level (or the default attribute @@ -253,9 +234,7 @@ import org.springframework.core.annotation.AliasFor; * *

        NOTE: {@code @RequestMapping} will only be processed if an * an appropriate {@code HandlerMapping}-{@code HandlerAdapter} pair - * is configured. This is the case by default in both the - * {@code DispatcherServlet} and the {@code DispatcherPortlet}. - * However, if you are defining custom {@code HandlerMappings} or + * is configured. If you are defining custom {@code HandlerMappings} or * {@code HandlerAdapters}, then you need to add * {@code DefaultAnnotationHandlerMapping} and * {@code AnnotationMethodHandlerAdapter} to your configuration.. @@ -293,8 +272,6 @@ import org.springframework.core.annotation.AliasFor; * @see InitBinder * @see org.springframework.web.context.request.WebRequest * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - * @see org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping - * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @@ -314,11 +291,9 @@ public @interface RequestMapping { /** * The primary mapping expressed by this annotation. - *

        In a Servlet environment this is an alias for {@link #path}. - * For example {@code @RequestMapping("/foo")} is equivalent to + *

        This is an alias for {@link #path}. For example + * {@code @RequestMapping("/foo")} is equivalent to * {@code @RequestMapping(path="/foo")}. - *

        In a Portlet environment this is the mapped portlet modes - * (i.e. "EDIT", "VIEW", "HELP" or any custom modes). *

        Supported at the type level as well as at the method level! * When used at the type level, all method-level mappings inherit * this primary mapping, narrowing it for a specific handler method. @@ -348,7 +323,6 @@ public @interface RequestMapping { * When used at the type level, all method-level mappings inherit * this HTTP method restriction (i.e. the type-level restriction * gets checked before the handler method is even resolved). - *

        Supported for Servlet environments as well as Portlet 2.0 environments. */ RequestMethod[] method() default {}; @@ -365,14 +339,10 @@ public @interface RequestMapping { * When used at the type level, all method-level mappings inherit * this parameter restriction (i.e. the type-level restriction * gets checked before the handler method is even resolved). - *

        In a Servlet environment, parameter mappings are considered as restrictions - * that are enforced at the type level. The primary path mapping (i.e. the - * specified URI value) still has to uniquely identify the target handler, with - * parameter mappings simply expressing preconditions for invoking the handler. - *

        In a Portlet environment, parameters are taken into account as mapping - * differentiators, i.e. the primary portlet mode mapping plus the parameter - * conditions uniquely identify the target handler. Different handlers may be - * mapped onto the same portlet mode, as long as their parameter mappings differ. + *

        Parameter mappings are considered as restrictions that are enforced at + * the type level. The primary path mapping (i.e. the specified URI value) + * still has to uniquely identify the target handler, with parameter mappings + * simply expressing preconditions for invoking the handler. */ String[] params() default {}; @@ -395,8 +365,6 @@ public @interface RequestMapping { * When used at the type level, all method-level mappings inherit * this header restriction (i.e. the type-level restriction * gets checked before the handler method is even resolved). - *

        Maps against HttpServletRequest headers in a Servlet environment, - * and against PortletRequest properties in a Portlet 2.0 environment. * @see org.springframework.http.MediaType */ String[] headers() default {}; diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java index 9c5e2a03d1..3287a3258c 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -47,9 +47,6 @@ import org.springframework.core.annotation.AliasFor; * @see RequestMapping * @see RequestHeader * @see CookieValue - * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter - * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvocationException.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvocationException.java deleted file mode 100644 index 52850cd38d..0000000000 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvocationException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2002-2012 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.bind.annotation.support; - -import java.lang.reflect.Method; - -import org.springframework.core.NestedRuntimeException; - -/** - * Exception indicating that the execution of an annotated MVC handler method failed. - * - * @author Juergen Hoeller - * @since 2.5.6 - * @see HandlerMethodInvoker#invokeHandlerMethod - * @deprecated as of 4.3, in favor of the {@code HandlerMethod}-based MVC infrastructure - */ -@Deprecated -@SuppressWarnings("serial") -public class HandlerMethodInvocationException extends NestedRuntimeException { - - /** - * Create a new HandlerMethodInvocationException for the given Method handle and cause. - * @param handlerMethod the handler method handle - * @param cause the cause of the invocation failure - */ - public HandlerMethodInvocationException(Method handlerMethod, Throwable cause) { - super("Failed to invoke handler method [" + handlerMethod + "]", cause); - } - -} diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java deleted file mode 100644 index 9287882baf..0000000000 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodInvoker.java +++ /dev/null @@ -1,901 +0,0 @@ -/* - * Copyright 2002-2015 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.bind.annotation.support; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.BridgeMethodResolver; -import org.springframework.core.Conventions; -import org.springframework.core.GenericTypeResolver; -import org.springframework.core.MethodParameter; -import org.springframework.core.ParameterNameDiscoverer; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.annotation.SynthesizingMethodParameter; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.MediaType; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.ui.ExtendedModelMap; -import org.springframework.ui.Model; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.util.ReflectionUtils; -import org.springframework.validation.BindException; -import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ValueConstants; -import org.springframework.web.bind.support.DefaultSessionAttributeStore; -import org.springframework.web.bind.support.SessionAttributeStore; -import org.springframework.web.bind.support.SessionStatus; -import org.springframework.web.bind.support.SimpleSessionStatus; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.bind.support.WebBindingInitializer; -import org.springframework.web.bind.support.WebRequestDataBinder; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.multipart.MultipartRequest; - -/** - * Support class for invoking an annotated handler method. Operates on the introspection - * results of a {@link HandlerMethodResolver} for a specific handler type. - * - *

        Used by {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter} - * and {@link org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter}. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @since 2.5.2 - * @see #invokeHandlerMethod - * @deprecated as of 4.3, in favor of the {@code HandlerMethod}-based MVC infrastructure - */ -@Deprecated -public class HandlerMethodInvoker { - - private static final String MODEL_KEY_PREFIX_STALE = SessionAttributeStore.class.getName() + ".STALE."; - - /** We'll create a lot of these objects, so we don't want a new logger every time. */ - private static final Log logger = LogFactory.getLog(HandlerMethodInvoker.class); - - private final HandlerMethodResolver methodResolver; - - private final WebBindingInitializer bindingInitializer; - - private final SessionAttributeStore sessionAttributeStore; - - private final ParameterNameDiscoverer parameterNameDiscoverer; - - private final WebArgumentResolver[] customArgumentResolvers; - - private final HttpMessageConverter[] messageConverters; - - private final SimpleSessionStatus sessionStatus = new SimpleSessionStatus(); - - - public HandlerMethodInvoker(HandlerMethodResolver methodResolver) { - this(methodResolver, null); - } - - public HandlerMethodInvoker(HandlerMethodResolver methodResolver, WebBindingInitializer bindingInitializer) { - this(methodResolver, bindingInitializer, new DefaultSessionAttributeStore(), null, null, null); - } - - public HandlerMethodInvoker(HandlerMethodResolver methodResolver, WebBindingInitializer bindingInitializer, - SessionAttributeStore sessionAttributeStore, ParameterNameDiscoverer parameterNameDiscoverer, - WebArgumentResolver[] customArgumentResolvers, HttpMessageConverter[] messageConverters) { - - this.methodResolver = methodResolver; - this.bindingInitializer = bindingInitializer; - this.sessionAttributeStore = sessionAttributeStore; - this.parameterNameDiscoverer = parameterNameDiscoverer; - this.customArgumentResolvers = customArgumentResolvers; - this.messageConverters = messageConverters; - } - - - public final Object invokeHandlerMethod(Method handlerMethod, Object handler, - NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { - - Method handlerMethodToInvoke = BridgeMethodResolver.findBridgedMethod(handlerMethod); - try { - boolean debug = logger.isDebugEnabled(); - for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { - Object attrValue = this.sessionAttributeStore.retrieveAttribute(webRequest, attrName); - if (attrValue != null) { - implicitModel.addAttribute(attrName, attrValue); - } - } - for (Method attributeMethod : this.methodResolver.getModelAttributeMethods()) { - Method attributeMethodToInvoke = BridgeMethodResolver.findBridgedMethod(attributeMethod); - Object[] args = resolveHandlerArguments(attributeMethodToInvoke, handler, webRequest, implicitModel); - if (debug) { - logger.debug("Invoking model attribute method: " + attributeMethodToInvoke); - } - String attrName = AnnotationUtils.findAnnotation(attributeMethod, ModelAttribute.class).value(); - if (!"".equals(attrName) && implicitModel.containsAttribute(attrName)) { - continue; - } - ReflectionUtils.makeAccessible(attributeMethodToInvoke); - Object attrValue = attributeMethodToInvoke.invoke(handler, args); - if ("".equals(attrName)) { - Class resolvedType = GenericTypeResolver.resolveReturnType(attributeMethodToInvoke, handler.getClass()); - attrName = Conventions.getVariableNameForReturnType(attributeMethodToInvoke, resolvedType, attrValue); - } - if (!implicitModel.containsAttribute(attrName)) { - implicitModel.addAttribute(attrName, attrValue); - } - } - Object[] args = resolveHandlerArguments(handlerMethodToInvoke, handler, webRequest, implicitModel); - if (debug) { - logger.debug("Invoking request handler method: " + handlerMethodToInvoke); - } - ReflectionUtils.makeAccessible(handlerMethodToInvoke); - return handlerMethodToInvoke.invoke(handler, args); - } - catch (IllegalStateException ex) { - // Internal assertion failed (e.g. invalid signature): - // throw exception with full handler method context... - throw new HandlerMethodInvocationException(handlerMethodToInvoke, ex); - } - catch (InvocationTargetException ex) { - // User-defined @ModelAttribute/@InitBinder/@RequestMapping method threw an exception... - ReflectionUtils.rethrowException(ex.getTargetException()); - return null; - } - } - - public final void updateModelAttributes(Object handler, Map mavModel, - ExtendedModelMap implicitModel, NativeWebRequest webRequest) throws Exception { - - if (this.methodResolver.hasSessionAttributes() && this.sessionStatus.isComplete()) { - for (String attrName : this.methodResolver.getActualSessionAttributeNames()) { - this.sessionAttributeStore.cleanupAttribute(webRequest, attrName); - } - } - - // Expose model attributes as session attributes, if required. - // Expose BindingResults for all attributes, making custom editors available. - Map model = (mavModel != null ? mavModel : implicitModel); - if (model != null) { - try { - String[] originalAttrNames = model.keySet().toArray(new String[model.size()]); - for (String attrName : originalAttrNames) { - Object attrValue = model.get(attrName); - boolean isSessionAttr = this.methodResolver.isSessionAttribute( - attrName, (attrValue != null ? attrValue.getClass() : null)); - if (isSessionAttr) { - if (this.sessionStatus.isComplete()) { - implicitModel.put(MODEL_KEY_PREFIX_STALE + attrName, Boolean.TRUE); - } - else if (!implicitModel.containsKey(MODEL_KEY_PREFIX_STALE + attrName)) { - this.sessionAttributeStore.storeAttribute(webRequest, attrName, attrValue); - } - } - if (!attrName.startsWith(BindingResult.MODEL_KEY_PREFIX) && - (isSessionAttr || isBindingCandidate(attrValue))) { - String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + attrName; - if (mavModel != null && !model.containsKey(bindingResultKey)) { - WebDataBinder binder = createBinder(webRequest, attrValue, attrName); - initBinder(handler, attrName, binder, webRequest); - mavModel.put(bindingResultKey, binder.getBindingResult()); - } - } - } - } - catch (InvocationTargetException ex) { - // User-defined @InitBinder method threw an exception... - ReflectionUtils.rethrowException(ex.getTargetException()); - } - } - } - - - private Object[] resolveHandlerArguments(Method handlerMethod, Object handler, - NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception { - - Class[] paramTypes = handlerMethod.getParameterTypes(); - Object[] args = new Object[paramTypes.length]; - - for (int i = 0; i < args.length; i++) { - MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i); - methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer); - GenericTypeResolver.resolveParameterType(methodParam, handler.getClass()); - String paramName = null; - String headerName = null; - boolean requestBodyFound = false; - String cookieName = null; - String pathVarName = null; - String attrName = null; - boolean required = false; - String defaultValue = null; - boolean validate = false; - Object[] validationHints = null; - int annotationsFound = 0; - Annotation[] paramAnns = methodParam.getParameterAnnotations(); - - for (Annotation paramAnn : paramAnns) { - if (RequestParam.class.isInstance(paramAnn)) { - RequestParam requestParam = (RequestParam) paramAnn; - paramName = requestParam.name(); - required = requestParam.required(); - defaultValue = parseDefaultValueAttribute(requestParam.defaultValue()); - annotationsFound++; - } - else if (RequestHeader.class.isInstance(paramAnn)) { - RequestHeader requestHeader = (RequestHeader) paramAnn; - headerName = requestHeader.name(); - required = requestHeader.required(); - defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue()); - annotationsFound++; - } - else if (RequestBody.class.isInstance(paramAnn)) { - requestBodyFound = true; - annotationsFound++; - } - else if (CookieValue.class.isInstance(paramAnn)) { - CookieValue cookieValue = (CookieValue) paramAnn; - cookieName = cookieValue.name(); - required = cookieValue.required(); - defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue()); - annotationsFound++; - } - else if (PathVariable.class.isInstance(paramAnn)) { - PathVariable pathVar = (PathVariable) paramAnn; - pathVarName = pathVar.value(); - annotationsFound++; - } - else if (ModelAttribute.class.isInstance(paramAnn)) { - ModelAttribute attr = (ModelAttribute) paramAnn; - attrName = attr.value(); - annotationsFound++; - } - else if (Value.class.isInstance(paramAnn)) { - defaultValue = ((Value) paramAnn).value(); - } - else { - Validated validatedAnn = AnnotationUtils.getAnnotation(paramAnn, Validated.class); - if (validatedAnn != null || paramAnn.annotationType().getSimpleName().startsWith("Valid")) { - validate = true; - Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(paramAnn)); - validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[]{hints}); - } - } - } - - if (annotationsFound > 1) { - throw new IllegalStateException("Handler parameter annotations are exclusive choices - " + - "do not specify more than one such annotation on the same parameter: " + handlerMethod); - } - - if (annotationsFound == 0) { - Object argValue = resolveCommonArgument(methodParam, webRequest); - if (argValue != WebArgumentResolver.UNRESOLVED) { - args[i] = argValue; - } - else if (defaultValue != null) { - args[i] = resolveDefaultValue(defaultValue); - } - else { - Class paramType = methodParam.getParameterType(); - if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) { - if (!paramType.isAssignableFrom(implicitModel.getClass())) { - throw new IllegalStateException("Argument [" + paramType.getSimpleName() + "] is of type " + - "Model or Map but is not assignable from the actual model. You may need to switch " + - "newer MVC infrastructure classes to use this argument."); - } - args[i] = implicitModel; - } - else if (SessionStatus.class.isAssignableFrom(paramType)) { - args[i] = this.sessionStatus; - } - else if (HttpEntity.class.isAssignableFrom(paramType)) { - args[i] = resolveHttpEntityRequest(methodParam, webRequest); - } - else if (Errors.class.isAssignableFrom(paramType)) { - throw new IllegalStateException("Errors/BindingResult argument declared " + - "without preceding model attribute. Check your handler method signature!"); - } - else if (BeanUtils.isSimpleProperty(paramType)) { - paramName = ""; - } - else { - attrName = ""; - } - } - } - - if (paramName != null) { - args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler); - } - else if (headerName != null) { - args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler); - } - else if (requestBodyFound) { - args[i] = resolveRequestBody(methodParam, webRequest, handler); - } - else if (cookieName != null) { - args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler); - } - else if (pathVarName != null) { - args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler); - } - else if (attrName != null) { - WebDataBinder binder = - resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler); - boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1])); - if (binder.getTarget() != null) { - doBind(binder, webRequest, validate, validationHints, !assignBindingResult); - } - args[i] = binder.getTarget(); - if (assignBindingResult) { - args[i + 1] = binder.getBindingResult(); - i++; - } - implicitModel.putAll(binder.getBindingResult().getModel()); - } - } - - return args; - } - - protected void initBinder(Object handler, String attrName, WebDataBinder binder, NativeWebRequest webRequest) - throws Exception { - - if (this.bindingInitializer != null) { - this.bindingInitializer.initBinder(binder, webRequest); - } - if (handler != null) { - Set initBinderMethods = this.methodResolver.getInitBinderMethods(); - if (!initBinderMethods.isEmpty()) { - boolean debug = logger.isDebugEnabled(); - for (Method initBinderMethod : initBinderMethods) { - Method methodToInvoke = BridgeMethodResolver.findBridgedMethod(initBinderMethod); - String[] targetNames = AnnotationUtils.findAnnotation(initBinderMethod, InitBinder.class).value(); - if (targetNames.length == 0 || Arrays.asList(targetNames).contains(attrName)) { - Object[] initBinderArgs = - resolveInitBinderArguments(handler, methodToInvoke, binder, webRequest); - if (debug) { - logger.debug("Invoking init-binder method: " + methodToInvoke); - } - ReflectionUtils.makeAccessible(methodToInvoke); - Object returnValue = methodToInvoke.invoke(handler, initBinderArgs); - if (returnValue != null) { - throw new IllegalStateException( - "InitBinder methods must not have a return value: " + methodToInvoke); - } - } - } - } - } - } - - private Object[] resolveInitBinderArguments(Object handler, Method initBinderMethod, - WebDataBinder binder, NativeWebRequest webRequest) throws Exception { - - Class[] initBinderParams = initBinderMethod.getParameterTypes(); - Object[] initBinderArgs = new Object[initBinderParams.length]; - - for (int i = 0; i < initBinderArgs.length; i++) { - MethodParameter methodParam = new SynthesizingMethodParameter(initBinderMethod, i); - methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer); - GenericTypeResolver.resolveParameterType(methodParam, handler.getClass()); - String paramName = null; - boolean paramRequired = false; - String paramDefaultValue = null; - String pathVarName = null; - Annotation[] paramAnns = methodParam.getParameterAnnotations(); - - for (Annotation paramAnn : paramAnns) { - if (RequestParam.class.isInstance(paramAnn)) { - RequestParam requestParam = (RequestParam) paramAnn; - paramName = requestParam.name(); - paramRequired = requestParam.required(); - paramDefaultValue = parseDefaultValueAttribute(requestParam.defaultValue()); - break; - } - else if (ModelAttribute.class.isInstance(paramAnn)) { - throw new IllegalStateException( - "@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod); - } - else if (PathVariable.class.isInstance(paramAnn)) { - PathVariable pathVar = (PathVariable) paramAnn; - pathVarName = pathVar.value(); - } - } - - if (paramName == null && pathVarName == null) { - Object argValue = resolveCommonArgument(methodParam, webRequest); - if (argValue != WebArgumentResolver.UNRESOLVED) { - initBinderArgs[i] = argValue; - } - else { - Class paramType = initBinderParams[i]; - if (paramType.isInstance(binder)) { - initBinderArgs[i] = binder; - } - else if (BeanUtils.isSimpleProperty(paramType)) { - paramName = ""; - } - else { - throw new IllegalStateException("Unsupported argument [" + paramType.getName() + - "] for @InitBinder method: " + initBinderMethod); - } - } - } - - if (paramName != null) { - initBinderArgs[i] = - resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null); - } - else if (pathVarName != null) { - initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null); - } - } - - return initBinderArgs; - } - - @SuppressWarnings("unchecked") - private Object resolveRequestParam(String paramName, boolean required, String defaultValue, - MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) - throws Exception { - - Class paramType = methodParam.getParameterType(); - if (Map.class.isAssignableFrom(paramType) && paramName.length() == 0) { - return resolveRequestParamMap((Class>) paramType, webRequest); - } - if (paramName.length() == 0) { - paramName = getRequiredParameterName(methodParam); - } - Object paramValue = null; - MultipartRequest multipartRequest = webRequest.getNativeRequest(MultipartRequest.class); - if (multipartRequest != null) { - List files = multipartRequest.getFiles(paramName); - if (!files.isEmpty()) { - paramValue = (files.size() == 1 ? files.get(0) : files); - } - } - if (paramValue == null) { - String[] paramValues = webRequest.getParameterValues(paramName); - if (paramValues != null) { - paramValue = (paramValues.length == 1 ? paramValues[0] : paramValues); - } - } - if (paramValue == null) { - if (defaultValue != null) { - paramValue = resolveDefaultValue(defaultValue); - } - else if (required) { - raiseMissingParameterException(paramName, paramType); - } - paramValue = checkValue(paramName, paramValue, paramType); - } - WebDataBinder binder = createBinder(webRequest, null, paramName); - initBinder(handlerForInitBinderCall, paramName, binder, webRequest); - return binder.convertIfNecessary(paramValue, paramType, methodParam); - } - - private Map resolveRequestParamMap(Class> mapType, NativeWebRequest webRequest) { - Map parameterMap = webRequest.getParameterMap(); - if (MultiValueMap.class.isAssignableFrom(mapType)) { - MultiValueMap result = new LinkedMultiValueMap(parameterMap.size()); - for (Map.Entry entry : parameterMap.entrySet()) { - for (String value : entry.getValue()) { - result.add(entry.getKey(), value); - } - } - return result; - } - else { - Map result = new LinkedHashMap(parameterMap.size()); - for (Map.Entry entry : parameterMap.entrySet()) { - if (entry.getValue().length > 0) { - result.put(entry.getKey(), entry.getValue()[0]); - } - } - return result; - } - } - - @SuppressWarnings("unchecked") - private Object resolveRequestHeader(String headerName, boolean required, String defaultValue, - MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) - throws Exception { - - Class paramType = methodParam.getParameterType(); - if (Map.class.isAssignableFrom(paramType)) { - return resolveRequestHeaderMap((Class>) paramType, webRequest); - } - if (headerName.length() == 0) { - headerName = getRequiredParameterName(methodParam); - } - Object headerValue = null; - String[] headerValues = webRequest.getHeaderValues(headerName); - if (headerValues != null) { - headerValue = (headerValues.length == 1 ? headerValues[0] : headerValues); - } - if (headerValue == null) { - if (defaultValue != null) { - headerValue = resolveDefaultValue(defaultValue); - } - else if (required) { - raiseMissingHeaderException(headerName, paramType); - } - headerValue = checkValue(headerName, headerValue, paramType); - } - WebDataBinder binder = createBinder(webRequest, null, headerName); - initBinder(handlerForInitBinderCall, headerName, binder, webRequest); - return binder.convertIfNecessary(headerValue, paramType, methodParam); - } - - private Map resolveRequestHeaderMap(Class> mapType, NativeWebRequest webRequest) { - if (MultiValueMap.class.isAssignableFrom(mapType)) { - MultiValueMap result; - if (HttpHeaders.class.isAssignableFrom(mapType)) { - result = new HttpHeaders(); - } - else { - result = new LinkedMultiValueMap(); - } - for (Iterator iterator = webRequest.getHeaderNames(); iterator.hasNext();) { - String headerName = iterator.next(); - for (String headerValue : webRequest.getHeaderValues(headerName)) { - result.add(headerName, headerValue); - } - } - return result; - } - else { - Map result = new LinkedHashMap(); - for (Iterator iterator = webRequest.getHeaderNames(); iterator.hasNext();) { - String headerName = iterator.next(); - String headerValue = webRequest.getHeader(headerName); - result.put(headerName, headerValue); - } - return result; - } - } - - /** - * Resolves the given {@link RequestBody @RequestBody} annotation. - */ - protected Object resolveRequestBody(MethodParameter methodParam, NativeWebRequest webRequest, Object handler) - throws Exception { - - return readWithMessageConverters(methodParam, createHttpInputMessage(webRequest), methodParam.getParameterType()); - } - - private HttpEntity resolveHttpEntityRequest(MethodParameter methodParam, NativeWebRequest webRequest) - throws Exception { - - HttpInputMessage inputMessage = createHttpInputMessage(webRequest); - Class paramType = getHttpEntityType(methodParam); - Object body = readWithMessageConverters(methodParam, inputMessage, paramType); - return new HttpEntity(body, inputMessage.getHeaders()); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private Object readWithMessageConverters(MethodParameter methodParam, HttpInputMessage inputMessage, Class paramType) - throws Exception { - - MediaType contentType = inputMessage.getHeaders().getContentType(); - if (contentType == null) { - StringBuilder builder = new StringBuilder(ClassUtils.getShortName(methodParam.getParameterType())); - String paramName = methodParam.getParameterName(); - if (paramName != null) { - builder.append(' '); - builder.append(paramName); - } - throw new HttpMediaTypeNotSupportedException( - "Cannot extract parameter (" + builder.toString() + "): no Content-Type found"); - } - - List allSupportedMediaTypes = new ArrayList(); - if (this.messageConverters != null) { - for (HttpMessageConverter messageConverter : this.messageConverters) { - allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); - if (messageConverter.canRead(paramType, contentType)) { - if (logger.isDebugEnabled()) { - logger.debug("Reading [" + paramType.getName() + "] as \"" + contentType - +"\" using [" + messageConverter + "]"); - } - return messageConverter.read((Class) paramType, inputMessage); - } - } - } - throw new HttpMediaTypeNotSupportedException(contentType, allSupportedMediaTypes); - } - - private Class getHttpEntityType(MethodParameter methodParam) { - Assert.isAssignable(HttpEntity.class, methodParam.getParameterType()); - ParameterizedType type = (ParameterizedType) methodParam.getGenericParameterType(); - if (type.getActualTypeArguments().length == 1) { - Type typeArgument = type.getActualTypeArguments()[0]; - if (typeArgument instanceof Class) { - return (Class) typeArgument; - } - else if (typeArgument instanceof GenericArrayType) { - Type componentType = ((GenericArrayType) typeArgument).getGenericComponentType(); - if (componentType instanceof Class) { - // Surely, there should be a nicer way to do this - Object array = Array.newInstance((Class) componentType, 0); - return array.getClass(); - } - } - } - throw new IllegalArgumentException( - "HttpEntity parameter (" + methodParam.getParameterName() + ") is not parameterized"); - - } - - private Object resolveCookieValue(String cookieName, boolean required, String defaultValue, - MethodParameter methodParam, NativeWebRequest webRequest, Object handlerForInitBinderCall) - throws Exception { - - Class paramType = methodParam.getParameterType(); - if (cookieName.length() == 0) { - cookieName = getRequiredParameterName(methodParam); - } - Object cookieValue = resolveCookieValue(cookieName, paramType, webRequest); - if (cookieValue == null) { - if (defaultValue != null) { - cookieValue = resolveDefaultValue(defaultValue); - } - else if (required) { - raiseMissingCookieException(cookieName, paramType); - } - cookieValue = checkValue(cookieName, cookieValue, paramType); - } - WebDataBinder binder = createBinder(webRequest, null, cookieName); - initBinder(handlerForInitBinderCall, cookieName, binder, webRequest); - return binder.convertIfNecessary(cookieValue, paramType, methodParam); - } - - /** - * Resolves the given {@link CookieValue @CookieValue} annotation. - *

        Throws an UnsupportedOperationException by default. - */ - protected Object resolveCookieValue(String cookieName, Class paramType, NativeWebRequest webRequest) - throws Exception { - - throw new UnsupportedOperationException("@CookieValue not supported"); - } - - private Object resolvePathVariable(String pathVarName, MethodParameter methodParam, - NativeWebRequest webRequest, Object handlerForInitBinderCall) throws Exception { - - Class paramType = methodParam.getParameterType(); - if (pathVarName.length() == 0) { - pathVarName = getRequiredParameterName(methodParam); - } - String pathVarValue = resolvePathVariable(pathVarName, paramType, webRequest); - WebDataBinder binder = createBinder(webRequest, null, pathVarName); - initBinder(handlerForInitBinderCall, pathVarName, binder, webRequest); - return binder.convertIfNecessary(pathVarValue, paramType, methodParam); - } - - /** - * Resolves the given {@link PathVariable @PathVariable} annotation. - *

        Throws an UnsupportedOperationException by default. - */ - protected String resolvePathVariable(String pathVarName, Class paramType, NativeWebRequest webRequest) - throws Exception { - - throw new UnsupportedOperationException("@PathVariable not supported"); - } - - private String getRequiredParameterName(MethodParameter methodParam) { - String name = methodParam.getParameterName(); - if (name == null) { - throw new IllegalStateException( - "No parameter name specified for argument of type [" + methodParam.getParameterType().getName() + - "], and no parameter name information found in class file either."); - } - return name; - } - - private Object checkValue(String name, Object value, Class paramType) { - if (value == null) { - if (boolean.class == paramType) { - return Boolean.FALSE; - } - else if (paramType.isPrimitive()) { - throw new IllegalStateException("Optional " + paramType + " parameter '" + name + - "' is not present but cannot be translated into a null value due to being declared as a " + - "primitive type. Consider declaring it as object wrapper for the corresponding primitive type."); - } - } - return value; - } - - private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam, - ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception { - - // Bind request parameter onto object... - String name = attrName; - if ("".equals(name)) { - name = Conventions.getVariableNameForParameter(methodParam); - } - Class paramType = methodParam.getParameterType(); - Object bindObject; - if (implicitModel.containsKey(name)) { - bindObject = implicitModel.get(name); - } - else if (this.methodResolver.isSessionAttribute(name, paramType)) { - bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name); - if (bindObject == null) { - raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session"); - } - } - else { - bindObject = BeanUtils.instantiateClass(paramType); - } - WebDataBinder binder = createBinder(webRequest, bindObject, name); - initBinder(handler, name, binder, webRequest); - return binder; - } - - - /** - * Determine whether the given value qualifies as a "binding candidate", i.e. might potentially be subject to - * bean-style data binding later on. - */ - protected boolean isBindingCandidate(Object value) { - return (value != null && !value.getClass().isArray() && !(value instanceof Collection) && - !(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass())); - } - - protected void raiseMissingParameterException(String paramName, Class paramType) throws Exception { - throw new IllegalStateException("Missing parameter '" + paramName + "' of type [" + paramType.getName() + "]"); - } - - protected void raiseMissingHeaderException(String headerName, Class paramType) throws Exception { - throw new IllegalStateException("Missing header '" + headerName + "' of type [" + paramType.getName() + "]"); - } - - protected void raiseMissingCookieException(String cookieName, Class paramType) throws Exception { - throw new IllegalStateException( - "Missing cookie value '" + cookieName + "' of type [" + paramType.getName() + "]"); - } - - protected void raiseSessionRequiredException(String message) throws Exception { - throw new IllegalStateException(message); - } - - protected WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) - throws Exception { - - return new WebRequestDataBinder(target, objectName); - } - - private void doBind(WebDataBinder binder, NativeWebRequest webRequest, boolean validate, - Object[] validationHints, boolean failOnErrors) throws Exception { - - doBind(binder, webRequest); - if (validate) { - binder.validate(validationHints); - } - if (failOnErrors && binder.getBindingResult().hasErrors()) { - throw new BindException(binder.getBindingResult()); - } - } - - protected void doBind(WebDataBinder binder, NativeWebRequest webRequest) throws Exception { - ((WebRequestDataBinder) binder).bind(webRequest); - } - - /** - * Return a {@link HttpInputMessage} for the given {@link NativeWebRequest}. - *

        Throws an UnsupportedOperation1Exception by default. - */ - protected HttpInputMessage createHttpInputMessage(NativeWebRequest webRequest) throws Exception { - throw new UnsupportedOperationException("@RequestBody not supported"); - } - - /** - * Return a {@link HttpOutputMessage} for the given {@link NativeWebRequest}. - *

        Throws an UnsupportedOperationException by default. - */ - protected HttpOutputMessage createHttpOutputMessage(NativeWebRequest webRequest) throws Exception { - throw new UnsupportedOperationException("@Body not supported"); - } - - protected String parseDefaultValueAttribute(String value) { - return (ValueConstants.DEFAULT_NONE.equals(value) ? null : value); - } - - protected Object resolveDefaultValue(String value) { - return value; - } - - protected Object resolveCommonArgument(MethodParameter methodParameter, NativeWebRequest webRequest) - throws Exception { - - // Invoke custom argument resolvers if present... - if (this.customArgumentResolvers != null) { - for (WebArgumentResolver argumentResolver : this.customArgumentResolvers) { - Object value = argumentResolver.resolveArgument(methodParameter, webRequest); - if (value != WebArgumentResolver.UNRESOLVED) { - return value; - } - } - } - - // Resolution of standard parameter types... - Class paramType = methodParameter.getParameterType(); - Object value = resolveStandardArgument(paramType, webRequest); - if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) { - throw new IllegalStateException("Standard argument type [" + paramType.getName() + - "] resolved to incompatible value of type [" + (value != null ? value.getClass() : null) + - "]. Consider declaring the argument type in a less specific fashion."); - } - return value; - } - - protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest) throws Exception { - if (WebRequest.class.isAssignableFrom(parameterType)) { - return webRequest; - } - return WebArgumentResolver.UNRESOLVED; - } - - protected final void addReturnValueAsModelAttribute(Method handlerMethod, Class handlerType, - Object returnValue, ExtendedModelMap implicitModel) { - - ModelAttribute attr = AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class); - String attrName = (attr != null ? attr.value() : ""); - if ("".equals(attrName)) { - Class resolvedType = GenericTypeResolver.resolveReturnType(handlerMethod, handlerType); - attrName = Conventions.getVariableNameForReturnType(handlerMethod, resolvedType, returnValue); - } - implicitModel.addAttribute(attrName, returnValue); - } - -} diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodResolver.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodResolver.java deleted file mode 100644 index 53d6584e86..0000000000 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/HandlerMethodResolver.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright 2002-2015 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.bind.annotation.support; - -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.core.BridgeMethodResolver; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; -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.SessionAttributes; - -/** - * Support class for resolving web method annotations in a handler type. - * Processes {@code @RequestMapping}, {@code @InitBinder}, - * {@code @ModelAttribute} and {@code @SessionAttributes}. - * - *

        Used by {@link org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter} - * and {@link org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter}. - * - * @author Juergen Hoeller - * @since 2.5.2 - * @see org.springframework.web.bind.annotation.RequestMapping - * @see org.springframework.web.bind.annotation.InitBinder - * @see org.springframework.web.bind.annotation.ModelAttribute - * @see org.springframework.web.bind.annotation.SessionAttributes - * @deprecated as of 4.3, in favor of the {@code HandlerMethod}-based MVC infrastructure - */ -@Deprecated -public class HandlerMethodResolver { - - private final Set handlerMethods = new LinkedHashSet(); - - private final Set initBinderMethods = new LinkedHashSet(); - - private final Set modelAttributeMethods = new LinkedHashSet(); - - private RequestMapping typeLevelMapping; - - private boolean sessionAttributesFound; - - private final Set sessionAttributeNames = new HashSet(); - - private final Set> sessionAttributeTypes = new HashSet>(); - - private final Set actualSessionAttributeNames = - Collections.newSetFromMap(new ConcurrentHashMap(4)); - - - /** - * Initialize a new HandlerMethodResolver for the specified handler type. - * @param handlerType the handler class to introspect - */ - public void init(final Class handlerType) { - Set> handlerTypes = new LinkedHashSet>(); - Class specificHandlerType = null; - if (!Proxy.isProxyClass(handlerType)) { - handlerTypes.add(handlerType); - specificHandlerType = handlerType; - } - handlerTypes.addAll(Arrays.asList(handlerType.getInterfaces())); - for (Class currentHandlerType : handlerTypes) { - final Class targetClass = (specificHandlerType != null ? specificHandlerType : currentHandlerType); - ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) { - Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass); - Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); - if (isHandlerMethod(specificMethod) && - (bridgedMethod == specificMethod || !isHandlerMethod(bridgedMethod))) { - handlerMethods.add(specificMethod); - } - else if (isInitBinderMethod(specificMethod) && - (bridgedMethod == specificMethod || !isInitBinderMethod(bridgedMethod))) { - initBinderMethods.add(specificMethod); - } - else if (isModelAttributeMethod(specificMethod) && - (bridgedMethod == specificMethod || !isModelAttributeMethod(bridgedMethod))) { - modelAttributeMethods.add(specificMethod); - } - } - }, ReflectionUtils.USER_DECLARED_METHODS); - } - this.typeLevelMapping = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class); - SessionAttributes sessionAttributes = AnnotationUtils.findAnnotation(handlerType, SessionAttributes.class); - this.sessionAttributesFound = (sessionAttributes != null); - if (this.sessionAttributesFound) { - this.sessionAttributeNames.addAll(Arrays.asList(sessionAttributes.names())); - this.sessionAttributeTypes.addAll(Arrays.asList(sessionAttributes.types())); - } - } - - protected boolean isHandlerMethod(Method method) { - return AnnotationUtils.findAnnotation(method, RequestMapping.class) != null; - } - - protected boolean isInitBinderMethod(Method method) { - return AnnotationUtils.findAnnotation(method, InitBinder.class) != null; - } - - protected boolean isModelAttributeMethod(Method method) { - return AnnotationUtils.findAnnotation(method, ModelAttribute.class) != null; - } - - - public final boolean hasHandlerMethods() { - return !this.handlerMethods.isEmpty(); - } - - public final Set getHandlerMethods() { - return this.handlerMethods; - } - - public final Set getInitBinderMethods() { - return this.initBinderMethods; - } - - public final Set getModelAttributeMethods() { - return this.modelAttributeMethods; - } - - public boolean hasTypeLevelMapping() { - return (this.typeLevelMapping != null); - } - - public RequestMapping getTypeLevelMapping() { - return this.typeLevelMapping; - } - - public boolean hasSessionAttributes() { - return this.sessionAttributesFound; - } - - public boolean isSessionAttribute(String attrName, Class attrType) { - if (this.sessionAttributeNames.contains(attrName) || this.sessionAttributeTypes.contains(attrType)) { - this.actualSessionAttributeNames.add(attrName); - return true; - } - else { - return false; - } - } - - public Set getActualSessionAttributeNames() { - return this.actualSessionAttributeNames; - } - -} diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/package-info.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/support/package-info.java deleted file mode 100644 index 347285afe4..0000000000 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/support/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Support classes for web annotation processing. - */ -package org.springframework.web.bind.annotation.support; diff --git a/spring-web/src/main/java/org/springframework/web/bind/support/WebArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/bind/support/WebArgumentResolver.java index 143edb28e4..2ab5731a87 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/support/WebArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/bind/support/WebArgumentResolver.java @@ -40,7 +40,6 @@ import org.springframework.web.context.request.NativeWebRequest; * @author Juergen Hoeller * @since 2.5.2 * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#setCustomArgumentResolvers - * @see org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter#setCustomArgumentResolvers */ public interface WebArgumentResolver { diff --git a/spring-web/src/main/java/org/springframework/web/context/WebApplicationContext.java b/spring-web/src/main/java/org/springframework/web/context/WebApplicationContext.java index b9585787d8..92ac80c1b5 100644 --- a/spring-web/src/main/java/org/springframework/web/context/WebApplicationContext.java +++ b/spring-web/src/main/java/org/springframework/web/context/WebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 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. @@ -65,12 +65,6 @@ public interface WebApplicationContext extends ApplicationContext { */ String SCOPE_SESSION = "session"; - /** - * Scope identifier for global session scope: "globalSession". - * Supported in addition to the standard scopes "singleton" and "prototype". - */ - String SCOPE_GLOBAL_SESSION = "globalSession"; - /** * Scope identifier for the global web application scope: "application". * Supported in addition to the standard scopes "singleton" and "prototype". diff --git a/spring-web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java b/spring-web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java index bfbf032b01..7b52f993c8 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/FacesRequestAttributes.java @@ -20,13 +20,11 @@ import java.lang.reflect.Method; import java.util.Map; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; -import javax.portlet.PortletSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.util.WebUtils; @@ -52,9 +50,6 @@ import org.springframework.web.util.WebUtils; */ public class FacesRequestAttributes implements RequestAttributes { - private static final boolean portletApiPresent = - ClassUtils.isPresent("javax.portlet.PortletSession", FacesRequestAttributes.class.getClassLoader()); - /** * We'll create a lot of these objects, so we don't want a new logger every time. */ @@ -108,42 +103,22 @@ public class FacesRequestAttributes implements RequestAttributes { @Override public Object getAttribute(String name, int scope) { - if (scope == SCOPE_GLOBAL_SESSION && portletApiPresent) { - return PortletSessionAccessor.getAttribute(name, getExternalContext()); - } - else { - return getAttributeMap(scope).get(name); - } + return getAttributeMap(scope).get(name); } @Override public void setAttribute(String name, Object value, int scope) { - if (scope == SCOPE_GLOBAL_SESSION && portletApiPresent) { - PortletSessionAccessor.setAttribute(name, value, getExternalContext()); - } - else { - getAttributeMap(scope).put(name, value); - } + getAttributeMap(scope).put(name, value); } @Override public void removeAttribute(String name, int scope) { - if (scope == SCOPE_GLOBAL_SESSION && portletApiPresent) { - PortletSessionAccessor.removeAttribute(name, getExternalContext()); - } - else { - getAttributeMap(scope).remove(name); - } + getAttributeMap(scope).remove(name); } @Override public String[] getAttributeNames(int scope) { - if (scope == SCOPE_GLOBAL_SESSION && portletApiPresent) { - return PortletSessionAccessor.getAttributeNames(getExternalContext()); - } - else { - return StringUtils.toStringArray(getAttributeMap(scope).keySet()); - } + return StringUtils.toStringArray(getAttributeMap(scope).keySet()); } @Override @@ -237,58 +212,4 @@ public class FacesRequestAttributes implements RequestAttributes { return mutex; } - - /** - * Inner class to avoid hard-coded Portlet API dependency. - */ - private static class PortletSessionAccessor { - - public static Object getAttribute(String name, ExternalContext externalContext) { - Object session = externalContext.getSession(false); - if (session instanceof PortletSession) { - return ((PortletSession) session).getAttribute(name, PortletSession.APPLICATION_SCOPE); - } - else if (session != null) { - return externalContext.getSessionMap().get(name); - } - else { - return null; - } - } - - public static void setAttribute(String name, Object value, ExternalContext externalContext) { - Object session = externalContext.getSession(true); - if (session instanceof PortletSession) { - ((PortletSession) session).setAttribute(name, value, PortletSession.APPLICATION_SCOPE); - } - else { - externalContext.getSessionMap().put(name, value); - } - } - - public static void removeAttribute(String name, ExternalContext externalContext) { - Object session = externalContext.getSession(false); - if (session instanceof PortletSession) { - ((PortletSession) session).removeAttribute(name, PortletSession.APPLICATION_SCOPE); - } - else if (session != null) { - externalContext.getSessionMap().remove(name); - } - } - - public static String[] getAttributeNames(ExternalContext externalContext) { - Object session = externalContext.getSession(false); - if (session instanceof PortletSession) { - return StringUtils.toStringArray( - ((PortletSession) session).getAttributeNames(PortletSession.APPLICATION_SCOPE)); - } - else if (session != null) { - return StringUtils.toStringArray(externalContext.getSessionMap().keySet()); - } - else { - return new String[0]; - } - } - } - } diff --git a/spring-web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java b/spring-web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java index 61d9bdf41d..6ddb31c48d 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/FacesWebRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -155,11 +155,6 @@ public class FacesWebRequest extends FacesRequestAttributes implements NativeWeb return false; } - /** - * Last-modified handling not supported for portlet requests: - * As a consequence, this method always returns {@code false}. - * @since 4.2 - */ @Override public boolean checkNotModified(String etag, long lastModifiedTimestamp) { return false; diff --git a/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java b/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java index 8554099076..edf161e127 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/NativeWebRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2016 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. @@ -31,16 +31,12 @@ public interface NativeWebRequest extends WebRequest { /** * Return the underlying native request object, if available. * @see javax.servlet.http.HttpServletRequest - * @see javax.portlet.ActionRequest - * @see javax.portlet.RenderRequest */ Object getNativeRequest(); /** * Return the underlying native response object, if available. * @see javax.servlet.http.HttpServletResponse - * @see javax.portlet.ActionResponse - * @see javax.portlet.RenderResponse */ Object getNativeResponse(); @@ -50,8 +46,6 @@ public interface NativeWebRequest extends WebRequest { * @return the matching request object, or {@code null} if none * of that type is available * @see javax.servlet.http.HttpServletRequest - * @see javax.portlet.ActionRequest - * @see javax.portlet.RenderRequest */ T getNativeRequest(Class requiredType); @@ -61,8 +55,6 @@ public interface NativeWebRequest extends WebRequest { * @return the matching response object, or {@code null} if none * of that type is available * @see javax.servlet.http.HttpServletResponse - * @see javax.portlet.ActionResponse - * @see javax.portlet.RenderResponse */ T getNativeResponse(Class requiredType); diff --git a/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java b/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java index 71568c0a47..6fba81f3c2 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/RequestAttributes.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2016 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. @@ -22,12 +22,11 @@ package org.springframework.web.context.request; * attributes, with the optional notion of a "global session". * *

        Can be implemented for any kind of request/session mechanism, - * in particular for servlet requests and portlet requests. + * in particular for servlet requests. * * @author Juergen Hoeller * @since 2.0 * @see ServletRequestAttributes - * @see org.springframework.web.portlet.context.PortletRequestAttributes */ public interface RequestAttributes { @@ -44,14 +43,6 @@ public interface RequestAttributes { */ int SCOPE_SESSION = 1; - /** - * Constant that indicates global session scope. - *

        This explicitly refers to a globally shared session, if such - * a distinction is available (for example, in a Portlet environment). - * Else, it simply refers to the common session. - */ - int SCOPE_GLOBAL_SESSION = 2; - /** * Name of the standard reference to the request object: "request". diff --git a/spring-web/src/main/java/org/springframework/web/context/request/RequestContextHolder.java b/spring-web/src/main/java/org/springframework/web/context/request/RequestContextHolder.java index 8cf39688a3..793e7c4893 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/RequestContextHolder.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/RequestContextHolder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 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. @@ -31,9 +31,8 @@ import org.springframework.util.ClassUtils; *

        Use {@link RequestContextListener} or * {@link org.springframework.web.filter.RequestContextFilter} to expose * the current web request. Note that - * {@link org.springframework.web.servlet.DispatcherServlet} and - * {@link org.springframework.web.portlet.DispatcherPortlet} already - * expose the current request by default. + * {@link org.springframework.web.servlet.DispatcherServlet} + * already exposes the current request by default. * * @author Juergen Hoeller * @author Rod Johnson @@ -41,7 +40,6 @@ import org.springframework.util.ClassUtils; * @see RequestContextListener * @see org.springframework.web.filter.RequestContextFilter * @see org.springframework.web.servlet.DispatcherServlet - * @see org.springframework.web.portlet.DispatcherPortlet */ public abstract class RequestContextHolder { diff --git a/spring-web/src/main/java/org/springframework/web/context/request/RequestScope.java b/spring-web/src/main/java/org/springframework/web/context/request/RequestScope.java index 370a3ee841..92b36f84ae 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/RequestScope.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/RequestScope.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 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. @@ -25,11 +25,6 @@ package org.springframework.web.context.request; * {@link org.springframework.web.filter.RequestContextFilter} or * {@link org.springframework.web.servlet.DispatcherServlet}. * - *

        This {@code Scope} will also work for Portlet environments, - * through an alternate {@code RequestAttributes} implementation - * (as exposed out-of-the-box by Spring's - * {@link org.springframework.web.portlet.DispatcherPortlet}. - * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop @@ -39,7 +34,6 @@ package org.springframework.web.context.request; * @see RequestContextListener * @see org.springframework.web.filter.RequestContextFilter * @see org.springframework.web.servlet.DispatcherServlet - * @see org.springframework.web.portlet.DispatcherPortlet */ public class RequestScope extends AbstractRequestAttributesScope { diff --git a/spring-web/src/main/java/org/springframework/web/context/request/SessionScope.java b/spring-web/src/main/java/org/springframework/web/context/request/SessionScope.java index 9df39c4f5f..8d6a6e5fea 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/SessionScope.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/SessionScope.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 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. @@ -27,58 +27,21 @@ import org.springframework.beans.factory.ObjectFactory; * {@link org.springframework.web.filter.RequestContextFilter} or * {@link org.springframework.web.servlet.DispatcherServlet}. * - *

        This {@code Scope} will also work for Portlet environments, - * through an alternate {@code RequestAttributes} implementation - * (as exposed out-of-the-box by Spring's - * {@link org.springframework.web.portlet.DispatcherPortlet}. - * * @author Rod Johnson * @author Juergen Hoeller * @author Rob Harrop * @since 2.0 * @see RequestContextHolder#currentRequestAttributes() * @see RequestAttributes#SCOPE_SESSION - * @see RequestAttributes#SCOPE_GLOBAL_SESSION * @see RequestContextListener * @see org.springframework.web.filter.RequestContextFilter * @see org.springframework.web.servlet.DispatcherServlet - * @see org.springframework.web.portlet.DispatcherPortlet */ public class SessionScope extends AbstractRequestAttributesScope { - private final int scope; - - - /** - * Create a new SessionScope, storing attributes in a locally - * isolated session (or default session, if there is no distinction - * between a global session and a component-specific session). - */ - public SessionScope() { - this.scope = RequestAttributes.SCOPE_SESSION; - } - - /** - * Create a new SessionScope, specifying whether to store attributes - * in the global session, provided that such a distinction is available. - *

        This distinction is important for Portlet environments, where there - * are two notions of a session: "portlet scope" and "application scope". - * If this flag is on, objects will be put into the "application scope" session; - * else they will end up in the "portlet scope" session (the typical default). - *

        In a Servlet environment, this flag is effectively ignored. - * @param globalSession {@code true} in case of the global session as target; - * {@code false} in case of a component-specific session as target - * @see org.springframework.web.portlet.context.PortletRequestAttributes - * @see ServletRequestAttributes - */ - public SessionScope(boolean globalSession) { - this.scope = (globalSession ? RequestAttributes.SCOPE_GLOBAL_SESSION : RequestAttributes.SCOPE_SESSION); - } - - @Override protected int getScope() { - return this.scope; + return RequestAttributes.SCOPE_SESSION; } @Override diff --git a/spring-web/src/main/java/org/springframework/web/context/request/WebRequestInterceptor.java b/spring-web/src/main/java/org/springframework/web/context/request/WebRequestInterceptor.java index 1a5089bd96..4b16c98334 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/WebRequestInterceptor.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/WebRequestInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 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. @@ -52,11 +52,6 @@ import org.springframework.ui.ModelMap; * @see org.springframework.web.servlet.DispatcherServlet * @see org.springframework.web.servlet.handler.AbstractHandlerMapping#setInterceptors * @see org.springframework.web.servlet.HandlerInterceptor - * @see org.springframework.web.portlet.context.PortletWebRequest - * @see org.springframework.web.portlet.DispatcherPortlet - * @see org.springframework.web.portlet.handler.AbstractHandlerMapping#setInterceptors - * @see org.springframework.web.portlet.handler.AbstractHandlerMapping#setApplyWebRequestInterceptorsToRenderPhaseOnly - * @see org.springframework.web.portlet.HandlerInterceptor */ public interface WebRequestInterceptor { diff --git a/spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java b/spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java index 26838d3907..34b5786916 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/WebApplicationContextUtils.java @@ -177,8 +177,7 @@ public abstract class WebApplicationContextUtils { */ public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, ServletContext sc) { beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); - beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false)); - beanFactory.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true)); + beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope()); if (sc != null) { ServletContextScope appScope = new ServletContextScope(sc); beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope); diff --git a/spring-web/src/main/java/org/springframework/web/multipart/MultipartRequest.java b/spring-web/src/main/java/org/springframework/web/multipart/MultipartRequest.java index f24bb2207d..4dc2cb25d7 100644 --- a/spring-web/src/main/java/org/springframework/web/multipart/MultipartRequest.java +++ b/spring-web/src/main/java/org/springframework/web/multipart/MultipartRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2016 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,10 +23,8 @@ import java.util.Map; import org.springframework.util.MultiValueMap; /** - * This interface defines the multipart request access operations - * that are exposed for actual multipart requests. It is extended - * by {@link MultipartHttpServletRequest} and the Portlet - * {@link org.springframework.web.portlet.multipart.MultipartActionRequest}. + * This interface defines the multipart request access operations that are exposed + * for actual multipart requests. It is extended by {@link MultipartHttpServletRequest}. * * @author Juergen Hoeller * @author Arjen Poutsma diff --git a/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java b/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java index 727bc92c5f..17af1ce15b 100644 --- a/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java +++ b/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsFileUploadSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -47,16 +47,10 @@ import org.springframework.web.util.WebUtils; * as representation of uploaded files and a String-based parameter Map as * representation of uploaded form fields. * - *

        Subclasses implement concrete resolution strategies for Servlet or Portlet - * environments: see CommonsMultipartResolver and CommonsPortletMultipartResolver, - * respectively. This base class is not tied to either of those APIs, factoring - * out common functionality. - * * @author Juergen Hoeller * @since 2.0 * @see CommonsMultipartFile * @see CommonsMultipartResolver - * @see org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver */ public abstract class CommonsFileUploadSupport { diff --git a/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java b/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java index 22960e3811..b40c42f947 100644 --- a/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java +++ b/spring-web/src/main/java/org/springframework/web/multipart/commons/CommonsMultipartResolver.java @@ -55,7 +55,6 @@ import org.springframework.web.util.WebUtils; * @since 29.09.2003 * @see #CommonsMultipartResolver(ServletContext) * @see #setResolveLazily - * @see org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver * @see org.apache.commons.fileupload.servlet.ServletFileUpload * @see org.apache.commons.fileupload.disk.DiskFileItemFactory */ diff --git a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java index 603e264279..a22daa3e3e 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/ServletRequestAttributesTests.java @@ -95,31 +95,6 @@ public class ServletRequestAttributesTests { assertSame(VALUE, session.getAttribute(KEY)); } - @Test - public void setGlobalSessionScopedAttribute() throws Exception { - MockHttpSession session = new MockHttpSession(); - session.setAttribute(KEY, VALUE); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setSession(session); - ServletRequestAttributes attrs = new ServletRequestAttributes(request); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION); - assertSame(VALUE, session.getAttribute(KEY)); - } - - @Test - public void setGlobalSessionScopedAttributeAfterCompletion() throws Exception { - MockHttpSession session = new MockHttpSession(); - session.setAttribute(KEY, VALUE); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setSession(session); - ServletRequestAttributes attrs = new ServletRequestAttributes(request); - assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_GLOBAL_SESSION)); - attrs.requestCompleted(); - request.close(); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION); - assertSame(VALUE, session.getAttribute(KEY)); - } - @Test public void getSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java deleted file mode 100644 index 35300634ec..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/DispatcherPortlet.java +++ /dev/null @@ -1,1381 +0,0 @@ -/* - * Copyright 2002-2016 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; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -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.PortletRequestDispatcher; -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.StateAwareResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -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.core.annotation.AnnotationAwareOrderComparator; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.support.PropertiesLoaderUtils; -import org.springframework.core.style.StylerUtils; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.multipart.MultipartException; -import org.springframework.web.portlet.multipart.MultipartActionRequest; -import org.springframework.web.portlet.multipart.PortletMultipartResolver; -import org.springframework.web.servlet.View; -import org.springframework.web.servlet.ViewRendererServlet; -import org.springframework.web.servlet.ViewResolver; - -/** - * Central dispatcher for use within the Portlet MVC framework, e.g. for web UI - * controllers. Dispatches to registered handlers for processing a portlet request. - * - *

        This portlet is very flexible: It can be used with just about any workflow, - * with the installation of the appropriate adapter classes. It offers the following - * functionality that distinguishes it from other request-driven Portlet MVC frameworks: - * - *

          - *
        • It is based around a JavaBeans configuration mechanism. - * - *
        • 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}. - * 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). - * - *
        • 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. - * 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). - * - *
        • The dispatcher's exception resolution strategy can be specified via a - * {@link HandlerExceptionResolver}, for example mapping certain exceptions to - * error pages. Default is none. Additional HandlerExceptionResolvers can be added - * through the application context. HandlerExceptionResolver can be given any - * bean name (they are tested by type). - * - *
        • Its view resolution strategy can be specified via a {@link ViewResolver} - * implementation, resolving symbolic view names into View objects. Default is - * {@link org.springframework.web.servlet.view.InternalResourceViewResolver}. - * ViewResolver objects can be added as beans in the application context, - * overriding the default ViewResolver. ViewResolvers can be given any bean name - * (they are tested by type). - * - *
        • The dispatcher's strategy for resolving multipart requests is determined by a - * {@link org.springframework.web.portlet.multipart.PortletMultipartResolver} - * implementation. An implementations for Apache Commons FileUpload is included: - * {@link org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver}. - * The MultipartResolver bean name is "portletMultipartResolver"; default is none. - *
        - * - *

        NOTE: The {@code @RequestMapping} annotation will only be processed if a - * corresponding {@code HandlerMapping} (for type-level annotations) and/or - * {@code HandlerAdapter} (for method-level annotations) is present in the dispatcher. - * This is the case by default. However, if you are defining custom {@code HandlerMappings} - * or {@code HandlerAdapters}, then you need to make sure that a corresponding custom - * {@code DefaultAnnotationHandlerMapping} and/or {@code AnnotationMethodHandlerAdapter} - * is defined as well - provided that you intend to use {@code @RequestMapping}. - * - *

        A web application can define any number of DispatcherPortlets. - * Each portlet will operate in its own namespace, loading its own application context - * with mappings, handlers, etc. Only the root application context as loaded by - * {@link org.springframework.web.context.ContextLoaderListener}, if any, will be shared. - * - *

        Thanks to Rainer Schmitz, Nick Lothian and Eric Dalquist for their suggestions! - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see org.springframework.web.portlet.mvc.Controller - * @see org.springframework.web.servlet.ViewRendererServlet - * @see org.springframework.web.context.ContextLoaderListener - */ -public class DispatcherPortlet extends FrameworkPortlet { - - /** - * Well-known name for the PortletMultipartResolver object in the bean factory for this namespace. - */ - public static final String MULTIPART_RESOLVER_BEAN_NAME = "portletMultipartResolver"; - - /** - * Well-known name for the HandlerMapping object in the bean factory for this namespace. - * Only used when "detectAllHandlerMappings" is turned off. - * @see #setDetectAllViewResolvers - */ - public static final String HANDLER_MAPPING_BEAN_NAME = "handlerMapping"; - - /** - * Well-known name for the HandlerAdapter object in the bean factory for this namespace. - * Only used when "detectAllHandlerAdapters" is turned off. - * @see #setDetectAllHandlerAdapters - */ - public static final String HANDLER_ADAPTER_BEAN_NAME = "handlerAdapter"; - - /** - * Well-known name for the HandlerExceptionResolver object in the bean factory for this - * namespace. Only used when "detectAllHandlerExceptionResolvers" is turned off. - * @see #setDetectAllViewResolvers - */ - public static final String HANDLER_EXCEPTION_RESOLVER_BEAN_NAME = "handlerExceptionResolver"; - - /** - * Well-known name for the ViewResolver object in the bean factory for this namespace. - */ - public static final String VIEW_RESOLVER_BEAN_NAME = "viewResolver"; - - /** - * Default URL to ViewRendererServlet. This bridge servlet is used to convert - * portlet render requests to servlet requests in order to leverage the view support - * in the {@code org.springframework.web.view} package. - */ - public static final String DEFAULT_VIEW_RENDERER_URL = "/WEB-INF/servlet/view"; - - /** - * Unlike the Servlet version of this class, we have to deal with the - * two-phase nature of the portlet request. To do this, we need to pass - * forward any exception that occurs during the action phase, so that - * it can be displayed in the render phase. The only direct way to pass - * things forward and preserve them for each render request is through - * render parameters, but these are limited to String objects and we need - * to pass the Exception itself. The only other way to do this is in the - * session. The bad thing about using the session is that we have no way - * of knowing when we are done re-rendering the request and so we don't - * know when we can remove the objects from the session. So we will end - * up polluting the session with an old exception when we finally leave - * the render phase of one request and move on to something else. - */ - public static final String ACTION_EXCEPTION_SESSION_ATTRIBUTE = - DispatcherPortlet.class.getName() + ".ACTION_EXCEPTION"; - - /** - * This render parameter is used to indicate forward to the render phase - * that an exception occurred during the action phase. - */ - public static final String ACTION_EXCEPTION_RENDER_PARAMETER = "actionException"; - - /** - * Log category to use when no mapped handler is found for a request. - */ - public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.portlet.PageNotFound"; - - /** - * Name of the class path resource (relative to the DispatcherPortlet class) - * that defines DispatcherPortet's default strategy names. - */ - private static final String DEFAULT_STRATEGIES_PATH = "DispatcherPortlet.properties"; - - - /** - * Additional logger to use when no mapped handler is found for a request. - */ - protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY); - - private static final Properties defaultStrategies; - - static { - // Load default strategy implementations from properties file. - // This is currently strictly internal and not meant to be customized - // by application developers. - try { - ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherPortlet.class); - defaultStrategies = PropertiesLoaderUtils.loadProperties(resource); - } - catch (IOException ex) { - throw new IllegalStateException("Could not load 'DispatcherPortlet.properties': " + ex.getMessage()); - } - } - - - /** Detect all HandlerMappings or just expect "handlerMapping" bean? */ - private boolean detectAllHandlerMappings = true; - - /** Detect all HandlerAdapters or just expect "handlerAdapter" bean? */ - private boolean detectAllHandlerAdapters = true; - - /** Detect all HandlerExceptionResolvers or just expect "handlerExceptionResolver" bean? */ - private boolean detectAllHandlerExceptionResolvers = true; - - /** Detect all ViewResolvers or just expect "viewResolver" bean? */ - private boolean detectAllViewResolvers = true; - - /** Whether exceptions thrown during doAction should be forwarded to doRender */ - private boolean forwardActionException = true; - - /** Whether exceptions thrown during doEvent should be forwarded to doRender */ - private boolean forwardEventException = false; - - /** URL that points to the ViewRendererServlet */ - private String viewRendererUrl = DEFAULT_VIEW_RENDERER_URL; - - - /** MultipartResolver used by this portlet */ - private PortletMultipartResolver multipartResolver; - - /** List of HandlerMappings used by this portlet */ - private List handlerMappings; - - /** List of HandlerAdapters used by this portlet */ - private List handlerAdapters; - - /** List of HandlerExceptionResolvers used by this portlet */ - private List handlerExceptionResolvers; - - /** List of ViewResolvers used by this portlet */ - private List viewResolvers; - - - /** - * Set whether to detect all HandlerMapping beans in this portlet's context. - * Else, just a single bean with name "handlerMapping" will be expected. - *

        Default is true. Turn this off if you want this portlet to use a - * single HandlerMapping, despite multiple HandlerMapping beans being - * defined in the context. - */ - public void setDetectAllHandlerMappings(boolean detectAllHandlerMappings) { - this.detectAllHandlerMappings = detectAllHandlerMappings; - } - - /** - * Set whether to detect all HandlerAdapter beans in this portlet's context. - * Else, just a single bean with name "handlerAdapter" will be expected. - *

        Default is "true". Turn this off if you want this portlet to use a - * single HandlerAdapter, despite multiple HandlerAdapter beans being - * defined in the context. - */ - public void setDetectAllHandlerAdapters(boolean detectAllHandlerAdapters) { - this.detectAllHandlerAdapters = detectAllHandlerAdapters; - } - - /** - * Set whether to detect all HandlerExceptionResolver beans in this portlet's context. - * Else, just a single bean with name "handlerExceptionResolver" will be expected. - *

        Default is true. Turn this off if you want this portlet to use a - * single HandlerExceptionResolver, despite multiple HandlerExceptionResolver - * beans being defined in the context. - */ - public void setDetectAllHandlerExceptionResolvers(boolean detectAllHandlerExceptionResolvers) { - this.detectAllHandlerExceptionResolvers = detectAllHandlerExceptionResolvers; - } - - /** - * Set whether to detect all ViewResolver beans in this portlet's context. - * Else, just a single bean with name "viewResolver" will be expected. - *

        Default is true. Turn this off if you want this portlet to use a - * single ViewResolver, despite multiple ViewResolver beans being - * defined in the context. - */ - public void setDetectAllViewResolvers(boolean detectAllViewResolvers) { - this.detectAllViewResolvers = detectAllViewResolvers; - } - - /** - * Set whether to forward exceptions thrown during the action phase - * to the render phase via a session attribute. - *

        Default is true. Turn this off if you want the portlet container - * to provide immediate exception handling for action requests. - * @see #exposeActionException(javax.portlet.PortletRequest, javax.portlet.StateAwareResponse, Exception) - */ - public void setForwardActionException(boolean forwardActionException) { - this.forwardActionException = forwardActionException; - } - - /** - * Set whether to forward exceptions thrown during the event phase - * to the render phase via a session attribute. - *

        Default is false. Turn this on if you want the {@link DispatcherPortlet} - * to forward the exception to the render phase, similar to what it does - * for {@link #setForwardActionException action exceptions} by default. - */ - public void setForwardEventException(boolean forwardEventException) { - this.forwardEventException = forwardEventException; - } - - /** - * Set the URL to the ViewRendererServlet. That servlet is used to - * ultimately render all views in the portlet application. - */ - public void setViewRendererUrl(String viewRendererUrl) { - this.viewRendererUrl = viewRendererUrl; - } - - - /** - * This implementation calls {@link #initStrategies}. - */ - @Override - public void onRefresh(ApplicationContext context) { - initStrategies(context); - } - - /** - * Refresh the strategy objects that this portlet uses. - *

        May be overridden in subclasses in order to initialize - * further strategy objects. - */ - protected void initStrategies(ApplicationContext context) { - initMultipartResolver(context); - initHandlerMappings(context); - initHandlerAdapters(context); - initHandlerExceptionResolvers(context); - initViewResolvers(context); - } - - /** - * Initialize the PortletMultipartResolver used by this class. - *

        If no valid bean is defined with the given name in the BeanFactory - * for this namespace, no multipart handling is provided. - */ - private void initMultipartResolver(ApplicationContext context) { - try { - this.multipartResolver = context.getBean(MULTIPART_RESOLVER_BEAN_NAME, PortletMultipartResolver.class); - if (logger.isDebugEnabled()) { - logger.debug("Using MultipartResolver [" + this.multipartResolver + "]"); - } - } - catch (NoSuchBeanDefinitionException ex) { - // Default is no multipart resolver. - this.multipartResolver = null; - if (logger.isDebugEnabled()) { - logger.debug("Unable to locate PortletMultipartResolver with name '" + MULTIPART_RESOLVER_BEAN_NAME + - "': no multipart request handling provided"); - } - } - } - - /** - * Initialize the HandlerMappings used by this class. - *

        If no HandlerMapping beans are defined in the BeanFactory - * for this namespace, we default to PortletModeHandlerMapping. - */ - private void initHandlerMappings(ApplicationContext context) { - this.handlerMappings = null; - - if (this.detectAllHandlerMappings) { - // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( - context, HandlerMapping.class, true, false); - if (!matchingBeans.isEmpty()) { - this.handlerMappings = new ArrayList(matchingBeans.values()); - // We keep HandlerMappings in sorted order. - AnnotationAwareOrderComparator.sort(this.handlerMappings); - } - } - else { - try { - HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class); - this.handlerMappings = Collections.singletonList(hm); - } - catch (NoSuchBeanDefinitionException ex) { - // Ignore, we'll add a default HandlerMapping later. - } - } - - // Ensure we have at least one HandlerMapping, by registering - // a default HandlerMapping if no other mappings are found. - if (this.handlerMappings == null) { - this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class); - if (logger.isDebugEnabled()) { - logger.debug("No HandlerMappings found in portlet '" + getPortletName() + "': using default"); - } - } - } - - /** - * Initialize the HandlerAdapters used by this class. - *

        If no HandlerAdapter beans are defined in the BeanFactory - * for this namespace, we default to SimpleControllerHandlerAdapter. - */ - private void initHandlerAdapters(ApplicationContext context) { - this.handlerAdapters = null; - - if (this.detectAllHandlerAdapters) { - // Find all HandlerAdapters in the ApplicationContext, including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( - context, HandlerAdapter.class, true, false); - if (!matchingBeans.isEmpty()) { - this.handlerAdapters = new ArrayList(matchingBeans.values()); - // We keep HandlerAdapters in sorted order. - AnnotationAwareOrderComparator.sort(this.handlerAdapters); - } - } - else { - try { - HandlerAdapter ha = context.getBean(HANDLER_ADAPTER_BEAN_NAME, HandlerAdapter.class); - this.handlerAdapters = Collections.singletonList(ha); - } - catch (NoSuchBeanDefinitionException ex) { - // Ignore, we'll add a default HandlerAdapter later. - } - } - - // Ensure we have at least some HandlerAdapters, by registering - // default HandlerAdapters if no other adapters are found. - if (this.handlerAdapters == null) { - this.handlerAdapters = getDefaultStrategies(context, HandlerAdapter.class); - if (logger.isDebugEnabled()) { - logger.debug("No HandlerAdapters found in portlet '" + getPortletName() + "': using default"); - } - } - } - - /** - * Initialize the HandlerExceptionResolver used by this class. - *

        If no bean is defined with the given name in the BeanFactory - * for this namespace, we default to no exception resolver. - */ - private void initHandlerExceptionResolvers(ApplicationContext context) { - this.handlerExceptionResolvers = null; - - if (this.detectAllHandlerExceptionResolvers) { - // Find all HandlerExceptionResolvers in the ApplicationContext, including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( - context, HandlerExceptionResolver.class, true, false); - if (!matchingBeans.isEmpty()) { - this.handlerExceptionResolvers = new ArrayList(matchingBeans.values()); - // We keep HandlerExceptionResolvers in sorted order. - AnnotationAwareOrderComparator.sort(this.handlerExceptionResolvers); - } - } - else { - try { - HandlerExceptionResolver her = context.getBean( - HANDLER_EXCEPTION_RESOLVER_BEAN_NAME, HandlerExceptionResolver.class); - this.handlerExceptionResolvers = Collections.singletonList(her); - } - catch (NoSuchBeanDefinitionException ex) { - // Ignore, no HandlerExceptionResolver is fine too. - } - } - - // Just for consistency, check for default HandlerExceptionResolvers... - // There aren't any in usual scenarios. - if (this.handlerExceptionResolvers == null) { - this.handlerExceptionResolvers = getDefaultStrategies(context, HandlerExceptionResolver.class); - if (logger.isDebugEnabled()) { - logger.debug("No HandlerExceptionResolvers found in portlet '" + getPortletName() + "': using default"); - } - } - } - - /** - * Initialize the ViewResolvers used by this class. - *

        If no ViewResolver beans are defined in the BeanFactory - * for this namespace, we default to InternalResourceViewResolver. - */ - private void initViewResolvers(ApplicationContext context) { - this.viewResolvers = null; - - if (this.detectAllViewResolvers) { - // Find all ViewResolvers in the ApplicationContext, including ancestor contexts. - Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors( - context, ViewResolver.class, true, false); - if (!matchingBeans.isEmpty()) { - this.viewResolvers = new ArrayList(matchingBeans.values()); - // We keep ViewResolvers in sorted order. - AnnotationAwareOrderComparator.sort(this.viewResolvers); - } - } - else { - try { - ViewResolver vr = context.getBean(VIEW_RESOLVER_BEAN_NAME, ViewResolver.class); - this.viewResolvers = Collections.singletonList(vr); - } - catch (NoSuchBeanDefinitionException ex) { - // Ignore, we'll add a default ViewResolver later. - } - } - - // Ensure we have at least one ViewResolver, by registering - // a default ViewResolver if no other resolvers are found. - if (this.viewResolvers == null) { - this.viewResolvers = getDefaultStrategies(context, ViewResolver.class); - if (logger.isDebugEnabled()) { - logger.debug("No ViewResolvers found in portlet '" + getPortletName() + "': using default"); - } - } - } - - - /** - * Return the default strategy object for the given strategy interface. - *

        The default implementation delegates to {@link #getDefaultStrategies}, - * expecting a single object in the list. - * @param context the current Portlet ApplicationContext - * @param strategyInterface the strategy interface - * @return the corresponding strategy object - * @see #getDefaultStrategies - */ - protected T getDefaultStrategy(ApplicationContext context, Class strategyInterface) { - List strategies = getDefaultStrategies(context, strategyInterface); - if (strategies.size() != 1) { - throw new BeanInitializationException( - "DispatcherPortlet needs exactly 1 strategy for interface [" + strategyInterface.getName() + "]"); - } - return strategies.get(0); - } - - /** - * Create a List of default strategy objects for the given strategy interface. - *

        The default implementation uses the "DispatcherPortlet.properties" file - * (in the same package as the DispatcherPortlet class) to determine the class names. - * It instantiates the strategy objects and satisifies ApplicationContextAware - * if necessary. - * @param context the current Portlet ApplicationContext - * @param strategyInterface the strategy interface - * @return the List of corresponding strategy objects - */ - @SuppressWarnings("unchecked") - protected List getDefaultStrategies(ApplicationContext context, Class strategyInterface) { - String key = strategyInterface.getName(); - String value = defaultStrategies.getProperty(key); - if (value != null) { - String[] classNames = StringUtils.commaDelimitedListToStringArray(value); - List strategies = new ArrayList(classNames.length); - for (String className : classNames) { - try { - Class clazz = ClassUtils.forName(className, DispatcherPortlet.class.getClassLoader()); - Object strategy = createDefaultStrategy(context, clazz); - strategies.add((T) strategy); - } - catch (ClassNotFoundException ex) { - throw new BeanInitializationException( - "Could not find DispatcherPortlet's default strategy class [" + className + - "] for interface [" + key + "]", ex); - } - catch (LinkageError err) { - throw new BeanInitializationException( - "Error loading DispatcherPortlet's default strategy class [" + className + - "] for interface [" + key + "]: problem with class file or dependent class", err); - } - } - return strategies; - } - else { - return new LinkedList(); - } - } - - /** - * Create a default strategy. - *

        The default implementation uses - * {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory#createBean}. - * @param context the current Portlet ApplicationContext - * @param clazz the strategy implementation class to instantiate - * @return the fully configured strategy instance - * @see org.springframework.context.ApplicationContext#getAutowireCapableBeanFactory() - */ - protected Object createDefaultStrategy(ApplicationContext context, Class clazz) { - return context.getAutowireCapableBeanFactory().createBean(clazz); - } - - - /** - * Obtain this portlet's PortletMultipartResolver, if any. - * @return the PortletMultipartResolver used by this portlet, or {@code null} - * if none (indicating that no multipart support is available) - */ - public PortletMultipartResolver getMultipartResolver() { - return this.multipartResolver; - } - - - /** - * Processes the actual dispatching to the handler for action requests. - *

        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 - */ - @Override - protected void doActionService(ActionRequest request, ActionResponse response) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received action request"); - } - - ActionRequest processedRequest = request; - HandlerExecutionChain mappedHandler = null; - int interceptorIndex = -1; - - try { - processedRequest = checkMultipart(request); - - // Determine handler for the current request. - mappedHandler = getHandler(processedRequest); - if (mappedHandler == null || mappedHandler.getHandler() == null) { - noHandlerFound(processedRequest, 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.preHandleAction(processedRequest, response, mappedHandler.getHandler())) { - triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); - return; - } - interceptorIndex = i; - } - } - - // Actually invoke the handler. - HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); - ha.handleAction(processedRequest, response, mappedHandler.getHandler()); - - // Trigger after-completion for successful outcome. - triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, null); - } - - catch (Exception ex) { - // Trigger after-completion for thrown exception. - triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); - // Forward the exception to the render phase to be displayed. - if (this.forwardActionException) { - try { - exposeActionException(request, response, 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; - } - } - else { - throw ex; - } - } - catch (Throwable err) { - PortletException ex = - new PortletException("Error occured during request processing: " + err.getMessage(), err); - // Trigger after-completion for thrown exception. - triggerAfterActionCompletion(mappedHandler, interceptorIndex, processedRequest, response, ex); - throw ex; - } - - finally { - // Clean up any resources used by a multipart request. - if (processedRequest instanceof MultipartActionRequest && processedRequest != request) { - this.multipartResolver.cleanupMultipart((MultipartActionRequest) processedRequest); - } - } - } - - /** - * Processes the actual dispatching to the handler for render requests. - *

        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 doRenderService(RenderRequest request, RenderResponse response) throws Exception { - if (logger.isDebugEnabled()) { - logger.debug("DispatcherPortlet with name '" + getPortletName() + "' received render request"); - } - - HandlerExecutionChain mappedHandler = null; - int interceptorIndex = -1; - - try { - ModelAndView mv; - try { - // Determine handler for the current request. - mappedHandler = getHandler(request); - 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.preHandleRender(request, response, mappedHandler.getHandler())) { - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null); - return; - } - interceptorIndex = i; - } - } - - // 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); - } - } - - // Actually invoke the handler. - HandlerAdapter ha = getHandlerAdapter(mappedHandler.getHandler()); - mv = ha.handleRender(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.postHandleRender(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. - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, null); - } - - catch (Exception ex) { - // Trigger after-completion for thrown exception. - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex); - throw ex; - } - catch (Throwable err) { - PortletException ex = - new PortletException("Error occured during request processing: " + err.getMessage(), err); - // Trigger after-completion for thrown exception. - triggerAfterRenderCompletion(mappedHandler, interceptorIndex, request, response, ex); - throw ex; - } - } - - /** - * Processes the actual dispatching to the handler for resource requests. - *

        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"); - } - - HandlerExecutionChain mappedHandler = null; - int interceptorIndex = -1; - - try { - ModelAndView mv; - try { - // Determine handler for the current request. - mappedHandler = getHandler(request); - 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 (Throwable 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; - } - } - - /** - * Processes the actual dispatching to the handler for event requests. - *

        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 - */ - @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); - 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. - if (this.forwardEventException) { - try { - exposeActionException(request, response, ex); - logger.debug("Caught exception during event phase - forwarding to render phase", ex); - } - catch (IllegalStateException ex2) { - // Probably sendRedirect called... need to rethrow exception immediately. - throw ex; - } - } - else { - throw ex; - } - } - catch (Throwable 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. - * @param request current HTTP request - * @return the processed request (multipart wrapper if necessary) - */ - protected ActionRequest checkMultipart(ActionRequest request) throws MultipartException { - if (this.multipartResolver != null && this.multipartResolver.isMultipart(request)) { - if (request instanceof MultipartActionRequest) { - logger.debug("Request is already a MultipartActionRequest - probably in a forward"); - } - else { - return this.multipartResolver.resolveMultipart(request); - } - } - // If not returned before: return original request. - return request; - } - - /** - * Return the HandlerExecutionChain for this request. - * Try all handler mappings in order. - * @param request current portlet request - * @return the HandlerExecutionChain, or null if no handler could be found - */ - protected HandlerExecutionChain getHandler(PortletRequest request) throws Exception { - for (HandlerMapping hm : this.handlerMappings) { - if (logger.isDebugEnabled()) { - logger.debug( - "Testing handler map [" + hm + "] in DispatcherPortlet with name '" + getPortletName() + "'"); - } - HandlerExecutionChain handler = hm.getHandler(request); - if (handler != null) { - return handler; - } - } - return null; - } - - /** - * No handler found -> throw appropriate exception. - * @param request current portlet request - * @param response current portlet response - * @throws Exception if preparing the response failed - */ - protected void noHandlerFound(PortletRequest request, PortletResponse response) throws Exception { - if (pageNotFoundLogger.isWarnEnabled()) { - pageNotFoundLogger.warn("No handler found for current request " + - "in DispatcherPortlet with name '" + getPortletName() + - "', mode '" + request.getPortletMode() + - "', phase '" + request.getAttribute(PortletRequest.LIFECYCLE_PHASE) + - "', parameters " + StylerUtils.style(request.getParameterMap())); - } - throw new NoHandlerFoundException("No handler found for portlet request", request); - } - - /** - * Return the HandlerAdapter for this handler object. - * @param handler the handler object to find an adapter for - * @throws PortletException if no HandlerAdapter can be found for the handler. - * This is a fatal error. - */ - protected HandlerAdapter getHandlerAdapter(Object handler) throws PortletException { - for (HandlerAdapter ha : this.handlerAdapters) { - if (logger.isDebugEnabled()) { - logger.debug("Testing handler adapter [" + ha + "]"); - } - if (ha.supports(handler)) { - return ha; - } - } - throw new PortletException("No adapter for handler [" + handler + - "]: Does your handler implement a supported interface like Controller?"); - } - - /** - * Expose the given action exception to the given response. - * @param request current portlet request - * @param response current portlet response - * @param ex the action exception (may also come from an event phase) - */ - protected void exposeActionException(PortletRequest request, StateAwareResponse response, Exception ex) { - // Copy all parameters unless overridden in the action handler. - Enumeration paramNames = request.getParameterNames(); - while (paramNames.hasMoreElements()) { - String paramName = paramNames.nextElement(); - String[] paramValues = request.getParameterValues(paramName); - if (paramValues != null && !response.getRenderParameterMap().containsKey(paramName)) { - response.setRenderParameter(paramName, paramValues); - } - } - response.setRenderParameter(ACTION_EXCEPTION_RENDER_PARAMETER, ex.toString()); - request.getPortletSession().setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, ex); - } - - - /** - * Render the given ModelAndView. This is the last stage in handling a request. - * It may involve resolving the view by name. - * @param mv the ModelAndView to render - * @param request current portlet render request - * @param response current portlet render response - * @throws Exception if there's a problem rendering the view - */ - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - View view; - if (mv.isReference()) { - // We need to resolve the view name. - view = resolveViewName(mv.getViewName(), mv.getModelInternal(), request); - if (view == null) { - throw new PortletException("Could not resolve view with name '" + mv.getViewName() + - "' in portlet with name '" + getPortletName() + "'"); - } - } - else { - // No need to lookup: the ModelAndView object contains the actual View object. - Object viewObject = mv.getView(); - if (viewObject == null) { - throw new PortletException("ModelAndView [" + mv + "] neither contains a view name nor a " + - "View object in portlet with name '" + getPortletName() + "'"); - } - if (!(viewObject instanceof View)) { - throw new PortletException( - "View object [" + viewObject + "] is not an instance of [org.springframework.web.servlet.View] - " + - "DispatcherPortlet does not support any other view types"); - } - view = (View) viewObject; - } - - // Set the content type on the response if needed and if possible. - // The Portlet spec requires the content type to be set on the RenderResponse; - // it's not sufficient to let the View set it on the ServletResponse. - if (response.getContentType() != null) { - if (logger.isDebugEnabled()) { - logger.debug("Portlet response content type already set to [" + response.getContentType() + "]"); - } - } - else { - // No Portlet content type specified yet -> use the view-determined type. - String contentType = view.getContentType(); - if (contentType != null) { - if (logger.isDebugEnabled()) { - logger.debug("Setting portlet response content type to view-determined type [" + contentType + "]"); - } - response.setContentType(contentType); - } - } - - doRender(view, mv.getModelInternal(), request, response); - } - - /** - * Resolve the given view name into a View object (to be rendered). - *

        Default implementations asks all ViewResolvers of this dispatcher. - * Can be overridden for custom resolution strategies, potentially based - * on specific model attributes or request parameters. - * @param viewName the name of the view to resolve - * @param model the model to be passed to the view - * @param request current portlet render request - * @return the View object, or null if none found - * @throws Exception if the view cannot be resolved - * (typically in case of problems creating an actual View object) - * @see ViewResolver#resolveViewName - */ - 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) { - return view; - } - } - return null; - } - - /** - * Actually render the given view. - *

        The default implementation delegates to - * {@link org.springframework.web.servlet.ViewRendererServlet}. - * @param view the View to render - * @param model the associated model - * @param request current portlet render/resource request - * @param response current portlet render/resource response - * @throws Exception if there's a problem rendering the view - */ - 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()); - - // These attributes are required by the ViewRendererServlet. - request.setAttribute(ViewRendererServlet.VIEW_ATTRIBUTE, view); - request.setAttribute(ViewRendererServlet.MODEL_ATTRIBUTE, model); - - // Include the content of the view in the render/resource response. - doDispatch(getPortletContext().getRequestDispatcher(this.viewRendererUrl), request, response); - } - - /** - * Perform a dispatch on the given PortletRequestDispatcher. - *

        The default implementation uses a forward for resource requests - * and an include for render requests. - * @param dispatcher the PortletRequestDispatcher to use - * @param request current portlet render/resource request - * @param response current portlet render/resource response - * @throws Exception if there's a problem performing the dispatch - */ - protected void doDispatch(PortletRequestDispatcher dispatcher, PortletRequest request, MimeResponse response) - throws Exception { - - // In general, we prefer a forward for resource responses, in order to have full Servlet API - // support in the target resource (e.g. on uPortal). However, on Liferay, a resource forward - // displays an empty page, so we have to resort to an include there... - if (PortletRequest.RESOURCE_PHASE.equals(request.getAttribute(PortletRequest.LIFECYCLE_PHASE)) && - !dispatcher.getClass().getName().startsWith("com.liferay")) { - dispatcher.forward(request, response); - } - else { - dispatcher.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 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 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 - * 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 triggerAfterRenderCompletion(HandlerExecutionChain mappedHandler, int interceptorIndex, - RenderRequest request, RenderResponse 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.afterRenderCompletion(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 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); - } - } - } - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java deleted file mode 100644 index 8933a4d4d4..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/FrameworkPortlet.java +++ /dev/null @@ -1,712 +0,0 @@ -/* - * Copyright 2002-2015 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; - -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.context.ApplicationContext; -import org.springframework.context.ApplicationContextException; -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.core.env.ConfigurableEnvironment; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -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.StandardPortletEnvironment; -import org.springframework.web.portlet.context.XmlPortletApplicationContext; - -/** - * Base portlet for Spring's portlet framework. Provides integration with - * a Spring application context, in a JavaBean-based overall solution. - * - *

        This class offers the following functionality: - *

          - *
        • Manages a Portlet {@link org.springframework.context.ApplicationContext} - * instance per portlet. The portlet's configuration is determined by beans - * in the portlet's namespace. - *
        • Publishes events on request processing, whether or not a request is - * successfully handled. - *
        - * - *

        Subclasses must implement {@link #doActionService} and {@link #doRenderService} - * to handle action and render requests. Because this extends {@link GenericPortletBean} - * rather than Portlet directly, bean properties are mapped onto it. Subclasses can - * override {@link #initFrameworkPortlet()} for custom initialization. - * - *

        Regards a "contextClass" parameter at the portlet init-param level, - * falling back to the default context class - * ({@link org.springframework.web.portlet.context.XmlPortletApplicationContext}) - * if not found. Note that, with the default FrameworkPortlet, - * a context class needs to implement the - * {@link org.springframework.web.portlet.context.ConfigurablePortletApplicationContext} SPI. - * - *

        Passes a "contextConfigLocation" portlet init-param to the context instance, - * parsing it into potentially multiple file paths which can be separated by any - * number of commas and spaces, like "test-portlet.xml, myPortlet.xml". - * If not explicitly specified, the context implementation is supposed to build a - * default location from the namespace of the portlet. - * - *

        Note: In case of multiple config locations, later bean definitions will - * override ones defined in earlier loaded files, at least when using one of - * Spring's default ApplicationContext implementations. This can be leveraged - * to deliberately override certain bean definitions via an extra XML file. - * - *

        The default namespace is "'portlet-name'-portlet", e.g. "test-portlet" for a - * portlet-name "test" (leading to a "/WEB-INF/test-portlet.xml" default location - * with XmlPortletApplicationContext). The namespace can also be set explicitly via - * the "namespace" portlet init-param. - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see #doActionService - * @see #doRenderService - * @see #setContextClass - * @see #setContextConfigLocation - * @see #setNamespace - */ -public abstract class FrameworkPortlet extends GenericPortletBean - implements ApplicationListener { - - /** - * Default context class for FrameworkPortlet. - * @see org.springframework.web.portlet.context.XmlPortletApplicationContext - */ - public static final Class DEFAULT_CONTEXT_CLASS = XmlPortletApplicationContext.class; - - /** - * Suffix for Portlet ApplicationContext namespaces. If a portlet of this class is - * given the name "test" in a context, the namespace used by the portlet will - * resolve to "test-portlet". - */ - public static final String DEFAULT_NAMESPACE_SUFFIX = "-portlet"; - - /** - * Prefix for the PortletContext attribute for the Portlet ApplicationContext. - * The completion is the portlet name. - */ - public static final String PORTLET_CONTEXT_PREFIX = FrameworkPortlet.class.getName() + ".CONTEXT."; - - /** - * Default USER_INFO attribute names to search for the current username: - * "user.login.id", "user.name". - */ - public static final String[] DEFAULT_USERINFO_ATTRIBUTE_NAMES = {"user.login.id", "user.name"}; - - - /** Portlet ApplicationContext implementation class to use */ - private Class contextClass = DEFAULT_CONTEXT_CLASS; - - /** Namespace for this portlet */ - private String namespace; - - /** Explicit context config location */ - private String contextConfigLocation; - - /** Should we publish the context as a PortletContext attribute? */ - private boolean publishContext = true; - - /** 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; - - /** ApplicationContext for this portlet */ - private ApplicationContext portletApplicationContext; - - /** Flag used to detect whether onRefresh has already been called */ - private boolean refreshEventReceived = false; - - - /** - * Set a custom context class. This class must be of type ApplicationContext; - * when using the default FrameworkPortlet implementation, the context class - * must also implement ConfigurablePortletApplicationContext. - * @see #createPortletApplicationContext - */ - public void setContextClass(Class contextClass) { - this.contextClass = contextClass; - } - - /** - * Return the custom context class. - */ - public Class getContextClass() { - return this.contextClass; - } - - /** - * Set a custom namespace for this portlet, - * to be used for building a default context config location. - */ - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - /** - * Return the namespace for this portlet, falling back to default scheme if - * no custom namespace was set. (e.g. "test-portlet" for a portlet named "test") - */ - public String getNamespace() { - return (this.namespace != null) ? this.namespace : getPortletName() + DEFAULT_NAMESPACE_SUFFIX; - } - - /** - * Set the context config location explicitly, instead of relying on the default - * location built from the namespace. This location string can consist of - * multiple locations separated by any number of commas and spaces. - */ - public void setContextConfigLocation(String contextConfigLocation) { - this.contextConfigLocation = contextConfigLocation; - } - - /** - * Return the explicit context config location, if any. - */ - public String getContextConfigLocation() { - return this.contextConfigLocation; - } - - /** - * Set whether to publish this portlet's context as a PortletContext attribute, - * available to all objects in the web container. Default is true. - *

        This is especially handy during testing, although it is debatable whether - * it's good practice to let other application objects access the context this way. - */ - public void setPublishContext(boolean publishContext) { - this.publishContext = 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 - * improvement, provided that no ApplicationListeners rely on such events. - * @see org.springframework.web.portlet.context.PortletRequestHandledEvent - */ - public void setPublishEvents(boolean publishEvents) { - this.publishEvents = publishEvents; - } - - /** - * Set whether to expose the LocaleContext and RequestAttributes as inheritable - * for child threads (using an {@link java.lang.InheritableThreadLocal}). - *

        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). - *

        WARNING: 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; - } - - /** - * Set the list of attributes to search in the USER_INFO map when trying - * to find the username of the current user. - * @see #getUsernameForRequest - */ - public void setUserinfoUsernameAttributes(String[] userinfoUsernameAttributes) { - this.userinfoUsernameAttributes = userinfoUsernameAttributes; - } - - - /** - * Overridden method of GenericPortletBean, invoked after any bean properties - * have been set. Creates this portlet's ApplicationContext. - */ - @Override - protected final void initPortletBean() throws PortletException { - getPortletContext().log("Initializing Spring FrameworkPortlet '" + getPortletName() + "'"); - if (logger.isInfoEnabled()) { - logger.info("FrameworkPortlet '" + getPortletName() + "': initialization started"); - } - long startTime = System.currentTimeMillis(); - - try { - this.portletApplicationContext = initPortletApplicationContext(); - initFrameworkPortlet(); - } - catch (PortletException ex) { - logger.error("Context initialization failed", ex); - throw ex; - } - catch (RuntimeException ex) { - logger.error("Context initialization failed", ex); - throw ex; - } - - if (logger.isInfoEnabled()) { - long elapsedTime = System.currentTimeMillis() - startTime; - logger.info("FrameworkPortlet '" + getPortletName() + "': initialization completed in " + elapsedTime + " ms"); - } - } - - /** - * Initialize and publish the Portlet ApplicationContext for this portlet. - *

        Delegates to {@link #createPortletApplicationContext} for actual creation. - * Can be overridden in subclasses. - * @return the ApplicationContext for this portlet - */ - protected ApplicationContext initPortletApplicationContext() { - ApplicationContext parent = PortletApplicationContextUtils.getWebApplicationContext(getPortletContext()); - ApplicationContext pac = createPortletApplicationContext(parent); - - if (!this.refreshEventReceived) { - // Apparently not a ConfigurableApplicationContext with refresh support: - // triggering initial onRefresh manually here. - onRefresh(pac); - } - - if (this.publishContext) { - // publish the context as a portlet context attribute - String attName = getPortletContextAttributeName(); - getPortletContext().setAttribute(attName, pac); - if (logger.isDebugEnabled()) { - logger.debug("Published ApplicationContext of portlet '" + getPortletName() + - "' as PortletContext attribute with name [" + attName + "]"); - } - } - return pac; - } - - /** - * Instantiate the Portlet ApplicationContext for this portlet, either a default - * XmlPortletApplicationContext or a custom context class if set. - *

        This implementation expects custom contexts to implement - * ConfigurablePortletApplicationContext. Can be overridden in subclasses. - * @param parent the parent ApplicationContext to use, or null if none - * @return the Portlet ApplicationContext for this portlet - * @see #setContextClass - * @see org.springframework.web.portlet.context.XmlPortletApplicationContext - */ - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) { - Class contextClass = getContextClass(); - if (logger.isDebugEnabled()) { - logger.debug("Portlet with name '" + getPortletName() + - "' will try to create custom ApplicationContext context of class '" + - contextClass.getName() + "'" + ", using parent context [" + parent + "]"); - } - if (!ConfigurablePortletApplicationContext.class.isAssignableFrom(contextClass)) { - throw new ApplicationContextException("Fatal initialization error in portlet with name '" + getPortletName() + - "': custom ApplicationContext class [" + contextClass.getName() + - "] is not of type ConfigurablePortletApplicationContext"); - } - ConfigurablePortletApplicationContext pac = - (ConfigurablePortletApplicationContext) BeanUtils.instantiateClass(contextClass); - - // Assign the best possible id value. - String portletContextName = getPortletContext().getPortletContextName(); - if (portletContextName != null) { - pac.setId(ConfigurablePortletApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + portletContextName + "." + getPortletName()); - } - else { - pac.setId(ConfigurablePortletApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + getPortletName()); - } - - pac.setEnvironment(getEnvironment()); - pac.setParent(parent); - pac.setPortletContext(getPortletContext()); - pac.setPortletConfig(getPortletConfig()); - pac.setNamespace(getNamespace()); - pac.setConfigLocation(getContextConfigLocation()); - pac.addApplicationListener(new SourceFilteringListener(pac, this)); - - // The wac environment's #initPropertySources will be called in any case when the context - // is refreshed; do it eagerly here to ensure portlet property sources are in place for - // use in any post-processing or initialization that occurs below prior to #refresh - ConfigurableEnvironment env = pac.getEnvironment(); - if (env instanceof StandardPortletEnvironment) { - ((StandardPortletEnvironment) env).initPropertySources(pac.getServletContext(), getPortletContext(), getPortletConfig()); - } - - postProcessPortletApplicationContext(pac); - pac.refresh(); - - return pac; - } - - /** - * Post-process the given Portlet ApplicationContext before it is refreshed - * and activated as context for this portlet. - *

        The default implementation is empty. {@code refresh()} will - * be called automatically after this method returns. - * @param pac the configured Portlet ApplicationContext (not refreshed yet) - * @see #createPortletApplicationContext - * @see ConfigurableApplicationContext#refresh() - */ - protected void postProcessPortletApplicationContext(ConfigurableApplicationContext pac) { - } - - /** - * Return the PortletContext attribute name for this portlets's ApplicationContext. - *

        The default implementation returns PORTLET_CONTEXT_PREFIX + portlet name. - * @see #PORTLET_CONTEXT_PREFIX - * @see #getPortletName - */ - public String getPortletContextAttributeName() { - return PORTLET_CONTEXT_PREFIX + getPortletName(); - } - - /** - * Return this portlet's ApplicationContext. - */ - public final ApplicationContext getPortletApplicationContext() { - return this.portletApplicationContext; - } - - - /** - * This method will be invoked after any bean properties have been set and - * the ApplicationContext has been loaded. - *

        The default implementation is empty; subclasses may override this method - * to perform any initialization they require. - * @throws PortletException in case of an initialization exception - */ - protected void initFrameworkPortlet() throws PortletException { - } - - /** - * Refresh this portlet's application context, as well as the - * dependent state of the portlet. - * @see #getPortletApplicationContext() - * @see org.springframework.context.ConfigurableApplicationContext#refresh() - */ - public void refresh() { - ApplicationContext pac = getPortletApplicationContext(); - if (!(pac instanceof ConfigurableApplicationContext)) { - throw new IllegalStateException("Portlet ApplicationContext does not support refresh: " + pac); - } - ((ConfigurableApplicationContext) pac).refresh(); - } - - /** - * ApplicationListener endpoint that receives events from this servlet's - * WebApplicationContext. - *

        The default implementation calls {@link #onRefresh} in case of a - * {@link org.springframework.context.event.ContextRefreshedEvent}, - * triggering a refresh of this servlet's context-dependent state. - * @param event the incoming ApplicationContext event - */ - @Override - public void onApplicationEvent(ContextRefreshedEvent event) { - this.refreshEventReceived = true; - onRefresh(event.getApplicationContext()); - } - - /** - * Template method which can be overridden to add portlet-specific refresh work. - * Called after successful context refresh. - *

        This implementation is empty. - * @param context the current Portlet ApplicationContext - * @see #refresh() - */ - protected void onRefresh(ApplicationContext context) { - // For subclasses: do nothing by default. - } - - - /** - * Overridden for friendlier behavior in unit tests. - */ - @Override - protected String getTitle(RenderRequest renderRequest) { - try { - return super.getTitle(renderRequest); - } - catch (NullPointerException ex) { - return getPortletName(); - } - } - - /** - * 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. - */ - @Override - protected final void doDispatch(RenderRequest request, RenderResponse response) - throws PortletException, IOException { - - processRequest(request, response); - } - - @Override - 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 - * {@code doActionService()} and {@code doRenderService()} template methods. - * @see #doActionService - * @see #doRenderService - */ - protected final void processRequest(PortletRequest request, PortletResponse response) - throws PortletException, IOException { - - 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 = null; - if (previousRequestAttributes == null || - PortletRequestAttributes.class == previousRequestAttributes.getClass() || - ServletRequestAttributes.class == previousRequestAttributes.getClass()) { - requestAttributes = new PortletRequestAttributes(request, response); - RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); - } - - if (logger.isTraceEnabled()) { - logger.trace("Bound request context to thread: " + request); - } - - try { - String phase = (String) request.getAttribute(PortletRequest.LIFECYCLE_PHASE); - if (PortletRequest.ACTION_PHASE.equals(phase)) { - doActionService((ActionRequest) request, (ActionResponse) response); - } - 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; - throw ex; - } - catch (IOException ex) { - failureCause = ex; - throw ex; - } - catch (Throwable ex) { - failureCause = ex; - throw new PortletException("Request processing failed", ex); - } - - finally { - // Clear request attributes and reset thread-bound context. - LocaleContextHolder.setLocaleContext(previousLocaleContext, this.threadContextInheritable); - if (requestAttributes != null) { - RequestContextHolder.setRequestAttributes(previousRequestAttributes, this.threadContextInheritable); - 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 (this.publishEvents) { - // Whether or not we succeeded, publish an event. - long processingTime = System.currentTimeMillis() - startTime; - this.portletApplicationContext.publishEvent( - new PortletRequestHandledEvent(this, - getPortletConfig().getPortletName(), request.getPortletMode().toString(), - (request instanceof ActionRequest ? "action" : "render"), - request.getRequestedSessionId(), getUsernameForRequest(request), - processingTime, failureCause)); - } - } - } - - /** - * 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. - *

        The default implementation first tries the UserPrincipal. - * If that does not exist, then it checks the USER_INFO map. - * Can be overridden in subclasses. - * @param request current portlet request - * @return the username, or {@code null} if none found - * @see javax.portlet.PortletRequest#getUserPrincipal() - * @see javax.portlet.PortletRequest#getRemoteUser() - * @see javax.portlet.PortletRequest#USER_INFO - * @see #setUserinfoUsernameAttributes - */ - protected String getUsernameForRequest(PortletRequest request) { - // Try the principal. - Principal userPrincipal = request.getUserPrincipal(); - if (userPrincipal != null) { - return userPrincipal.getName(); - } - - // Try the remote user name. - String userName = request.getRemoteUser(); - if (userName != null) { - return userName; - } - - // Try the Portlet USER_INFO map. - Map userInfo = (Map) request.getAttribute(PortletRequest.USER_INFO); - if (userInfo != null) { - for (int i = 0, n = this.userinfoUsernameAttributes.length; i < n; i++) { - userName = (String) userInfo.get(this.userinfoUsernameAttributes[i]); - if (userName != null) { - return userName; - } - } - } - - // Nothing worked... - return null; - } - - - /** - * Subclasses must implement this method to do the work of action request handling. - *

        The contract is essentially the same as that for the {@code processAction} - * method of GenericPortlet. - *

        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. - *

        The contract is essentially the same as that for the {@code doDispatch} - * method of GenericPortlet. - *

        This class intercepts calls to ensure that exception handling and - * event publication takes place. - * @param request current render request - * @param response current render response - * @throws Exception in case of any kind of processing failure - * @see javax.portlet.GenericPortlet#doDispatch - */ - protected abstract void doRenderService(RenderRequest request, RenderResponse response) - throws Exception; - - /** - * Subclasses must implement this method to do the work of resource request handling. - *

        The contract is essentially the same as that for the {@code serveResource} - * method of GenericPortlet. - *

        This class intercepts calls to ensure that exception handling and - * event publication takes place. - * @param request current resource request - * @param response current resource response - * @throws Exception in case of any kind of processing failure - * @see javax.portlet.GenericPortlet#serveResource - */ - protected abstract void doResourceService(ResourceRequest request, ResourceResponse response) - throws Exception; - - /** - * Subclasses must implement this method to do the work of event request handling. - *

        The contract is essentially the same as that for the {@code processEvent} - * method of GenericPortlet. - *

        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; - - - /** - * Close the ApplicationContext of this portlet. - * @see org.springframework.context.ConfigurableApplicationContext#close() - */ - @Override - public void destroy() { - getPortletContext().log("Destroying Spring FrameworkPortlet '" + getPortletName() + "'"); - if (this.portletApplicationContext instanceof ConfigurableApplicationContext) { - ((ConfigurableApplicationContext) this.portletApplicationContext).close(); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/GenericPortletBean.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/GenericPortletBean.java deleted file mode 100644 index bcbf08fc96..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/GenericPortletBean.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import javax.portlet.GenericPortlet; -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.portlet.PortletException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.BeanWrapper; -import org.springframework.beans.BeansException; -import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.PropertyAccessorFactory; -import org.springframework.beans.PropertyValue; -import org.springframework.beans.PropertyValues; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.Environment; -import org.springframework.core.env.EnvironmentCapable; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceEditor; -import org.springframework.core.io.ResourceLoader; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import org.springframework.web.portlet.context.PortletContextResourceLoader; -import org.springframework.web.portlet.context.StandardPortletEnvironment; - -/** - * Simple extension of {@code javax.portlet.GenericPortlet} that treats - * its config parameters as bean properties. - * - *

        A very handy superclass for any type of portlet. Type conversion is automatic. - * It is also possible for subclasses to specify required properties. - * - *

        This portlet leaves request handling to subclasses, inheriting the default - * behaviour of GenericPortlet ({@code doDispatch}, {@code processAction}, etc). - * - *

        This portlet superclass has no dependency on a Spring application context, - * in contrast to the FrameworkPortlet class which loads its own context. - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see #addRequiredProperty - * @see #initPortletBean - * @see #doDispatch - * @see #processAction - * @see FrameworkPortlet - */ -public abstract class GenericPortletBean extends GenericPortlet - implements EnvironmentCapable, EnvironmentAware { - - /** Logger available to subclasses */ - protected final Log logger = LogFactory.getLog(getClass()); - - /** - * Set of required properties (Strings) that must be supplied as - * config parameters to this portlet. - */ - private final Set requiredProperties = new HashSet(); - - private ConfigurableEnvironment environment; - - - /** - * Subclasses can invoke this method to specify that this property - * (which must match a JavaBean property they expose) is mandatory, - * and must be supplied as a config parameter. This method would - * normally be called from a subclass constructor. - * @param property name of the required property - */ - protected final void addRequiredProperty(String property) { - this.requiredProperties.add(property); - } - - /** - * Map config parameters onto bean properties of this portlet, and - * invoke subclass initialization. - * @throws PortletException if bean properties are invalid (or required - * properties are missing), or if subclass initialization fails. - */ - @Override - public final void init() throws PortletException { - if (logger.isInfoEnabled()) { - logger.info("Initializing portlet '" + getPortletName() + "'"); - } - - // Set bean properties from init parameters. - try { - PropertyValues pvs = new PortletConfigPropertyValues(getPortletConfig(), this.requiredProperties); - BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); - ResourceLoader resourceLoader = new PortletContextResourceLoader(getPortletContext()); - bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment())); - initBeanWrapper(bw); - bw.setPropertyValues(pvs, true); - } - catch (BeansException ex) { - logger.error("Failed to set bean properties on portlet '" + getPortletName() + "'", ex); - throw ex; - } - - // let subclasses do whatever initialization they like - initPortletBean(); - - if (logger.isInfoEnabled()) { - logger.info("Portlet '" + getPortletName() + "' configured successfully"); - } - } - - /** - * Initialize the BeanWrapper for this GenericPortletBean, - * possibly with custom editors. - * @param bw the BeanWrapper to initialize - * @throws BeansException if thrown by BeanWrapper methods - * @see org.springframework.beans.BeanWrapper#registerCustomEditor - */ - protected void initBeanWrapper(BeanWrapper bw) throws BeansException { - } - - - /** - * Overridden method that simply returns {@code null} when no - * PortletConfig set yet. - * @see #getPortletConfig() - */ - @Override - public final String getPortletName() { - return (getPortletConfig() != null ? getPortletConfig().getPortletName() : null); - } - - /** - * Overridden method that simply returns {@code null} when no - * PortletConfig set yet. - * @see #getPortletConfig() - */ - @Override - public final PortletContext getPortletContext() { - return (getPortletConfig() != null ? getPortletConfig().getPortletContext() : null); - } - - - /** - * Subclasses may override this to perform custom initialization. - * All bean properties of this portlet will have been set before this - * method is invoked. This default implementation does nothing. - * @throws PortletException if subclass initialization fails - */ - protected void initPortletBean() throws PortletException { - } - - /** - * {@inheritDoc} - * @throws IllegalArgumentException if environment is not assignable to - * {@code ConfigurableEnvironment}. - */ - @Override - public void setEnvironment(Environment environment) { - Assert.isInstanceOf(ConfigurableEnvironment.class, environment); - this.environment = (ConfigurableEnvironment)environment; - } - - /** - * {@inheritDoc} - *

        If {@code null}, a new environment will be initialized via - * {@link #createEnvironment()}. - */ - @Override - public ConfigurableEnvironment getEnvironment() { - if (this.environment == null) { - this.environment = this.createEnvironment(); - } - return this.environment; - } - - /** - * Create and return a new {@link StandardPortletEnvironment}. Subclasses may override - * in order to configure the environment or specialize the environment type returned. - */ - protected ConfigurableEnvironment createEnvironment() { - return new StandardPortletEnvironment(); - } - - - /** - * PropertyValues implementation created from PortletConfig init parameters. - */ - @SuppressWarnings("serial") - private static class PortletConfigPropertyValues extends MutablePropertyValues { - - /** - * Create new PortletConfigPropertyValues. - * @param config PortletConfig we'll use to take PropertyValues from - * @param requiredProperties set of property names we need, where - * we can't accept default values - * @throws PortletException if any required properties are missing - */ - private PortletConfigPropertyValues(PortletConfig config, Set requiredProperties) - throws PortletException { - - Set missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ? - new HashSet(requiredProperties) : null; - - Enumeration en = config.getInitParameterNames(); - while (en.hasMoreElements()) { - String property = en.nextElement(); - Object value = config.getInitParameter(property); - addPropertyValue(new PropertyValue(property, value)); - if (missingProps != null) { - missingProps.remove(property); - } - } - - // fail if we are still missing properties - if (missingProps != null && missingProps.size() > 0) { - throw new PortletException( - "Initialization from PortletConfig for portlet '" + config.getPortletName() + - "' failed; the following required properties were missing: " + - StringUtils.collectionToDelimitedString(missingProps, ", ")); - } - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerAdapter.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerAdapter.java deleted file mode 100644 index 9785904d11..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerAdapter.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2002-2012 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; - -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. - * - *

        Interface that must be implemented for each handler type to handle a request. - * This interface is used to allow the DispatcherPortlet to be indefinitely - * extensible. The DispatcherPortlet accesses all installed handlers through this - * interface, meaning that it does not contain code specific to any handler type. - * - *

        Note that a handler can be of type Object. This is to enable handlers from - * other frameworks to be integrated with this framework without custom coding. - * - *

        This interface is not intended for application developers. It is available - * to handlers who want to develop their own web workflow. - * - *

        Note: Implementations can implement the Ordered interface to be able to - * specify a sorting order and thus a priority for getting applied by - * DispatcherPortlet. Non-Ordered instances get treated as lowest priority. - * - * @author John A. Lewis - * @since 2.0 - * @see org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter - */ -public interface HandlerAdapter { - - /** - * Given a handler instance, return whether or not this HandlerAdapter can - * support it. Typical HandlerAdapters will base the decision on the handler - * type. HandlerAdapters will usually only support one handler type each. - *

        A typical implementation: - *

        {@code - * return (handler instanceof MyHandler); - * } - * @param handler handler object to check - * @return whether or not this object can use the given handler - */ - boolean supports(Object handler); - - /** - * Use the given handler to handle this action 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} 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; - - /** - * Use the given handler to handle this render 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} method of this interface, which must have - * returned {@code true}. - * @throws Exception in case of errors - * @return ModelAndView object with the name of the view and the required - * model data, or {@code null} 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} method of this interface, which must have - * returned {@code true}. - * @throws Exception in case of errors - * @return ModelAndView object with the name of the view and the required - * model data, or {@code null} 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} 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; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExceptionResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExceptionResolver.java deleted file mode 100644 index c43b889215..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExceptionResolver.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2002-2012 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; - -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 - * during handler mapping or execution, in the typical case to error views. - * Implementors are typically registered as beans in the application context. - * - *

        Error views are analogous to the error page JSPs, but can be used with - * any kind of exception including any checked exception, with potentially - * fine-granular mappings for specific handlers. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - */ -public interface HandlerExceptionResolver { - - /** - * 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 {@code null} for default processing - */ - 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 {@code null} for default processing - */ - ModelAndView resolveException( - ResourceRequest request, ResourceResponse response, Object handler, Exception ex); - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java deleted file mode 100644 index e09a019868..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerExecutionChain.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2002-2014 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; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.springframework.util.CollectionUtils; -import org.springframework.util.ObjectUtils; - -/** - * Handler execution chain, consisting of handler object and any handler interceptors. - * Returned by HandlerMapping's {@link HandlerMapping#getHandler} method. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see HandlerInterceptor - */ -public class HandlerExecutionChain { - - private final Object handler; - - private HandlerInterceptor[] interceptors; - - private List interceptorList; - - - /** - * Create a new HandlerExecutionChain. - * @param handler the handler object to execute - */ - public HandlerExecutionChain(Object handler) { - this(handler, (HandlerInterceptor[]) null); - } - - /** - * Create a new HandlerExecutionChain. - * @param handler the handler object to execute - * @param interceptors the array of interceptors to apply - * (in the given order) before the handler itself executes - */ - public HandlerExecutionChain(Object handler, HandlerInterceptor... interceptors) { - if (handler instanceof HandlerExecutionChain) { - HandlerExecutionChain originalChain = (HandlerExecutionChain) handler; - this.handler = originalChain.getHandler(); - this.interceptorList = new ArrayList(); - CollectionUtils.mergeArrayIntoCollection(originalChain.getInterceptors(), this.interceptorList); - CollectionUtils.mergeArrayIntoCollection(interceptors, this.interceptorList); - } - else { - this.handler = handler; - this.interceptors = interceptors; - } - } - - - /** - * Return the handler object to execute. - * @return the handler object - */ - public Object getHandler() { - return this.handler; - } - - public void addInterceptor(HandlerInterceptor interceptor) { - initInterceptorList().add(interceptor); - } - - public void addInterceptors(HandlerInterceptor... interceptors) { - if (!ObjectUtils.isEmpty(interceptors)) { - initInterceptorList().addAll(Arrays.asList(interceptors)); - } - } - - private List initInterceptorList() { - if (this.interceptorList == null) { - this.interceptorList = new ArrayList(); - if (this.interceptors != null) { - // An interceptor array specified through the constructor - this.interceptorList.addAll(Arrays.asList(this.interceptors)); - } - } - this.interceptors = null; - return this.interceptorList; - } - - /** - * Return the array of interceptors to apply (in the given order). - * @return the array of HandlerInterceptors instances (may be {@code null}) - */ - public HandlerInterceptor[] getInterceptors() { - if (this.interceptors == null && this.interceptorList != null) { - this.interceptors = this.interceptorList.toArray(new HandlerInterceptor[this.interceptorList.size()]); - } - return this.interceptors; - } - - - /** - * Delegates to the handler's {@code toString()}. - */ - @Override - public String toString() { - return String.valueOf(this.handler); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerInterceptor.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerInterceptor.java deleted file mode 100644 index af442a75d5..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerInterceptor.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright 2002-2014 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; - -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; - -/** - * Workflow interface that allows for customized handler execution chains. - * Applications can register any number of existing or custom interceptors - * for certain groups of handlers, to add common pre-processing behavior - * without needing to modify each handler implementation. - * - *

        A {@code HandlerInterceptor} gets called before the appropriate - * {@link HandlerAdapter} triggers the - * execution of the handler itself. This mechanism can be used for a large - * field of preprocessing aspects, e.g. for authorization checks, - * or common handler behavior like locale or theme changes. Its main purpose - * is to permit the factoring out of otherwise repetitive handler code. - * - *

        Typically an interceptor chain is defined per - * {@link HandlerMapping} bean, sharing its - * granularity. To be able to apply a certain interceptor chain to a group of - * handlers, one needs to map the desired handlers via one - * {@code HandlerMapping} bean. The interceptors themselves are defined as - * beans in the application context, referenced by the mapping bean definition - * via its - * {@link org.springframework.web.portlet.handler.AbstractHandlerMapping#setInterceptors "interceptors"} - * property (in XML: a <list> of <ref> elements). - * - *

        A {@code HandlerInterceptor} is basically similar to a Servlet - * {@link javax.servlet.Filter}, but in contrast to the latter it allows - * custom pre-processing with the option to prohibit the execution of the handler - * itself, and custom post-processing. {@code Filters} are more powerful; - * for example they allow for exchanging the request and response objects that - * are handed down the chain. Note that a filter gets configured in - * {@code web.xml}, a {@code HandlerInterceptor} in the application context. - * - *

        As a basic guideline, fine-grained handler-related pre-processing tasks are - * candidates for {@code HandlerInterceptor} implementations, especially - * factored-out common handler code and authorization checks. On the other hand, - * a {@code Filter} is well-suited for request content and view content - * handling, like multipart forms and GZIP compression. This typically shows when - * one needs to map the filter to certain content types (e.g. images), or to all - * requests. - * - *

        Be aware that filters cannot be applied to portlet requests (they - * only operate on servlet requests), so for portlet requests interceptors are - * essential. - * - *

        If we assume a "sunny day" request cycle (i.e. a request where nothing goes wrong - * and all is well), the workflow of a {@code HandlerInterceptor} will be as - * follows: - * - *

        Action Request:

        - *

          - *
        1. {@code DispatcherPortlet} maps the action request to a particular handler and - * assembles a handler execution chain consisting of the handler that is to be invoked - * and all of the {@code HandlerInterceptor} instances that apply to the request.
        2. - *
        3. {@link HandlerInterceptor#preHandleAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse, Object) preHandleAction(..)} - * is called; if the invocation of this method returns {@code true} then this workflow continues.
        4. - *
        5. The target handler handles the action request (via - * {@link HandlerAdapter#handleAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse, Object) HandlerAdapter.handleAction(..)}).
        6. - *
        7. {@link HandlerInterceptor#afterActionCompletion(javax.portlet.ActionRequest, javax.portlet.ActionResponse, Object, Exception) afterActionCompletion(..)} - * is called.
        8. - *
        - * - *

        Render Request:

        - *

          - *
        1. {@code DispatcherPortlet} maps the render request to a particular handler and - * assembles a handler execution chain consisting of the handler that is to be invoked - * and all of the {@code HandlerInterceptor} instances that apply to the request.
        2. - *
        3. {@link HandlerInterceptor#preHandleRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse, Object) preHandleRender(..)} - * is called; if the invocation of this method returns {@code true} then this workflow continues.
        4. - *
        5. The target handler handles the render request (via - * {@link HandlerAdapter#handleRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse, Object) HandlerAdapter.handleRender(..)}).
        6. - *
        7. {@link HandlerInterceptor#postHandleRender(javax.portlet.RenderRequest, javax.portlet.RenderResponse, Object, ModelAndView) postHandleRender(..)} - * is called.
        8. - *
        9. If the {@code HandlerAdapter} returned a {@code ModelAndView}, then - * {@code DispatcherPortlet} renders the view accordingly. - *
        10. {@link HandlerInterceptor#afterRenderCompletion(javax.portlet.RenderRequest, javax.portlet.RenderResponse, Object, Exception) afterRenderCompletion(..)} - * is called.
        11. - *
        - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see HandlerExecutionChain#getInterceptors - * @see HandlerMapping - * @see org.springframework.web.portlet.handler.AbstractHandlerMapping#setInterceptors - * @see HandlerExecutionChain - */ -public interface HandlerInterceptor { - - /** - * Intercept the execution of a handler in the action phase. - *

        Called after a HandlerMapping determines an appropriate handler object - * to handle an {@link ActionRequest}, but before said HandlerAdapter actually - * invokes the handler. - *

        {@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} if the execution chain should proceed with the - * next interceptor or the handler itself. Else, {@code DispatcherPortlet} - * assumes that this interceptor has already dealt with the response itself - * @throws Exception in case of errors - */ - boolean preHandleAction(ActionRequest request, ActionResponse 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. - *

        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}! - * @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}) - * @throws Exception in case of errors - */ - void afterActionCompletion(ActionRequest request, ActionResponse response, Object handler, Exception ex) - throws Exception; - - /** - * Intercept the execution of a handler in the render phase. - *

        Called after a HandlerMapping determines an appropriate handler object - * to handle a {@link RenderRequest}, but before said HandlerAdapter actually - * invokes the handler. - *

        {@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} if the execution chain should proceed with the - * next interceptor or the handler itself. Else, {@code DispatcherPortlet} - * assumes that this interceptor has already dealt with the response itself - * @throws Exception in case of errors - */ - boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) - throws Exception; - - /** - * Intercept the execution of a handler in the render phase. - *

        Called after a {@link HandlerAdapter} actually invoked the handler, but - * before the {@code DispatcherPortlet} renders the view. Can thus expose - * additional model objects to the view via the given {@link ModelAndView}. - *

        {@code 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 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} that the handler returned - * (can also be {@code null}) - * @throws Exception in case of errors - */ - void postHandleRender(RenderRequest request, RenderResponse 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. - *

        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}! - * @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 afterRenderCompletion(RenderRequest request, RenderResponse response, Object handler, Exception ex) - throws Exception; - - /** - * Intercept the execution of a handler in the render phase. - *

        Called after a HandlerMapping determines an appropriate handler object - * to handle a {@link RenderRequest}, but before said HandlerAdapter actually - * invokes the handler. - *

        {@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} if the execution chain should proceed with the - * next interceptor or the handler itself. Else, {@code DispatcherPortlet} - * 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. - *

        Called after a {@link HandlerAdapter} actually invoked the handler, but - * before the {@code DispatcherPortlet} renders the view. Can thus expose - * additional model objects to the view via the given {@link ModelAndView}. - *

        {@code 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 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} that the handler returned - * (can also be {@code null}) - * @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. - *

        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}! - * @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. - *

        Called after a HandlerMapping determines an appropriate handler object - * to handle an {@link ActionRequest}, but before said HandlerAdapter actually - * invokes the handler. - *

        {@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} if the execution chain should proceed with the - * next interceptor or the handler itself. Else, {@code DispatcherPortlet} - * 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. - *

        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}! - * @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}) - * @throws Exception in case of errors - */ - void afterEventCompletion(EventRequest request, EventResponse response, Object handler, Exception ex) - throws Exception; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerMapping.java deleted file mode 100644 index 388d0ec21d..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/HandlerMapping.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletRequest; - -/** - * Interface to be implemented by objects that define a mapping between - * requests and handler objects. - * - *

        This class can be implemented by application developers, although this is not - * necessary, as {@link org.springframework.web.portlet.handler.PortletModeHandlerMapping}, - * {@link org.springframework.web.portlet.handler.ParameterHandlerMapping} and - * {@link org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping} - * are included in the framework. The first is the default if no HandlerMapping - * bean is registered in the portlet application context. - * - *

        HandlerMapping implementations can support mapped interceptors but do not - * have to. A handler will always be wrapped in a {@link HandlerExecutionChain} - * instance, optionally accompanied by some {@link HandlerInterceptor} instances. - * The DispatcherPortlet will first call each HandlerInterceptor's - * {@code preHandle} method in the given order, finally invoking the handler - * itself if all {@code preHandle} methods have returned {@code true}. - * - *

        The ability to parameterize this mapping is a powerful and unusual - * capability of this Portlet MVC framework. For example, it is possible to - * write a custom mapping based on session state, cookie state or many other - * variables. No other MVC framework seems to be equally flexible. - * - *

        Note: Implementations can implement the {@link org.springframework.core.Ordered} - * interface to be able to specify a sorting order and thus a priority for getting - * applied by DispatcherPortlet. Non-Ordered instances get treated as lowest priority. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @see org.springframework.core.Ordered - * @see org.springframework.web.portlet.handler.AbstractHandlerMapping - * @see org.springframework.web.portlet.handler.PortletModeHandlerMapping - * @see org.springframework.web.portlet.handler.ParameterHandlerMapping - * @see org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping - */ -public interface HandlerMapping { - - /** - * Return a handler and any interceptors for this request. The choice may be made - * on portlet mode, session state, or any factor the implementing class chooses. - *

        The returned HandlerExecutionChain contains a handler Object, rather than - * even a tag interface, so that handlers are not constrained in any way. - * For example, a HandlerAdapter could be written to allow another framework's - * handler objects to be used. - *

        Returns {@code null} if no match was found. This is not an error. - * The DispatcherPortlet will query all registered HandlerMapping beans to find - * a match, and only decide there is an error if none can find a handler. - * @param request current portlet request - * @return a HandlerExecutionChain instance containing handler object and - * any interceptors, or null if no mapping found - * @throws Exception if there is an internal error - */ - HandlerExecutionChain getHandler(PortletRequest request) throws Exception; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java deleted file mode 100644 index fb6f8521b4..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndView.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import java.util.Map; - -import org.springframework.ui.ModelMap; -import org.springframework.util.CollectionUtils; - -/** - * Holder for both Model and View in the web MVC framework. - * Note that these are entirely distinct. This class merely holds - * both to make it possible for a controller to return both model - * and view in a single return value. - * - *

        Represents a model and view returned by a handler, to be resolved - * by a DispatcherPortlet. The view can take the form of a String - * view name which will need to be resolved by a ViewResolver object; - * alternatively a view object can be specified directly. The model - * is a Map, allowing the use of multiple objects keyed by name. - * - * @author Juergen Hoeller - * @since 2.0 - * @see org.springframework.web.portlet.DispatcherPortlet - * @see org.springframework.web.servlet.ViewResolver - * @see org.springframework.web.portlet.HandlerAdapter - * @see org.springframework.web.portlet.mvc.Controller - */ -public class ModelAndView { - - /** View instance or view name String */ - private Object view; - - /** Model Map */ - private ModelMap model; - - /** - * Indicates whether or not this instance has been cleared with a call to {@link #clear()}. - */ - private boolean cleared = false; - - - /** - * Default constructor for bean-style usage: populating bean - * properties instead of passing in constructor arguments. - * @see #setView(Object) - * @see #setViewName(String) - */ - public ModelAndView() { - } - - /** - * Convenient constructor when there is no model data to expose. - * Can also be used in conjunction with {@code addObject}. - * @param viewName name of the View to render, to be resolved - * by the DispatcherPortlet's ViewResolver - * @see #addObject - */ - public ModelAndView(String viewName) { - this.view = viewName; - } - - /** - * Convenient constructor when there is no model data to expose. - * Can also be used in conjunction with {@code addObject}. - * @param view View object to render (usually a Servlet MVC View object) - * @see #addObject - */ - public ModelAndView(Object view) { - this.view = view; - } - - /** - * Create a new ModelAndView given a view name and a model. - * @param viewName name of the View to render, to be resolved - * by the DispatcherPortlet's ViewResolver - * @param model Map of model names (Strings) to model objects - * (Objects). Model entries may not be {@code null}, but the - * model Map may be {@code null} if there is no model data. - */ - public ModelAndView(String viewName, Map model) { - this.view = viewName; - if (model != null) { - getModelMap().addAllAttributes(model); - } - } - - /** - * Create a new ModelAndView given a View object and a model. - * @param view View object to render (usually a Servlet MVC View object) - * @param model Map of model names (Strings) to model objects - * (Objects). Model entries may not be {@code null}, but the - * model Map may be {@code null} if there is no model data. - */ - public ModelAndView(Object view, Map model) { - this.view = view; - if (model != null) { - getModelMap().addAllAttributes(model); - } - } - - /** - * Convenient constructor to take a single model object. - * @param viewName name of the View to render, to be resolved - * by the DispatcherPortlet's ViewResolver - * @param modelName name of the single entry in the model - * @param modelObject the single model object - */ - public ModelAndView(String viewName, String modelName, Object modelObject) { - this.view = viewName; - addObject(modelName, modelObject); - } - - /** - * Convenient constructor to take a single model object. - * @param view View object to render (usually a Servlet MVC View object) - * @param modelName name of the single entry in the model - * @param modelObject the single model object - */ - public ModelAndView(Object view, String modelName, Object modelObject) { - this.view = view; - addObject(modelName, modelObject); - } - - - /** - * Set a view name for this ModelAndView, to be resolved by the - * DispatcherPortlet via a ViewResolver. Will override any - * pre-existing view name or View. - */ - public void setViewName(String viewName) { - this.view = viewName; - } - - /** - * Return the view name to be resolved by the DispatcherPortlet - * via a ViewResolver, or {@code null} if we are using a view object. - */ - public String getViewName() { - return (this.view instanceof String ? (String) this.view : null); - } - - /** - * Set a View object for this ModelAndView. Will override any - * pre-existing view name or View. - *

        The given View object will usually be a Servlet MVC View object. - * This is nevertheless typed as Object to avoid a Servlet API dependency - * in the Portlet ModelAndView class. - */ - public void setView(Object view) { - this.view = view; - } - - /** - * Return the View object, or {@code null} if we are using a view name - * to be resolved by the DispatcherPortlet via a ViewResolver. - */ - public Object getView() { - return (!(this.view instanceof String) ? this.view : null); - } - - /** - * Indicate whether or not this {@code ModelAndView} has a view, either - * as a view name or as a direct view instance. - */ - public boolean hasView() { - return (this.view != null); - } - - /** - * Return whether we use a view reference, i.e. {@code true} - * if the view has been specified via a name to be resolved by the - * DispatcherPortlet via a ViewResolver. - */ - public boolean isReference() { - return (this.view instanceof String); - } - - /** - * Return the model map. May return {@code null}. - * Called by DispatcherPortlet for evaluation of the model. - */ - protected Map getModelInternal() { - return this.model; - } - - /** - * Return the underlying {@code ModelMap} instance (never {@code null}). - */ - public ModelMap getModelMap() { - if (this.model == null) { - this.model = new ModelMap(); - } - return this.model; - } - - /** - * Return the model map. Never returns {@code null}. - * To be called by application code for modifying the model. - */ - public Map getModel() { - return getModelMap(); - } - - - /** - * Add an attribute to the model. - * @param attributeName name of the object to add to the model - * @param attributeValue object to add to the model (never {@code null}) - * @see ModelMap#addAttribute(String, Object) - * @see #getModelMap() - */ - public ModelAndView addObject(String attributeName, Object attributeValue) { - getModelMap().addAttribute(attributeName, attributeValue); - return this; - } - - /** - * Add an attribute to the model using parameter name generation. - * @param attributeValue the object to add to the model (never {@code null}) - * @see ModelMap#addAttribute(Object) - * @see #getModelMap() - */ - public ModelAndView addObject(Object attributeValue) { - getModelMap().addAttribute(attributeValue); - return this; - } - - /** - * Add all attributes contained in the provided Map to the model. - * @param modelMap a Map of attributeName -> attributeValue pairs - * @see ModelMap#addAllAttributes(Map) - * @see #getModelMap() - */ - public ModelAndView addAllObjects(Map modelMap) { - getModelMap().addAllAttributes(modelMap); - return this; - } - - - /** - * Clear the state of this ModelAndView object. - * The object will be empty afterwards. - *

        Can be used to suppress rendering of a given ModelAndView object - * in the {@code postHandleRender} method of a HandlerInterceptor. - * @see #isEmpty() - * @see HandlerInterceptor#postHandleRender - */ - public void clear() { - this.view = null; - this.model = null; - this.cleared = true; - } - - /** - * Return whether this ModelAndView object is empty, - * i.e. whether it does not hold any view and does not contain a model. - */ - public boolean isEmpty() { - return (this.view == null && CollectionUtils.isEmpty(this.model)); - } - - /** - * Return whether this ModelAndView object is empty as a result of a call to {@link #clear} - * i.e. whether it does not hold any view and does not contain a model. - * Returns {@code false} if any additional state was added to the instance - * after the call to {@link #clear}. - * @see #clear() - */ - public boolean wasCleared() { - return (this.cleared && isEmpty()); - } - - - /** - * Return diagnostic information about this model and view. - */ - @Override - public String toString() { - StringBuilder result = new StringBuilder("ModelAndView: "); - if (isReference()) { - result.append("reference to view with name '").append(this.view).append("'"); - } - else { - result.append("materialized View is [").append(this.view).append(']'); - } - result.append("; model is ").append(this.model); - return result.toString(); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndViewDefiningException.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndViewDefiningException.java deleted file mode 100644 index 5ff78ab1e5..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/ModelAndViewDefiningException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletException; - -/** - * Exception to be thrown on error conditions that should forward - * to a specific view with a specific model. - * - *

        Can be thrown at any time during handler processing. - * This includes any template methods of pre-built controllers. - * For example, a form controller might abort to a specific error page - * if certain parameters do not allow to proceed with the normal workflow. - * - * @author Juergen Hoeller - * @since 2.0 - */ -@SuppressWarnings("serial") -public class ModelAndViewDefiningException extends PortletException { - - private ModelAndView modelAndView; - - - /** - * Create new ModelAndViewDefiningException with the given ModelAndView, - * typically representing a specific error page. - * @param modelAndView ModelAndView with view to forward to and model to expose - */ - public ModelAndViewDefiningException(ModelAndView modelAndView) { - if (modelAndView == null) { - throw new IllegalArgumentException("modelAndView must not be null in ModelAndViewDefiningException"); - } - this.modelAndView = modelAndView; - } - - /** - * Return the ModelAndView that this exception contains for forwarding to. - */ - public ModelAndView getModelAndView() { - return modelAndView; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/NoHandlerFoundException.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/NoHandlerFoundException.java deleted file mode 100644 index 758794d754..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/NoHandlerFoundException.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; - -import org.springframework.core.style.StylerUtils; - -/** - * Exception to be thrown if DispatcherPortlet is unable to determine - * a corresponding handler for an incoming portlet request. - * - * @author Juergen Hoeller - * @since 3.0.5 - */ -@SuppressWarnings("serial") -public class NoHandlerFoundException extends PortletException { - - /** - * Constructor for NoHandlerFoundException. - * @param msg the detail message - */ - public NoHandlerFoundException(String msg) { - super(msg); - } - - /** - * Constructor for NoHandlerFoundException. - * @param msg the detail message - * @param request the current portlet request, - * for further context to be included in the exception message - */ - public NoHandlerFoundException(String msg, PortletRequest request) { - super(msg + ": mode '" + request.getPortletMode() + - "', phase '" + request.getAttribute(PortletRequest.LIFECYCLE_PHASE) + - "', parameters " + StylerUtils.style(request.getParameterMap())); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/MissingPortletRequestParameterException.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/MissingPortletRequestParameterException.java deleted file mode 100644 index 630f2e89b7..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/MissingPortletRequestParameterException.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2002-2012 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; - -/** - * {@link PortletRequestBindingException} subclass that indicates a missing parameter. - * - * @author Juergen Hoeller - * @since 2.0.2 - */ -@SuppressWarnings("serial") -public class MissingPortletRequestParameterException extends PortletRequestBindingException { - - private final String parameterName; - - private final String parameterType; - - - /** - * Constructor for MissingPortletRequestParameterException. - * @param parameterName the name of the missing parameter - * @param parameterType the expected type of the missing parameter - */ - public MissingPortletRequestParameterException(String parameterName, String parameterType) { - super(""); - this.parameterName = parameterName; - this.parameterType = parameterType; - } - - - @Override - public String getMessage() { - return "Required " + this.parameterType + " parameter '" + parameterName + "' is not present"; - } - - /** - * Return the name of the offending parameter. - */ - public final String getParameterName() { - return this.parameterName; - } - - /** - * Return the expected type of the offending parameter. - */ - public final String getParameterType() { - return this.parameterType; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestBindingException.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestBindingException.java deleted file mode 100644 index 69cc5ff3d3..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestBindingException.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletException; - -/** - * Fatal binding exception, thrown when we want to - * treat binding exceptions as unrecoverable. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - */ -@SuppressWarnings("serial") -public class PortletRequestBindingException extends PortletException { - - /** - * Constructor for PortletRequestBindingException. - * @param msg the detail message - */ - public PortletRequestBindingException(String msg) { - super(msg); - } - - /** - * Constructor for PortletRequestBindingException. - * @param msg the detail message - * @param cause the root cause - */ - public PortletRequestBindingException(String msg, Throwable cause) { - super(msg, cause); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java deleted file mode 100644 index 648da8db20..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestDataBinder.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletRequest; - -import org.springframework.beans.MutablePropertyValues; -import org.springframework.validation.BindException; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.multipart.MultipartRequest; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Special {@link org.springframework.validation.DataBinder} to perform data binding - * from portlet request parameters to JavaBeans, including support for multipart files. - * - *

        See the DataBinder/WebDataBinder superclasses for customization options, - * which include specifying allowed/required fields, and registering custom - * property editors. - * - *

        Can also be used for manual data binding in custom web controllers: - * for example, in a plain Portlet Controller implementation. Simply instantiate - * a PortletRequestDataBinder for each binding process, and invoke {@code bind} - * with the current PortletRequest as argument: - * - *

        - * MyBean myBean = new MyBean();
        - * // apply binder to custom target object
        - * PortletRequestDataBinder binder = new PortletRequestDataBinder(myBean);
        - * // register custom editors, if desired
        - * binder.registerCustomEditor(...);
        - * // trigger actual binding of request parameters
        - * binder.bind(request);
        - * // optionally evaluate binding errors
        - * Errors errors = binder.getErrors();
        - * ...
        - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see #bind(javax.portlet.PortletRequest) - * @see #registerCustomEditor - * @see #setAllowedFields - * @see #setRequiredFields - * @see #setFieldMarkerPrefix - */ -public class PortletRequestDataBinder extends WebDataBinder { - - /** - * Create a new PortletRequestDataBinder instance, with default object name. - * @param target the target object to bind onto (or {@code null} - * if the binder is just used to convert a plain parameter value) - * @see #DEFAULT_OBJECT_NAME - */ - public PortletRequestDataBinder(Object target) { - super(target); - } - - /** - * Create a new PortletRequestDataBinder instance. - * @param target the target object to bind onto (or {@code null} - * if the binder is just used to convert a plain parameter value) - * @param objectName the name of the target object - */ - public PortletRequestDataBinder(Object target, String objectName) { - super(target, objectName); - } - - - /** - * Bind the parameters of the given request to this binder's target, - * also binding multipart files in case of a multipart request. - *

        This call can create field errors, representing basic binding - * errors like a required field (code "required"), or type mismatch - * between value and bean property (code "typeMismatch"). - *

        Multipart files are bound via their parameter name, just like normal - * HTTP parameters: i.e. "uploadedFile" to an "uploadedFile" bean property, - * invoking a "setUploadedFile" setter method. - *

        The type of the target property for a multipart file can be MultipartFile, - * byte[], or String. The latter two receive the contents of the uploaded file; - * all metadata like original file name, content type, etc are lost in those cases. - * @param request request with parameters to bind (can be multipart) - * @see org.springframework.web.portlet.multipart.MultipartActionRequest - * @see org.springframework.web.multipart.MultipartFile - * @see #bind(org.springframework.beans.PropertyValues) - */ - public void bind(PortletRequest request) { - MutablePropertyValues mpvs = new PortletRequestParameterPropertyValues(request); - MultipartRequest multipartRequest = PortletUtils.getNativeRequest(request, MultipartRequest.class); - if (multipartRequest != null) { - bindMultipart(multipartRequest.getMultiFileMap(), mpvs); - } - doBind(mpvs); - } - - /** - * Treats errors as fatal. - *

        Use this method only if it's an error if the input isn't valid. - * This might be appropriate if all input is from dropdowns, for example. - * @throws PortletRequestBindingException subclass of PortletException on any binding problem - */ - public void closeNoCatch() throws PortletRequestBindingException { - if (getBindingResult().hasErrors()) { - throw new PortletRequestBindingException( - "Errors binding onto object '" + getBindingResult().getObjectName() + "'", - new BindException(getBindingResult())); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValues.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValues.java deleted file mode 100644 index 358fc9370e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValues.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletRequest; - -import org.springframework.beans.MutablePropertyValues; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * PropertyValues implementation created from parameters in a PortletRequest. - * Can look for all property values beginning with a certain prefix and - * prefix separator (default is "_"). - * - *

        For example, with a prefix of "spring", "spring_param1" and - * "spring_param2" result in a Map with "param1" and "param2" as keys. - * - *

        This class is not immutable to be able to efficiently remove property - * values that should be ignored for binding. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see org.springframework.web.portlet.util.PortletUtils#getParametersStartingWith - */ -@SuppressWarnings("serial") -public class PortletRequestParameterPropertyValues extends MutablePropertyValues { - - /** Default prefix separator */ - public static final String DEFAULT_PREFIX_SEPARATOR = "_"; - - - /** - * Create new PortletRequestPropertyValues using no prefix - * (and hence, no prefix separator). - * @param request portlet request - */ - public PortletRequestParameterPropertyValues(PortletRequest request) { - this(request, null, null); - } - - /** - * Create new PortletRequestPropertyValues using the given prefix and - * the default prefix separator (the underscore character "_"). - * @param request portlet request - * @param prefix the prefix for parameters (the full prefix will - * consist of this plus the separator) - * @see #DEFAULT_PREFIX_SEPARATOR - */ - public PortletRequestParameterPropertyValues(PortletRequest request, String prefix) { - this(request, prefix, DEFAULT_PREFIX_SEPARATOR); - } - - /** - * Create new PortletRequestPropertyValues supplying both prefix and - * prefix separator. - * @param request portlet request - * @param prefix the prefix for parameters (the full prefix will - * consist of this plus the separator) - * @param prefixSeparator separator delimiting prefix (e.g. "spring") - * and the rest of the parameter name ("param1", "param2") - */ - public PortletRequestParameterPropertyValues(PortletRequest request, String prefix, String prefixSeparator) { - super(PortletUtils.getParametersStartingWith( - request, (prefix != null ? prefix + prefixSeparator : null))); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestUtils.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestUtils.java deleted file mode 100644 index 43eef92bef..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/PortletRequestUtils.java +++ /dev/null @@ -1,711 +0,0 @@ -/* - * Copyright 2002-2012 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; - -import javax.portlet.PortletRequest; - -/** - * Parameter extraction methods, for an approach distinct from data binding, - * in which parameters of specific types are required. - * - *

        This approach is very useful for simple submissions, where binding - * request parameters to a command object would be overkill. - * - * @author Juergen Hoeller - * @author Keith Donald - * @author John A. Lewis - * @since 2.0 - */ -public abstract class PortletRequestUtils { - - private static final IntParser INT_PARSER = new IntParser(); - - private static final LongParser LONG_PARSER = new LongParser(); - - private static final FloatParser FLOAT_PARSER = new FloatParser(); - - private static final DoubleParser DOUBLE_PARSER = new DoubleParser(); - - private static final BooleanParser BOOLEAN_PARSER = new BooleanParser(); - - private static final StringParser STRING_PARSER = new StringParser(); - - - /** - * Get an Integer parameter, or {@code null} if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @return the Integer value, or {@code null} if not present - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static Integer getIntParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return getRequiredIntParameter(request, name); - } - - /** - * Get an int parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current portlet request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static int getIntParameter(PortletRequest request, String name, int defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredIntParameter(request, name); - } - catch (PortletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of int parameters, return an empty array if not found. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - */ - public static int[] getIntParameters(PortletRequest request, String name) { - try { - return getRequiredIntParameters(request, name); - } - catch (PortletRequestBindingException ex) { - return new int[0]; - } - } - - /** - * Get an int parameter, throwing an exception if it isn't found or isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static int getRequiredIntParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - return INT_PARSER.parseInt(name, request.getParameter(name)); - } - - /** - * Get an array of int parameters, throwing an exception if not found or one is not a number.. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static int[] getRequiredIntParameters(PortletRequest request, String name) - throws PortletRequestBindingException { - - return INT_PARSER.parseInts(name, request.getParameterValues(name)); - } - - - /** - * Get a Long parameter, or {@code null} if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @return the Long value, or {@code null} if not present - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static Long getLongParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return getRequiredLongParameter(request, name); - } - - /** - * Get a long parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current portlet request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static long getLongParameter(PortletRequest request, String name, long defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredLongParameter(request, name); - } - catch (PortletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of long parameters, return an empty array if not found. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - */ - public static long[] getLongParameters(PortletRequest request, String name) { - try { - return getRequiredLongParameters(request, name); - } - catch (PortletRequestBindingException ex) { - return new long[0]; - } - } - - /** - * Get a long parameter, throwing an exception if it isn't found or isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static long getRequiredLongParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - return LONG_PARSER.parseLong(name, request.getParameter(name)); - } - - /** - * Get an array of long parameters, throwing an exception if not found or one is not a number. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static long[] getRequiredLongParameters(PortletRequest request, String name) - throws PortletRequestBindingException { - - return LONG_PARSER.parseLongs(name, request.getParameterValues(name)); - } - - - /** - * Get a Float parameter, or {@code null} if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @return the Float value, or {@code null} if not present - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static Float getFloatParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return getRequiredFloatParameter(request, name); - } - - /** - * Get a float parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current portlet request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static float getFloatParameter(PortletRequest request, String name, float defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredFloatParameter(request, name); - } - catch (PortletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of float parameters, return an empty array if not found. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - */ - public static float[] getFloatParameters(PortletRequest request, String name) { - try { - return getRequiredFloatParameters(request, name); - } - catch (PortletRequestBindingException ex) { - return new float[0]; - } - } - - /** - * Get a float parameter, throwing an exception if it isn't found or isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static float getRequiredFloatParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - return FLOAT_PARSER.parseFloat(name, request.getParameter(name)); - } - - /** - * Get an array of float parameters, throwing an exception if not found or one is not a number. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static float[] getRequiredFloatParameters(PortletRequest request, String name) - throws PortletRequestBindingException { - - return FLOAT_PARSER.parseFloats(name, request.getParameterValues(name)); - } - - - /** - * Get a Double parameter, or {@code null} if not present. - * Throws an exception if it the parameter value isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @return the Double value, or {@code null} if not present - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static Double getDoubleParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return getRequiredDoubleParameter(request, name); - } - - /** - * Get a double parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - * @param request current portlet request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static double getDoubleParameter(PortletRequest request, String name, double defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredDoubleParameter(request, name); - } - catch (PortletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of double parameters, return an empty array if not found. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - */ - public static double[] getDoubleParameters(PortletRequest request, String name) { - try { - return getRequiredDoubleParameters(request, name); - } - catch (PortletRequestBindingException ex) { - return new double[0]; - } - } - - /** - * Get a double parameter, throwing an exception if it isn't found or isn't a number. - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static double getRequiredDoubleParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - return DOUBLE_PARSER.parseDouble(name, request.getParameter(name)); - } - - /** - * Get an array of double parameters, throwing an exception if not found or one is not a number. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static double[] getRequiredDoubleParameters(PortletRequest request, String name) - throws PortletRequestBindingException { - - return DOUBLE_PARSER.parseDoubles(name, request.getParameterValues(name)); - } - - - /** - * Get a Boolean parameter, or {@code null} if not present. - * Throws an exception if it the parameter value isn't a boolean. - *

        Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current portlet request - * @param name the name of the parameter - * @return the Boolean value, or {@code null} if not present - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static Boolean getBooleanParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return (getRequiredBooleanParameter(request, name)); - } - - /** - * Get a boolean parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value as default to enable checks of whether it was supplied. - *

        Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current portlet request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static boolean getBooleanParameter(PortletRequest request, String name, boolean defaultVal) { - if (request.getParameter(name) == null) { - return defaultVal; - } - try { - return getRequiredBooleanParameter(request, name); - } - catch (PortletRequestBindingException ex) { - return defaultVal; - } - } - - /** - * Get an array of boolean parameters, return an empty array if not found. - *

        Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - */ - public static boolean[] getBooleanParameters(PortletRequest request, String name) { - try { - return getRequiredBooleanParameters(request, name); - } - catch (PortletRequestBindingException ex) { - return new boolean[0]; - } - } - - /** - * Get a boolean parameter, throwing an exception if it isn't found - * or isn't a boolean. - *

        Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static boolean getRequiredBooleanParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - return BOOLEAN_PARSER.parseBoolean(name, request.getParameter(name)); - } - - /** - * Get an array of boolean parameters, throwing an exception if not found - * or one isn't a boolean. - *

        Accepts "true", "on", "yes" (any case) and "1" as values for true; - * treats every other non-empty value as false (i.e. parses leniently). - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static boolean[] getRequiredBooleanParameters(PortletRequest request, String name) - throws PortletRequestBindingException { - - return BOOLEAN_PARSER.parseBooleans(name, request.getParameterValues(name)); - } - - - /** - * Get a String parameter, or {@code null} if not present. - * Throws an exception if it the parameter value is empty. - * @param request current portlet request - * @param name the name of the parameter - * @return the String value, or {@code null} if not present - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static String getStringParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - if (request.getParameter(name) == null) { - return null; - } - return getRequiredStringParameter(request, name); - } - - /** - * Get a String parameter, with a fallback value. Never throws an exception. - * Can pass a distinguished value to default to enable checks of whether it was supplied. - * @param request current portlet request - * @param name the name of the parameter - * @param defaultVal the default value to use as fallback - */ - public static String getStringParameter(PortletRequest request, String name, String defaultVal) { - String val = request.getParameter(name); - return (val != null ? val : defaultVal); - } - - /** - * Get an array of String parameters, return an empty array if not found. - * @param request current portlet request - * @param name the name of the parameter with multiple possible values - */ - public static String[] getStringParameters(PortletRequest request, String name) { - try { - return getRequiredStringParameters(request, name); - } - catch (PortletRequestBindingException ex) { - return new String[0]; - } - } - - /** - * Get a String parameter, throwing an exception if it isn't found or is empty. - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static String getRequiredStringParameter(PortletRequest request, String name) - throws PortletRequestBindingException { - - return STRING_PARSER.validateRequiredString(name, request.getParameter(name)); - } - - /** - * Get an array of String parameters, throwing an exception if not found or one is empty. - * @param request current portlet request - * @param name the name of the parameter - * @throws PortletRequestBindingException a subclass of PortletException, - * so it doesn't need to be caught - */ - public static String[] getRequiredStringParameters(PortletRequest request, String name) - throws PortletRequestBindingException { - - return STRING_PARSER.validateRequiredStrings(name, request.getParameterValues(name)); - } - - - private abstract static class ParameterParser { - - protected final T parse(String name, String parameter) throws PortletRequestBindingException { - validateRequiredParameter(name, parameter); - try { - return doParse(parameter); - } - catch (NumberFormatException ex) { - throw new PortletRequestBindingException( - "Required " + getType() + " parameter '" + name + "' with value of '" + - parameter + "' is not a valid number", ex); - } - } - - protected final void validateRequiredParameter(String name, Object parameter) - throws PortletRequestBindingException { - - if (parameter == null) { - throw new MissingPortletRequestParameterException(name, getType()); - } - } - - protected abstract String getType(); - - protected abstract T doParse(String parameter) throws NumberFormatException; - } - - - private static class IntParser extends ParameterParser { - - @Override - protected String getType() { - return "int"; - } - - @Override - protected Integer doParse(String s) throws NumberFormatException { - return Integer.valueOf(s); - } - - public int parseInt(String name, String parameter) throws PortletRequestBindingException { - return parse(name, parameter); - } - - public int[] parseInts(String name, String[] values) throws PortletRequestBindingException { - validateRequiredParameter(name, values); - int[] parameters = new int[values.length]; - for (int i = 0; i < values.length; i++) { - parameters[i] = parseInt(name, values[i]); - } - return parameters; - } - } - - - private static class LongParser extends ParameterParser { - - @Override - protected String getType() { - return "long"; - } - - @Override - protected Long doParse(String parameter) throws NumberFormatException { - return Long.valueOf(parameter); - } - - public long parseLong(String name, String parameter) throws PortletRequestBindingException { - return parse(name, parameter); - } - - public long[] parseLongs(String name, String[] values) throws PortletRequestBindingException { - validateRequiredParameter(name, values); - long[] parameters = new long[values.length]; - for (int i = 0; i < values.length; i++) { - parameters[i] = parseLong(name, values[i]); - } - return parameters; - } - } - - - private static class FloatParser extends ParameterParser { - - @Override - protected String getType() { - return "float"; - } - - @Override - protected Float doParse(String parameter) throws NumberFormatException { - return Float.valueOf(parameter); - } - - public float parseFloat(String name, String parameter) throws PortletRequestBindingException { - return parse(name, parameter); - } - - public float[] parseFloats(String name, String[] values) throws PortletRequestBindingException { - validateRequiredParameter(name, values); - float[] parameters = new float[values.length]; - for (int i = 0; i < values.length; i++) { - parameters[i] = parseFloat(name, values[i]); - } - return parameters; - } - } - - - private static class DoubleParser extends ParameterParser { - - @Override - protected String getType() { - return "double"; - } - - @Override - protected Double doParse(String parameter) throws NumberFormatException { - return Double.valueOf(parameter); - } - - public double parseDouble(String name, String parameter) throws PortletRequestBindingException { - return parse(name, parameter); - } - - public double[] parseDoubles(String name, String[] values) throws PortletRequestBindingException { - validateRequiredParameter(name, values); - double[] parameters = new double[values.length]; - for (int i = 0; i < values.length; i++) { - parameters[i] = parseDouble(name, values[i]); - } - return parameters; - } - } - - - private static class BooleanParser extends ParameterParser { - - @Override - protected String getType() { - return "boolean"; - } - - @Override - protected Boolean doParse(String parameter) throws NumberFormatException { - return (parameter.equalsIgnoreCase("true") || parameter.equalsIgnoreCase("on") || - parameter.equalsIgnoreCase("yes") || parameter.equals("1")); - } - - public boolean parseBoolean(String name, String parameter) throws PortletRequestBindingException { - return parse(name, parameter); - } - - public boolean[] parseBooleans(String name, String[] values) throws PortletRequestBindingException { - validateRequiredParameter(name, values); - boolean[] parameters = new boolean[values.length]; - for (int i = 0; i < values.length; i++) { - parameters[i] = parseBoolean(name, values[i]); - } - return parameters; - } - } - - - private static class StringParser extends ParameterParser { - - @Override - protected String getType() { - return "string"; - } - - @Override - protected String doParse(String parameter) throws NumberFormatException { - return parameter; - } - - public String validateRequiredString(String name, String value) throws PortletRequestBindingException { - validateRequiredParameter(name, value); - return value; - } - - public String[] validateRequiredStrings(String name, String[] values) throws PortletRequestBindingException { - validateRequiredParameter(name, values); - for (String value : values) { - validateRequiredParameter(name, value); - } - return values; - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ActionMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ActionMapping.java deleted file mode 100644 index 9341d3390f..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ActionMapping.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2002-2015 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.core.annotation.AliasFor; -import org.springframework.web.bind.annotation.Mapping; - -/** - * Annotation for mapping Portlet action requests onto handler methods. - * - * @author Juergen Hoeller - * @author Sam Brannen - * @since 3.0 - * @see org.springframework.web.bind.annotation.RequestMapping - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Mapping -public @interface ActionMapping { - - /** - * Alias for {@link #name}. - */ - @AliasFor("name") - String value() default ""; - - /** - * The name of the action, according to the Portlet 2.0 - * {@code javax.portlet.action} parameter. - *

        If not specified, the annotated method will be used as a default - * handler: i.e. for action requests where no specific action mapping - * was found. - *

        Note that all such annotated action methods only apply within the - * {@code @RequestMapping} constraints of the containing handler class. - * @since 4.2 - * @see javax.portlet.ActionRequest#ACTION_NAME - * @see #value - */ - @AliasFor("value") - String name() default ""; - - /** - * The parameters of the mapped request, narrowing the primary mapping. - *

        Same format for any environment: a sequence of {@code "myParam=myValue"} - * style expressions, with a request only mapped if each such parameter is found - * to have the given value. {@code "myParam"} style expressions are also supported, - * with such parameters having to be present in the request (allowed to have - * any value). Finally, {@code "!myParam"} style expressions indicate that the - * specified parameter is not supposed to be present in the request. - * @see org.springframework.web.bind.annotation.RequestMapping#params() - */ - String[] params() default {}; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/EventMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/EventMapping.java deleted file mode 100644 index 1d9e45ce98..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/EventMapping.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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. - * This name uniquely identifies an event within a portlet mode. - *

        Typically the local name of the event, but fully qualified names - * with a "{...}" namespace part will be mapped correctly as well. - *

        If not specified, the handler method will be invoked for any - * event request within its general mapping. - * @see javax.portlet.EventRequest#getEvent() - * @see javax.portlet.Event#getName() - */ - String value() default ""; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/RenderMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/RenderMapping.java deleted file mode 100644 index 668d31e17e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/RenderMapping.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2002-2015 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.core.annotation.AliasFor; -import org.springframework.web.bind.annotation.Mapping; - -/** - * Annotation for mapping Portlet render requests onto handler methods. - * - * @author Juergen Hoeller - * @author Sam Brannen - * @since 3.0 - * @see org.springframework.web.bind.annotation.RequestMapping - */ -@Target({ElementType.METHOD}) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Mapping -public @interface RenderMapping { - - /** - * Alias for {@link #windowState}. - */ - @AliasFor("windowState") - String value() default ""; - - /** - * The window state that the annotated render method applies for. - *

        If not specified, the render method will be invoked for any - * window state within its general mapping. - *

        Standard Portlet specification values are supported: {@code "NORMAL"}, - * {@code "MAXIMIZED"}, {@code "MINIMIZED"}. - *

        Custom window states can be used as well, as supported by the portal. - * @since 4.2 - * @see #value - * @see javax.portlet.PortletRequest#getWindowState() - */ - @AliasFor("value") - String windowState() default ""; - - /** - * The parameters of the mapped request, narrowing the primary mapping. - *

        Same format for any environment: a sequence of {@code "myParam=myValue"} - * style expressions, with a request only mapped if each such parameter is found - * to have the given value. {@code "myParam"} style expressions are also supported, - * with such parameters having to be present in the request (allowed to have - * any value). Finally, {@code "!myParam"} style expressions indicate that the - * specified parameter is not supposed to be present in the request. - * @see org.springframework.web.bind.annotation.RequestMapping#params() - */ - String[] params() default {}; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ResourceMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ResourceMapping.java deleted file mode 100644 index 1da4819200..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/ResourceMapping.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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. - * This id uniquely identifies a resource within a portlet mode. - *

        If not specified, the handler method will be invoked for any - * resource request within its general mapping. - * @see javax.portlet.ResourceRequest#getResourceID() - */ - String value() default ""; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/package-info.java deleted file mode 100644 index 204d5b8674..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/annotation/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Annotations for binding portlet requests to handler methods. - */ -package org.springframework.web.portlet.bind.annotation; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/package-info.java deleted file mode 100644 index 5527434085..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/bind/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Provides Portlet-specific data binding functionality. - */ -package org.springframework.web.portlet.bind; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java deleted file mode 100644 index 1df9110d19..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/AbstractRefreshablePortletApplicationContext.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.servlet.ServletContext; - -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.AbstractRefreshableConfigApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.web.context.ServletContextAware; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.ServletContextAwareProcessor; - -/** - * {@link org.springframework.context.support.AbstractRefreshableApplicationContext} - * subclass which implements the {@link ConfigurablePortletApplicationContext} - * interface for portlet environments. Provides a "configLocations" property, - * to be populated through the ConfigurablePortletApplicationContext interface - * on portlet application startup. - * - *

        This class is as easy to subclass as AbstractRefreshableApplicationContext: - * All you need to implements is the {@link #loadBeanDefinitions} method; - * see the superclass javadoc for details. Note that implementations are supposed - * to load bean definitions from the files specified by the locations returned - * by the {@link #getConfigLocations} method. - * - *

        Interprets resource paths as servlet context resources, i.e. as paths beneath - * the web application root. Absolute paths, e.g. for files outside the web app root, - * can be accessed via "file:" URLs, as implemented by - * {@link org.springframework.core.io.DefaultResourceLoader}. - * - *

        This is the portlet context to be subclassed for a different bean definition format. - * Such a context implementation can be specified as "contextClass" init-param - * for FrameworkPortlet, replacing the default {@link XmlPortletApplicationContext}. - * It will then automatically receive the "contextConfigLocation" init-param. - * - *

        Note that Portlet-based context implementations are generally supposed - * to configure themselves based on the configuration received through the - * {@link ConfigurablePortletApplicationContext} interface. In contrast, a standalone - * application context might allow for configuration in custom startup code - * (for example, {@link org.springframework.context.support.GenericApplicationContext}). - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see #loadBeanDefinitions - * @see org.springframework.web.portlet.context.ConfigurablePortletApplicationContext#setConfigLocations - * @see XmlPortletApplicationContext - */ -public abstract class AbstractRefreshablePortletApplicationContext extends AbstractRefreshableConfigApplicationContext - implements WebApplicationContext, ConfigurablePortletApplicationContext { - - /** Servlet context that this context runs in */ - private ServletContext servletContext; - - /** Portlet context that this context runs in */ - private PortletContext portletContext; - - /** Portlet config that this context runs in */ - private PortletConfig portletConfig; - - /** Namespace of this context, or null if root */ - private String namespace; - - - public AbstractRefreshablePortletApplicationContext() { - setDisplayName("Root PortletApplicationContext"); - } - - /** - * {@inheritDoc} - *

        The parent {@linkplain #getEnvironment() environment} is - * delegated to this (child) context if the parent is a - * {@link org.springframework.context.ConfigurableApplicationContext} implementation. - *

        The parent {@linkplain #getServletContext() servlet context} is - * delegated to this (child) context if the parent is a {@link WebApplicationContext} - * implementation. - */ - @Override - public void setParent(ApplicationContext parent) { - super.setParent(parent); - if (parent instanceof WebApplicationContext) { - this.servletContext = ((WebApplicationContext) parent).getServletContext(); - } - } - - @Override - public ServletContext getServletContext() { - return this.servletContext; - } - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - @Override - public void setPortletConfig(PortletConfig portletConfig) { - this.portletConfig = portletConfig; - if (portletConfig != null && this.portletContext == null) { - this.portletContext = portletConfig.getPortletContext(); - } - } - - @Override - public PortletConfig getPortletConfig() { - return this.portletConfig; - } - - @Override - public void setNamespace(String namespace) { - this.namespace = namespace; - if (namespace != null) { - setDisplayName("PortletApplicationContext for namespace '" + namespace + "'"); - } - } - - @Override - public String getNamespace() { - return this.namespace; - } - - @Override - public String[] getConfigLocations() { - return super.getConfigLocations(); - } - - @Override - public String getApplicationName() { - if (this.portletContext == null) { - return ""; - } - String name = this.portletContext.getPortletContextName(); - return (name != null ? name : ""); - } - - /** - * Create and return a new {@link StandardPortletEnvironment}. - */ - @Override - protected ConfigurableEnvironment createEnvironment() { - return new StandardPortletEnvironment(); - } - - /** - * Register request/session scopes, a {@link PortletContextAwareProcessor}, etc. - */ - @Override - protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext)); - beanFactory.addBeanPostProcessor(new PortletContextAwareProcessor(this.portletContext, this.portletConfig)); - beanFactory.ignoreDependencyInterface(ServletContextAware.class); - beanFactory.ignoreDependencyInterface(PortletContextAware.class); - beanFactory.ignoreDependencyInterface(PortletConfigAware.class); - - PortletApplicationContextUtils.registerPortletApplicationScopes(beanFactory, this.portletContext); - PortletApplicationContextUtils.registerEnvironmentBeans( - beanFactory, this.servletContext, this.portletContext, this.portletConfig); - } - - /** - * This implementation supports file paths beneath the root of the PortletContext. - * @see PortletContextResource - */ - @Override - protected Resource getResourceByPath(String path) { - return new PortletContextResource(this.portletContext, path); - } - - /** - * This implementation supports pattern matching in unexpanded WARs too. - * @see PortletContextResourcePatternResolver - */ - @Override - protected ResourcePatternResolver getResourcePatternResolver() { - return new PortletContextResourcePatternResolver(this); - } - - @Override - protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { - super.customizeBeanFactory(beanFactory); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/ConfigurablePortletApplicationContext.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/ConfigurablePortletApplicationContext.java deleted file mode 100644 index 9d330ad004..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/ConfigurablePortletApplicationContext.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; - -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.web.context.WebApplicationContext; - -/** - * Interface to be implemented by configurable portlet application contexts. - * Supported by {@link org.springframework.web.portlet.FrameworkPortlet}. - * - *

        Note: The setters of this interface need to be called before an - * invocation of the {@link #refresh} method inherited from - * {@link org.springframework.context.ConfigurableApplicationContext}. - * They do not cause an initialization of the context on their own. - * - * @author Juergen Hoeller - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @since 2.0 - * @see #refresh - * @see org.springframework.web.context.ContextLoader#createWebApplicationContext - * @see org.springframework.web.portlet.FrameworkPortlet#createPortletApplicationContext - * @see org.springframework.web.context.ConfigurableWebApplicationContext - */ -public interface ConfigurablePortletApplicationContext - extends WebApplicationContext, ConfigurableApplicationContext { - - /** - * Prefix for ApplicationContext ids that refer to portlet name. - */ - String APPLICATION_CONTEXT_ID_PREFIX = WebApplicationContext.class.getName() + ":"; - - /** - * Name of the PortletContext environment bean in the factory. - * @see javax.portlet.PortletContext - */ - String PORTLET_CONTEXT_BEAN_NAME = "portletContext"; - - /** - * Name of the PortletConfig environment bean in the factory. - * @see javax.portlet.PortletConfig - */ - String PORTLET_CONFIG_BEAN_NAME = "portletConfig"; - - - /** - * Set the PortletContext for this portlet application context. - *

        Does not cause an initialization of the context: refresh needs to be - * called after the setting of all configuration properties. - * @see #refresh() - */ - void setPortletContext(PortletContext portletContext); - - /** - * Return the standard Portlet API PortletContext for this application. - */ - PortletContext getPortletContext(); - - /** - * Set the PortletConfig for this portlet application context. - * @see #refresh() - */ - void setPortletConfig(PortletConfig portletConfig); - - /** - * Return the PortletConfig for this portlet application context, if any. - */ - PortletConfig getPortletConfig(); - - /** - * Set the namespace for this portlet application context, - * to be used for building a default context config location. - */ - void setNamespace(String namespace); - - /** - * Return the namespace for this web application context, if any. - */ - String getNamespace(); - - /** - * Set the config locations for this portlet application context in init-param style, - * i.e. with distinct locations separated by commas, semicolons or whitespace. - *

        If not set, the implementation is supposed to use a default for the - * given namespace. - */ - void setConfigLocation(String configLocation); - - /** - * Set the config locations for this portlet application context. - *

        If not set, the implementation is supposed to use a default for the - * given namespace. - */ - void setConfigLocations(String... configLocations); - - /** - * Return the config locations for this web application context, - * or {@code null} if none specified. - */ - String[] getConfigLocations(); - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java deleted file mode 100644 index ce29022a04..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationContextUtils.java +++ /dev/null @@ -1,316 +0,0 @@ -/* - * Copyright 2002-2016 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.context; - -import java.io.Serializable; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; -import javax.servlet.ServletContext; - -import org.springframework.beans.factory.ObjectFactory; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.util.Assert; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.RequestScope; -import org.springframework.web.context.request.SessionScope; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.support.WebApplicationContextUtils; - -/** - * Convenience methods for retrieving the root {@link WebApplicationContext} for - * a given {@link PortletContext}. This is useful for programmatically accessing - * a Spring application context from within custom Portlet implementations. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see org.springframework.web.context.ContextLoader - * @see org.springframework.web.context.support.WebApplicationContextUtils - * @see org.springframework.web.portlet.FrameworkPortlet - * @see org.springframework.web.portlet.DispatcherPortlet - */ -public abstract class PortletApplicationContextUtils { - - /** - * Find the root {@link WebApplicationContext} for this web app, typically - * loaded via {@link org.springframework.web.context.ContextLoaderListener}. - *

        Will rethrow an exception that happened on root context startup, - * to differentiate between a failed context startup and no context at all. - * @param pc PortletContext to find the web application context for - * @return the root WebApplicationContext for this web app, or {@code null} if none - * (typed to ApplicationContext to avoid a Servlet API dependency; can usually - * be casted to WebApplicationContext, but there shouldn't be a need to) - * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE - */ - public static ApplicationContext getWebApplicationContext(PortletContext pc) { - Assert.notNull(pc, "PortletContext must not be null"); - Object attr = pc.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); - if (attr == null) { - return null; - } - if (attr instanceof RuntimeException) { - throw (RuntimeException) attr; - } - if (attr instanceof Error) { - throw (Error) attr; - } - if (!(attr instanceof ApplicationContext)) { - throw new IllegalStateException("Root context attribute is not of type WebApplicationContext: " + attr); - } - return (ApplicationContext) attr; - } - - /** - * Find the root {@link WebApplicationContext} for this web app, typically - * loaded via {@link org.springframework.web.context.ContextLoaderListener}. - *

        Will rethrow an exception that happened on root context startup, - * to differentiate between a failed context startup and no context at all. - * @param pc PortletContext to find the web application context for - * @return the root WebApplicationContext for this web app - * (typed to ApplicationContext to avoid a Servlet API dependency; can usually - * be casted to WebApplicationContext, but there shouldn't be a need to) - * @throws IllegalStateException if the root WebApplicationContext could not be found - * @see org.springframework.web.context.WebApplicationContext#ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE - */ - public static ApplicationContext getRequiredWebApplicationContext(PortletContext pc) throws IllegalStateException { - ApplicationContext wac = getWebApplicationContext(pc); - if (wac == null) { - throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?"); - } - return wac; - } - - - /** - * Register web-specific scopes ("request", "session", "globalSession") - * with the given BeanFactory, as used by the Portlet ApplicationContext. - * @param bf the BeanFactory to configure - * @param pc the PortletContext that we're running within - */ - static void registerPortletApplicationScopes(ConfigurableListableBeanFactory bf, PortletContext pc) { - bf.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); - bf.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope(false)); - bf.registerScope(WebApplicationContext.SCOPE_GLOBAL_SESSION, new SessionScope(true)); - if (pc != null) { - PortletContextScope appScope = new PortletContextScope(pc); - bf.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope); - // Register as PortletContext attribute, for ContextCleanupListener to detect it. - pc.setAttribute(PortletContextScope.class.getName(), appScope); - } - - bf.registerResolvableDependency(PortletRequest.class, new RequestObjectFactory()); - bf.registerResolvableDependency(PortletResponse.class, new ResponseObjectFactory()); - bf.registerResolvableDependency(PortletSession.class, new SessionObjectFactory()); - bf.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); - } - - /** - * Register web-specific environment beans ("contextParameters", "contextAttributes") - * with the given BeanFactory, as used by the Portlet ApplicationContext. - * @param bf the BeanFactory to configure - * @param servletContext the ServletContext that we're running within - * @param portletContext the PortletContext that we're running within - * @param portletConfig the PortletConfig of the containing Portlet - */ - static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf, ServletContext servletContext, - PortletContext portletContext, PortletConfig portletConfig) { - - if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) { - bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext); - } - - if (portletContext != null && !bf.containsBean(ConfigurablePortletApplicationContext.PORTLET_CONTEXT_BEAN_NAME)) { - bf.registerSingleton(ConfigurablePortletApplicationContext.PORTLET_CONTEXT_BEAN_NAME, portletContext); - } - - if (portletConfig != null && !bf.containsBean(ConfigurablePortletApplicationContext.PORTLET_CONFIG_BEAN_NAME)) { - bf.registerSingleton(ConfigurablePortletApplicationContext.PORTLET_CONFIG_BEAN_NAME, portletConfig); - } - - if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) { - Map parameterMap = new HashMap(); - if (portletContext != null) { - Enumeration paramNameEnum = portletContext.getInitParameterNames(); - while (paramNameEnum.hasMoreElements()) { - String paramName = paramNameEnum.nextElement(); - parameterMap.put(paramName, portletContext.getInitParameter(paramName)); - } - } - if (portletConfig != null) { - Enumeration paramNameEnum = portletConfig.getInitParameterNames(); - while (paramNameEnum.hasMoreElements()) { - String paramName = paramNameEnum.nextElement(); - parameterMap.put(paramName, portletConfig.getInitParameter(paramName)); - } - } - bf.registerSingleton(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME, - Collections.unmodifiableMap(parameterMap)); - } - - if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) { - Map attributeMap = new HashMap(); - if (portletContext != null) { - Enumeration attrNameEnum = portletContext.getAttributeNames(); - while (attrNameEnum.hasMoreElements()) { - String attrName = attrNameEnum.nextElement(); - attributeMap.put(attrName, portletContext.getAttribute(attrName)); - } - } - bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME, - Collections.unmodifiableMap(attributeMap)); - } - } - - /** - * Replace {@code Servlet}- and {@code Portlet}-based {@link - * org.springframework.core.env.PropertySource.StubPropertySource stub property - * sources} with actual instances populated with the given {@code servletContext}, - * {@code portletContext} and {@code portletConfig} objects. - *

        This method is idempotent with respect to the fact it may be called any number - * of times but will perform replacement of stub property sources with their - * corresponding actual property sources once and only once. - * @param propertySources the {@link MutablePropertySources} to initialize (must not be {@code null}) - * @param servletContext the current {@link ServletContext} (ignored if {@code null} - * or if the {@link org.springframework.web.context.support.StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME - * servlet context property source} has already been initialized) - * @param portletContext the current {@link PortletContext} (ignored if {@code null} - * or if the {@link StandardPortletEnvironment#PORTLET_CONTEXT_PROPERTY_SOURCE_NAME - * portlet context property source} has already been initialized) - * @param portletConfig the current {@link PortletConfig} (ignored if {@code null} - * or if the {@link StandardPortletEnvironment#PORTLET_CONFIG_PROPERTY_SOURCE_NAME - * portlet config property source} has already been initialized) - * @see org.springframework.core.env.PropertySource.StubPropertySource - * @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources(MutablePropertySources, ServletContext) - * @see org.springframework.core.env.ConfigurableEnvironment#getPropertySources() - */ - public static void initPortletPropertySources(MutablePropertySources propertySources, ServletContext servletContext, - PortletContext portletContext, PortletConfig portletConfig) { - - Assert.notNull(propertySources, "'propertySources' must not be null"); - WebApplicationContextUtils.initServletPropertySources(propertySources, servletContext); - - if (portletContext != null && propertySources.contains(StandardPortletEnvironment.PORTLET_CONTEXT_PROPERTY_SOURCE_NAME)) { - propertySources.replace(StandardPortletEnvironment.PORTLET_CONTEXT_PROPERTY_SOURCE_NAME, - new PortletContextPropertySource(StandardPortletEnvironment.PORTLET_CONTEXT_PROPERTY_SOURCE_NAME, portletContext)); - } - if (portletConfig != null && propertySources.contains(StandardPortletEnvironment.PORTLET_CONFIG_PROPERTY_SOURCE_NAME)) { - propertySources.replace(StandardPortletEnvironment.PORTLET_CONFIG_PROPERTY_SOURCE_NAME, - new PortletConfigPropertySource(StandardPortletEnvironment.PORTLET_CONFIG_PROPERTY_SOURCE_NAME, portletConfig)); - } - } - - /** - * Return the current RequestAttributes instance as PortletRequestAttributes. - * @see RequestContextHolder#currentRequestAttributes() - */ - private static PortletRequestAttributes currentRequestAttributes() { - RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes(); - if (!(requestAttr instanceof PortletRequestAttributes)) { - throw new IllegalStateException("Current request is not a portlet request"); - } - return (PortletRequestAttributes) requestAttr; - } - - - /** - * Factory that exposes the current request object on demand. - */ - @SuppressWarnings("serial") - private static class RequestObjectFactory implements ObjectFactory, Serializable { - - @Override - public PortletRequest getObject() { - return currentRequestAttributes().getRequest(); - } - - @Override - public String toString() { - return "Current PortletRequest"; - } - } - - - /** - * Factory that exposes the current response object on demand. - */ - @SuppressWarnings("serial") - private static class ResponseObjectFactory implements ObjectFactory, Serializable { - - @Override - public PortletResponse getObject() { - PortletResponse response = currentRequestAttributes().getResponse(); - if (response == null) { - throw new IllegalStateException("Current portlet response not available"); - } - return response; - } - - @Override - public String toString() { - return "Current PortletResponse"; - } - } - - - /** - * Factory that exposes the current session object on demand. - */ - @SuppressWarnings("serial") - private static class SessionObjectFactory implements ObjectFactory, Serializable { - - @Override - public PortletSession getObject() { - return currentRequestAttributes().getRequest().getPortletSession(); - } - - @Override - public String toString() { - return "Current PortletSession"; - } - } - - - /** - * Factory that exposes the current WebRequest object on demand. - */ - @SuppressWarnings("serial") - private static class WebRequestObjectFactory implements ObjectFactory, Serializable { - - @Override - public WebRequest getObject() { - PortletRequestAttributes requestAttr = currentRequestAttributes(); - return new PortletWebRequest(requestAttr.getRequest(), requestAttr.getResponse()); - } - - @Override - public String toString() { - return "Current PortletWebRequest"; - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationObjectSupport.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationObjectSupport.java deleted file mode 100644 index 94f5835aca..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletApplicationObjectSupport.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import java.io.File; -import javax.portlet.PortletContext; - -import org.springframework.context.support.ApplicationObjectSupport; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Convenient superclass for application objects running in a Portlet ApplicationContext. - * Provides getApplicationContext, getServletContext, and getTempDir methods. - * - * @author Juergen Hoeller - * @since 2.0 - */ -public abstract class PortletApplicationObjectSupport extends ApplicationObjectSupport - implements PortletContextAware { - - private PortletContext portletContext; - - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - - /** - * Overrides the base class behavior to enforce running in an ApplicationContext. - * All accessors will throw IllegalStateException if not running in a context. - * @see #getApplicationContext() - * @see #getMessageSourceAccessor() - * @see #getPortletContext() - * @see #getTempDir() - */ - @Override - protected boolean isContextRequired() { - return true; - } - - /** - * Return the current PortletContext. - * @throws IllegalStateException if not running within a PortletContext - */ - protected final PortletContext getPortletContext() throws IllegalStateException { - if (this.portletContext == null) { - throw new IllegalStateException( - "PortletApplicationObjectSupport instance [" + this + "] does not run within a PortletContext"); - } - return this.portletContext; - } - - /** - * Return the temporary directory for the current web application, - * as provided by the servlet container. - * @return the File representing the temporary directory - * @throws IllegalStateException if not running within a PortletContext - * @see org.springframework.web.portlet.util.PortletUtils#getTempDir(javax.portlet.PortletContext) - */ - protected final File getTempDir() throws IllegalStateException { - return PortletUtils.getTempDir(getPortletContext()); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigAware.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigAware.java deleted file mode 100644 index d3fcbb4ce3..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigAware.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import javax.portlet.PortletConfig; - -import org.springframework.beans.factory.Aware; - -/** - * Interface to be implemented by any object that wishes to be notified - * of the PortletConfig (typically determined by the PortletApplicationContext) - * that it runs in. - * - * @author Juergen Hoeller - * @author Chris Beams - * @since 2.0 - * @see PortletContextAware - */ -public interface PortletConfigAware extends Aware { - - /** - * Set the PortletConfigthat this object runs in. - *

        Invoked after population of normal bean properties but before an init - * callback like InitializingBean's afterPropertiesSet or a custom init-method. - * Invoked after ApplicationContextAware's setApplicationContext. - * @param portletConfig PortletConfig object to be used by this object - */ - void setPortletConfig(PortletConfig portletConfig); - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigPropertySource.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigPropertySource.java deleted file mode 100644 index 09d2457866..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletConfigPropertySource.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import javax.portlet.PortletConfig; - -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.util.StringUtils; - -/** - * {@link PropertySource} that reads init parameters from a {@link PortletConfig} object. - * - * @author Chris Beams - * @since 3.1 - * @see PortletContextPropertySource - */ -public class PortletConfigPropertySource extends EnumerablePropertySource { - - public PortletConfigPropertySource(String name, PortletConfig portletConfig) { - super(name, portletConfig); - } - - @Override - public String[] getPropertyNames() { - return StringUtils.toStringArray(this.source.getInitParameterNames()); - } - - @Override - public String getProperty(String name) { - return this.source.getInitParameter(name); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAware.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAware.java deleted file mode 100644 index b11a4707e4..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAware.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import javax.portlet.PortletContext; - -import org.springframework.beans.factory.Aware; - -/** - * Interface to be implemented by any object that wishes to be notified - * of the PortletContext (typically determined by the PortletApplicationContext) - * that it runs in. - * - * @author Juergen Hoeller - * @author William G. Thompson, Jr. - * @author Chris Beams - * @since 2.0 - * @see PortletConfigAware - */ -public interface PortletContextAware extends Aware { - - /** - * Set the PortletContext that this object runs in. - *

        Invoked after population of normal bean properties but before an init - * callback like InitializingBean's afterPropertiesSet or a custom init-method. - * Invoked after ApplicationContextAware's setApplicationContext. - * @param portletContext PortletContext object to be used by this object - */ - void setPortletContext(PortletContext portletContext); - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAwareProcessor.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAwareProcessor.java deleted file mode 100644 index c941c6a187..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextAwareProcessor.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; - -/** - * {@link org.springframework.beans.factory.config.BeanPostProcessor} - * implementation that passes the PortletContext to beans that implement - * the {@link PortletContextAware} interface. - * - *

        Portlet application contexts will automatically register this with their - * underlying bean factory. Applications do not use this directly. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see org.springframework.web.portlet.context.PortletContextAware - * @see org.springframework.web.portlet.context.XmlPortletApplicationContext#postProcessBeanFactory - */ -public class PortletContextAwareProcessor implements BeanPostProcessor { - - private PortletContext portletContext; - - private PortletConfig portletConfig; - - - /** - * Create a new PortletContextAwareProcessor for the given context. - */ - public PortletContextAwareProcessor(PortletContext portletContext) { - this(portletContext, null); - } - - /** - * Create a new PortletContextAwareProcessor for the given config. - */ - public PortletContextAwareProcessor(PortletConfig portletConfig) { - this(null, portletConfig); - } - - /** - * Create a new PortletContextAwareProcessor for the given context and config. - */ - public PortletContextAwareProcessor(PortletContext portletContext, PortletConfig portletConfig) { - this.portletContext = portletContext; - this.portletConfig = portletConfig; - if (portletContext == null && portletConfig != null) { - this.portletContext = portletConfig.getPortletContext(); - } - } - - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (this.portletContext != null && bean instanceof PortletContextAware) { - ((PortletContextAware) bean).setPortletContext(this.portletContext); - } - if (this.portletConfig != null && bean instanceof PortletConfigAware) { - ((PortletConfigAware) bean).setPortletConfig(this.portletConfig); - } - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) { - return bean; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextPropertySource.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextPropertySource.java deleted file mode 100644 index 0627423745..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextPropertySource.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import javax.portlet.PortletContext; - -import org.springframework.core.env.EnumerablePropertySource; -import org.springframework.core.env.PropertySource; -import org.springframework.util.StringUtils; - -/** - * {@link PropertySource} that reads init parameters from a {@link PortletContext} object. - * - * @author Chris Beams - * @since 3.1 - * @see PortletConfigPropertySource - */ -public class PortletContextPropertySource extends EnumerablePropertySource { - - public PortletContextPropertySource(String name, PortletContext portletContext) { - super(name, portletContext); - } - - @Override - public String[] getPropertyNames() { - return StringUtils.toStringArray(this.source.getInitParameterNames()); - } - - @Override - public String getProperty(String name) { - return this.source.getInitParameter(name); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResource.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResource.java deleted file mode 100644 index 492d1432e8..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResource.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import javax.portlet.PortletContext; - -import org.springframework.core.io.AbstractFileResolvingResource; -import org.springframework.core.io.ContextResource; -import org.springframework.core.io.Resource; -import org.springframework.util.Assert; -import org.springframework.util.ResourceUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * {@link org.springframework.core.io.Resource} implementation for - * {@link javax.portlet.PortletContext} resources, interpreting - * relative paths within the portlet application root directory. - * - *

        Always supports stream access and URL access, but only allows - * {@code java.io.File} access when the portlet application archive - * is expanded. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see javax.portlet.PortletContext#getResourceAsStream - * @see javax.portlet.PortletContext#getRealPath - */ -public class PortletContextResource extends AbstractFileResolvingResource implements ContextResource { - - private final PortletContext portletContext; - - private final String path; - - - /** - * Create a new PortletContextResource. - *

        The Portlet spec requires that resource paths start with a slash, - * even if many containers accept paths without leading slash too. - * Consequently, the given path will be prepended with a slash if it - * doesn't already start with one. - * @param portletContext the PortletContext to load from - * @param path the path of the resource - */ - public PortletContextResource(PortletContext portletContext, String path) { - // check PortletContext - Assert.notNull(portletContext, "Cannot resolve PortletContextResource without PortletContext"); - this.portletContext = portletContext; - - // check path - Assert.notNull(path, "Path is required"); - String pathToUse = StringUtils.cleanPath(path); - if (!pathToUse.startsWith("/")) { - pathToUse = "/" + pathToUse; - } - this.path = pathToUse; - } - - /** - * Return the PortletContext for this resource. - */ - public final PortletContext getPortletContext() { - return this.portletContext; - } - - /** - * Return the path for this resource. - */ - public final String getPath() { - return this.path; - } - - - /** - * This implementation checks {@code PortletContext.getResource}. - * @see javax.portlet.PortletContext#getResource(String) - */ - @Override - public boolean exists() { - try { - URL url = this.portletContext.getResource(this.path); - return (url != null); - } - catch (MalformedURLException ex) { - return false; - } - } - - /** - * This implementation delegates to {@code PortletContext.getResourceAsStream}, - * which returns {@code null} in case of a non-readable resource (e.g. a directory). - * @see javax.portlet.PortletContext#getResourceAsStream(String) - */ - @Override - public boolean isReadable() { - InputStream is = this.portletContext.getResourceAsStream(this.path); - if (is != null) { - try { - is.close(); - } - catch (IOException ex) { - // ignore - } - return true; - } - else { - return false; - } - } - - /** - * This implementation delegates to {@code PortletContext.getResourceAsStream}, - * but throws a FileNotFoundException if not found. - * @see javax.portlet.PortletContext#getResourceAsStream(String) - */ - @Override - public InputStream getInputStream() throws IOException { - InputStream is = this.portletContext.getResourceAsStream(this.path); - if (is == null) { - throw new FileNotFoundException("Could not open " + getDescription()); - } - return is; - } - - /** - * This implementation delegates to {@code PortletContext.getResource}, - * but throws a FileNotFoundException if no resource found. - * @see javax.portlet.PortletContext#getResource(String) - */ - @Override - public URL getURL() throws IOException { - URL url = this.portletContext.getResource(this.path); - if (url == null) { - throw new FileNotFoundException( - getDescription() + " cannot be resolved to URL because it does not exist"); - } - return url; - } - - /** - * This implementation resolves "file:" URLs or alternatively delegates to - * {@code PortletContext.getRealPath}, throwing a FileNotFoundException - * if not found or not resolvable. - * @see javax.portlet.PortletContext#getResource(String) - * @see javax.portlet.PortletContext#getRealPath(String) - */ - @Override - public File getFile() throws IOException { - URL url = getURL(); - if (ResourceUtils.isFileURL(url)) { - // Proceed with file system resolution... - return super.getFile(); - } - else { - String realPath = PortletUtils.getRealPath(this.portletContext, this.path); - return new File(realPath); - } - } - - @Override - public Resource createRelative(String relativePath) { - String pathToUse = StringUtils.applyRelativePath(this.path, relativePath); - return new PortletContextResource(this.portletContext, pathToUse); - } - - @Override - public String getFilename() { - return StringUtils.getFilename(this.path); - } - - @Override - public String getDescription() { - return "PortletContext resource [" + this.path + "]"; - } - - @Override - public String getPathWithinContext() { - return this.path; - } - - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof PortletContextResource) { - PortletContextResource otherRes = (PortletContextResource) obj; - return (this.portletContext.equals(otherRes.portletContext) && this.path.equals(otherRes.path)); - } - return false; - } - - @Override - public int hashCode() { - return this.path.hashCode(); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourceLoader.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourceLoader.java deleted file mode 100644 index b72541e9e6..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourceLoader.java +++ /dev/null @@ -1,61 +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.context; - -import javax.portlet.PortletContext; - -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; - -/** - * ResourceLoader implementation that resolves paths as PortletContext - * resources, for use outside a Portlet ApplicationContext (for example, - * in a GenericPortletBean subclass). - * - *

        Within a WebApplicationContext, resource paths are automatically - * resolved as PortletContext resources by the context implementation. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see #getResourceByPath - * @see PortletContextResource - * @see org.springframework.web.portlet.GenericPortletBean - */ -public class PortletContextResourceLoader extends DefaultResourceLoader { - - private final PortletContext portletContext; - - - /** - * Create a new PortletContextResourceLoader. - * @param portletContext the PortletContext to load resources with - */ - public PortletContextResourceLoader(PortletContext portletContext) { - this.portletContext = portletContext; - } - - /** - * This implementation supports file paths beneath the root of the web application. - * @see PortletContextResource - */ - @Override - protected Resource getResourceByPath(String path) { - return new PortletContextResource(this.portletContext, path); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java deleted file mode 100644 index 2fb36297c5..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextResourcePatternResolver.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import java.io.IOException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import javax.portlet.PortletContext; - -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.util.StringUtils; - -/** - * PortletContext-aware subclass of {@link PathMatchingResourcePatternResolver}, - * able to find matching resources below the web application root directory - * via Portlet API's {@code PortletContext.getResourcePaths}. - * Falls back to the superclass' file system checking for other resources. - * - *

        The advantage of using {@code PortletContext.getResourcePaths} to - * find matching files is that it will work in a WAR file which has not been - * expanded too. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - */ -public class PortletContextResourcePatternResolver extends PathMatchingResourcePatternResolver { - - /** - * Create a new PortletContextResourcePatternResolver. - * @param portletContext the PortletContext to load resources with - * @see PortletContextResourceLoader#PortletContextResourceLoader(javax.portlet.PortletContext) - */ - public PortletContextResourcePatternResolver(PortletContext portletContext) { - super(new PortletContextResourceLoader(portletContext)); - } - - /** - * Create a new PortletContextResourcePatternResolver. - * @param resourceLoader the ResourceLoader to load root directories and - * actual resources with - */ - public PortletContextResourcePatternResolver(ResourceLoader resourceLoader) { - super(resourceLoader); - } - - - /** - * Overridden version which checks for PortletContextResource - * and uses {@code PortletContext.getResourcePaths} to find - * matching resources below the web application root directory. - * In case of other resources, delegates to the superclass version. - * @see #doRetrieveMatchingPortletContextResources - * @see PortletContextResource - * @see javax.portlet.PortletContext#getResourcePaths - */ - @Override - protected Set doFindPathMatchingFileResources(Resource rootDirResource, String subPattern) throws IOException { - if (rootDirResource instanceof PortletContextResource) { - PortletContextResource pcResource = (PortletContextResource) rootDirResource; - PortletContext pc = pcResource.getPortletContext(); - String fullPattern = pcResource.getPath() + subPattern; - Set result = new HashSet(); - doRetrieveMatchingPortletContextResources(pc, fullPattern, pcResource.getPath(), result); - return result; - } - return super.doFindPathMatchingFileResources(rootDirResource, subPattern); - } - - /** - * Recursively retrieve PortletContextResources that match the given pattern, - * adding them to the given result set. - * @param portletContext the PortletContext to work on - * @param fullPattern the pattern to match against, - * with preprended root directory path - * @param dir the current directory - * @param result the Set of matching Resources to add to - * @throws IOException if directory contents could not be retrieved - * @see org.springframework.web.portlet.context.PortletContextResource - * @see javax.portlet.PortletContext#getResourcePaths - */ - protected void doRetrieveMatchingPortletContextResources( - PortletContext portletContext, String fullPattern, String dir, Set result) throws IOException { - - Set candidates = portletContext.getResourcePaths(dir); - if (candidates != null) { - boolean dirDepthNotFixed = fullPattern.contains("**"); - for (Iterator it = candidates.iterator(); it.hasNext();) { - String currPath = it.next(); - if (currPath.endsWith("/") && - (dirDepthNotFixed || - StringUtils.countOccurrencesOf(currPath, "/") <= StringUtils.countOccurrencesOf(fullPattern, "/"))) { - doRetrieveMatchingPortletContextResources(portletContext, fullPattern, currPath, result); - } - if (getPathMatcher().match(fullPattern, currPath)) { - result.add(new PortletContextResource(portletContext, currPath)); - } - } - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextScope.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextScope.java deleted file mode 100644 index e2c42a09bb..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletContextScope.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import java.util.LinkedHashMap; -import java.util.Map; -import javax.portlet.PortletContext; - -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.ObjectFactory; -import org.springframework.beans.factory.config.Scope; -import org.springframework.util.Assert; - -/** - * {@link Scope} wrapper for a PortletContext, i.e. for global web application attributes. - * - *

        This differs from traditional Spring singletons in that it exposes attributes in the - * PortletContext. Those attributes will get destroyed whenever the entire application - * shuts down, which might be earlier or later than the shutdown of the containing Spring - * ApplicationContext. - * - *

        The associated destruction mechanism relies on a - * {@link org.springframework.web.context.ContextCleanupListener} being registered in - * {@code web.xml}. Note that {@link org.springframework.web.context.ContextLoaderListener} - * includes ContextCleanupListener's functionality. - * - *

        This scope is registered as default scope with key - * {@link org.springframework.web.context.WebApplicationContext#SCOPE_APPLICATION "application"}. - * - * @author Juergen Hoeller - * @since 3.0 - * @see org.springframework.web.context.ContextCleanupListener - */ -public class PortletContextScope implements Scope, DisposableBean { - - private final PortletContext portletContext; - - private final Map destructionCallbacks = new LinkedHashMap(); - - - /** - * Create a new Scope wrapper for the given PortletContext. - * @param portletContext the PortletContext to wrap - */ - public PortletContextScope(PortletContext portletContext) { - Assert.notNull(portletContext, "PortletContext must not be null"); - this.portletContext = portletContext; - } - - - @Override - public Object get(String name, ObjectFactory objectFactory) { - Object scopedObject = this.portletContext.getAttribute(name); - if (scopedObject == null) { - scopedObject = objectFactory.getObject(); - this.portletContext.setAttribute(name, scopedObject); - } - return scopedObject; - } - - @Override - public Object remove(String name) { - Object scopedObject = this.portletContext.getAttribute(name); - if (scopedObject != null) { - this.portletContext.removeAttribute(name); - this.destructionCallbacks.remove(name); - return scopedObject; - } - else { - return null; - } - } - - @Override - public void registerDestructionCallback(String name, Runnable callback) { - this.destructionCallbacks.put(name, callback); - } - - @Override - public Object resolveContextualObject(String key) { - return null; - } - - @Override - public String getConversationId() { - return null; - } - - - /** - * Invoke all registered destruction callbacks. - * To be called on ServletContext shutdown. - * @see org.springframework.web.context.ContextCleanupListener - */ - @Override - public void destroy() { - for (Runnable runnable : this.destructionCallbacks.values()) { - runnable.run(); - } - this.destructionCallbacks.clear(); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java deleted file mode 100644 index 936dfdec33..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestAttributes.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Copyright 2002-2016 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.context; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; - -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import org.springframework.web.context.request.AbstractRequestAttributes; -import org.springframework.web.context.request.DestructionCallbackBindingListener; -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Portlet-based implementation of the - * {@link org.springframework.web.context.request.RequestAttributes} interface. - * - *

        Accesses objects from portlet request and portlet session scope, - * with a distinction between "session" (the PortletSession's "portlet scope") - * and "global session" (the PortletSession's "application scope"). - * - * @author Juergen Hoeller - * @since 2.0 - * @see javax.portlet.PortletRequest#getAttribute - * @see javax.portlet.PortletSession#getAttribute - * @see javax.portlet.PortletSession#PORTLET_SCOPE - * @see javax.portlet.PortletSession#APPLICATION_SCOPE - * @see RequestAttributes#SCOPE_SESSION - * @see RequestAttributes#SCOPE_GLOBAL_SESSION - */ -public class PortletRequestAttributes extends AbstractRequestAttributes { - - /** - * Constant identifying the {@link String} prefixed to the name of a - * destruction callback when it is stored in a {@link PortletSession}. - */ - public static final String DESTRUCTION_CALLBACK_NAME_PREFIX = - PortletRequestAttributes.class.getName() + ".DESTRUCTION_CALLBACK."; - - - private final PortletRequest request; - - private PortletResponse response; - - private volatile PortletSession session; - - private final Map sessionAttributesToUpdate = new ConcurrentHashMap(1); - - private final Map globalSessionAttributesToUpdate = new ConcurrentHashMap(1); - - - /** - * Create a new PortletRequestAttributes instance for the given request. - * @param request current portlet request - */ - public PortletRequestAttributes(PortletRequest request) { - Assert.notNull(request, "Request must not be null"); - this.request = request; - } - - /** - * Create a new PortletRequestAttributes instance for the given request. - * @param request current portlet request - * @param response current portlet response (for optional exposure) - */ - public PortletRequestAttributes(PortletRequest request, PortletResponse response) { - this(request); - this.response = response; - } - - - /** - * Exposes the native {@link PortletRequest} that we're wrapping. - */ - public final PortletRequest getRequest() { - return this.request; - } - - /** - * Exposes the native {@link PortletResponse} that we're wrapping (if any). - */ - public final PortletResponse getResponse() { - return this.response; - } - - /** - * Exposes the {@link PortletSession} that we're wrapping. - * @param allowCreate whether to allow creation of a new session if none exists yet - */ - protected final PortletSession getSession(boolean allowCreate) { - if (isRequestActive()) { - PortletSession session = this.request.getPortletSession(allowCreate); - this.session = session; - return session; - } - else { - // Access through stored session reference, if any... - PortletSession session = this.session; - if (session == null) { - if (allowCreate) { - throw new IllegalStateException( - "No session found and request already completed - cannot create new session!"); - } - else { - session = this.request.getPortletSession(false); - this.session = session; - } - } - return session; - } - } - - - @Override - public Object getAttribute(String name, int scope) { - if (scope == SCOPE_REQUEST) { - if (!isRequestActive()) { - throw new IllegalStateException( - "Cannot ask for request attribute - request is not active anymore!"); - } - return this.request.getAttribute(name); - } - else { - PortletSession session = getSession(false); - if (session != null) { - if (scope == SCOPE_GLOBAL_SESSION) { - Object value = session.getAttribute(name, PortletSession.APPLICATION_SCOPE); - if (value != null) { - this.globalSessionAttributesToUpdate.put(name, value); - } - return value; - } - else { - Object value = session.getAttribute(name); - if (value != null) { - this.sessionAttributesToUpdate.put(name, value); - } - return value; - } - } - return null; - } - } - - @Override - public void setAttribute(String name, Object value, int scope) { - if (scope == SCOPE_REQUEST) { - if (!isRequestActive()) { - throw new IllegalStateException( - "Cannot set request attribute - request is not active anymore!"); - } - this.request.setAttribute(name, value); - } - else { - PortletSession session = getSession(true); - if (scope == SCOPE_GLOBAL_SESSION) { - session.setAttribute(name, value, PortletSession.APPLICATION_SCOPE); - this.globalSessionAttributesToUpdate.remove(name); - } - else { - session.setAttribute(name, value); - this.sessionAttributesToUpdate.remove(name); - } - } - } - - @Override - public void removeAttribute(String name, int scope) { - if (scope == SCOPE_REQUEST) { - if (isRequestActive()) { - this.request.removeAttribute(name); - removeRequestDestructionCallback(name); - } - } - else { - PortletSession session = getSession(false); - if (session != null) { - if (scope == SCOPE_GLOBAL_SESSION) { - session.removeAttribute(name, PortletSession.APPLICATION_SCOPE); - this.globalSessionAttributesToUpdate.remove(name); - } - else { - session.removeAttribute(name); - this.sessionAttributesToUpdate.remove(name); - } - } - } - } - - @Override - public String[] getAttributeNames(int scope) { - if (scope == SCOPE_REQUEST) { - if (!isRequestActive()) { - throw new IllegalStateException( - "Cannot ask for request attributes - request is not active anymore!"); - } - return StringUtils.toStringArray(this.request.getAttributeNames()); - } - else { - PortletSession session = getSession(false); - if (session != null) { - if (scope == SCOPE_GLOBAL_SESSION) { - return StringUtils.toStringArray(session.getAttributeNames(PortletSession.APPLICATION_SCOPE)); - } - else { - return StringUtils.toStringArray(session.getAttributeNames()); - } - } - return new String[0]; - } - } - - @Override - public void registerDestructionCallback(String name, Runnable callback, int scope) { - if (scope == SCOPE_REQUEST) { - registerRequestDestructionCallback(name, callback); - } - else { - registerSessionDestructionCallback(name, callback); - } - } - - @Override - public Object resolveReference(String key) { - if (REFERENCE_REQUEST.equals(key)) { - return this.request; - } - else if (REFERENCE_SESSION.equals(key)) { - return getSession(true); - } - else { - return null; - } - } - - @Override - public String getSessionId() { - return getSession(true).getId(); - } - - @Override - public Object getSessionMutex() { - return PortletUtils.getSessionMutex(getSession(true)); - } - - - /** - * Update all accessed session attributes through {@code session.setAttribute} - * calls, explicitly indicating to the container that they might have been modified. - */ - @Override - protected void updateAccessedSessionAttributes() { - if (!this.sessionAttributesToUpdate.isEmpty() || !this.globalSessionAttributesToUpdate.isEmpty()) { - PortletSession session = getSession(false); - if (session != null) { - try { - for (Map.Entry entry : this.sessionAttributesToUpdate.entrySet()) { - String name = entry.getKey(); - Object newValue = entry.getValue(); - Object oldValue = session.getAttribute(name); - if (oldValue == newValue) { - session.setAttribute(name, newValue); - } - } - for (Map.Entry entry : this.globalSessionAttributesToUpdate.entrySet()) { - String name = entry.getKey(); - Object newValue = entry.getValue(); - Object oldValue = session.getAttribute(name, PortletSession.APPLICATION_SCOPE); - if (oldValue == newValue) { - session.setAttribute(name, newValue, PortletSession.APPLICATION_SCOPE); - } - } - } - catch (IllegalStateException ex) { - // Session invalidated - shouldn't usually happen. - } - } - this.sessionAttributesToUpdate.clear(); - this.globalSessionAttributesToUpdate.clear(); - } - } - - /** - * Register the given callback as to be executed after session termination. - *

        Note: The callback object should be serializable in order to survive - * web app restarts. - * @param name the name of the attribute to register the callback for - * @param callback the callback to be executed for destruction - */ - protected void registerSessionDestructionCallback(String name, Runnable callback) { - PortletSession session = getSession(true); - session.setAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name, - new DestructionCallbackBindingListener(callback)); - } - - - @Override - public String toString() { - return this.request.toString(); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java deleted file mode 100644 index ce047869b5..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletRequestHandledEvent.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import org.springframework.web.context.support.RequestHandledEvent; - -/** - * Portlet-specific subclass of RequestHandledEvent, - * adding portlet-specific context information. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see org.springframework.web.portlet.FrameworkPortlet - * @see org.springframework.context.ApplicationContext#publishEvent - */ -@SuppressWarnings("serial") -public class PortletRequestHandledEvent extends RequestHandledEvent { - - /** Name of the portlet that handled the request */ - private final String portletName; - - /** PortletMode of the request */ - private final String portletMode; - - /** Type of Portlet Request */ - private final String requestType; - - - /** - * Create a new PortletRequestHandledEvent. - * @param source the component that published the event - * @param portletName the name of the portlet that handled the request - * @param portletMode the PortletMode of the request (usually 'view', 'edit', or 'help') - * @param requestType the type of Portlet request ('action' or 'render') - * @param sessionId the id of the HTTP session, if any - * @param userName the name of the user that was associated with the - * request, if any (usually the UserPrincipal) - * @param processingTimeMillis the processing time of the request in milliseconds - */ - public PortletRequestHandledEvent(Object source, String portletName, - String portletMode, String requestType, String sessionId, - String userName, long processingTimeMillis) { - - super(source, sessionId, userName, processingTimeMillis); - this.portletName = portletName; - this.portletMode = portletMode; - this.requestType = requestType; - } - - /** - * Create a new PortletRequestHandledEvent. - * @param source the component that published the event - * @param portletName the name of the portlet that handled the request - * @param portletMode the PortletMode of the request (usually 'view', 'edit', or 'help') - * @param requestType the type of Portlet request ('action' or 'render') - * @param sessionId the id of the HTTP session, if any - * @param userName the name of the user that was associated with the - * request, if any (usually the UserPrincipal) - * @param processingTimeMillis the processing time of the request in milliseconds - * @param failureCause the cause of failure, if any - */ - public PortletRequestHandledEvent(Object source, String portletName, - String portletMode, String requestType, String sessionId, - String userName, long processingTimeMillis, Throwable failureCause) { - - super(source, sessionId, userName, processingTimeMillis, failureCause); - this.portletName = portletName; - this.portletMode = portletMode; - this.requestType = requestType; - } - - - /** - * Return the name of the portlet that handled the request. - */ - public String getPortletName() { - return this.portletName; - } - - /** - * Return the mode of the portlet request (usually 'view', 'edit', or 'help'). - */ - public String getPortletMode() { - return this.portletMode; - } - - /** - * Return the type of Portlet Request ('action' or 'render'). - */ - public String getRequestType() { - return this.requestType; - } - - - @Override - public String getShortDescription() { - StringBuilder sb = new StringBuilder(); - sb.append("portlet=[").append(this.portletName).append("]; "); - sb.append(super.getShortDescription()); - return sb.toString(); - } - - @Override - public String getDescription() { - StringBuilder sb = new StringBuilder(); - sb.append("portlet=[").append(this.portletName).append("]; "); - sb.append("mode=[").append(this.portletMode).append("]; "); - sb.append("type=[").append(this.requestType).append("]; "); - sb.append(super.getDescription()); - return sb.toString(); - } - - @Override - public String toString() { - return "PortletRequestHandledEvent: " + getDescription(); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java deleted file mode 100644 index 12743cca9e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/PortletWebRequest.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2002-2015 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.context; - -import java.security.Principal; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; - -import org.springframework.util.CollectionUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * {@link org.springframework.web.context.request.WebRequest} adapter - * for a {@link javax.portlet.PortletRequest}. - * - * @author Juergen Hoeller - * @since 2.0 - */ -public class PortletWebRequest extends PortletRequestAttributes implements NativeWebRequest { - - /** - * Create a new PortletWebRequest instance for the given request. - * @param request current portlet request - */ - public PortletWebRequest(PortletRequest request) { - super(request); - } - - /** - * Create a new PortletWebRequest instance for the given request/response pair. - * @param request current portlet request - * @param response current portlet response - */ - public PortletWebRequest(PortletRequest request, PortletResponse response) { - super(request, response); - } - - - @Override - public Object getNativeRequest() { - return getRequest(); - } - - @Override - public Object getNativeResponse() { - return getResponse(); - } - - @Override - public T getNativeRequest(Class requiredType) { - return PortletUtils.getNativeRequest(getRequest(), requiredType); - } - - @Override - public T getNativeResponse(Class requiredType) { - return PortletUtils.getNativeResponse(getResponse(), requiredType); - } - - - @Override - public String getHeader(String headerName) { - return getRequest().getProperty(headerName); - } - - @Override - public String[] getHeaderValues(String headerName) { - String[] headerValues = StringUtils.toStringArray(getRequest().getProperties(headerName)); - return (!ObjectUtils.isEmpty(headerValues) ? headerValues : null); - } - - @Override - public Iterator getHeaderNames() { - return CollectionUtils.toIterator(getRequest().getPropertyNames()); - } - - @Override - public String getParameter(String paramName) { - return getRequest().getParameter(paramName); - } - - @Override - public String[] getParameterValues(String paramName) { - return getRequest().getParameterValues(paramName); - } - - @Override - public Iterator getParameterNames() { - return CollectionUtils.toIterator(getRequest().getParameterNames()); - } - - @Override - public Map getParameterMap() { - return getRequest().getParameterMap(); - } - - @Override - public Locale getLocale() { - return getRequest().getLocale(); - } - - @Override - public String getContextPath() { - return getRequest().getContextPath(); - } - - @Override - public String getRemoteUser() { - return getRequest().getRemoteUser(); - } - - @Override - public Principal getUserPrincipal() { - return getRequest().getUserPrincipal(); - } - - @Override - public boolean isUserInRole(String role) { - return getRequest().isUserInRole(role); - } - - @Override - public boolean isSecure() { - return getRequest().isSecure(); - } - - /** - * Last-modified handling not supported for portlet requests: - * As a consequence, this method always returns {@code false}. - */ - @Override - public boolean checkNotModified(long lastModifiedTimestamp) { - return false; - } - - /** - * Last-modified handling not supported for portlet requests: - * As a consequence, this method always returns {@code false}. - */ - @Override - public boolean checkNotModified(String eTag) { - return false; - } - - /** - * Last-modified handling not supported for portlet requests: - * As a consequence, this method always returns {@code false}. - * @since 4.2 - */ - @Override - public boolean checkNotModified(String etag, long lastModifiedTimestamp) { - return false; - } - - @Override - public String getDescription(boolean includeClientInfo) { - PortletRequest request = getRequest(); - StringBuilder result = new StringBuilder(); - result.append("context=").append(request.getContextPath()); - if (includeClientInfo) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - result.append(";session=").append(session.getId()); - } - String user = getRequest().getRemoteUser(); - if (StringUtils.hasLength(user)) { - result.append(";user=").append(user); - } - } - return result.toString(); - } - - - @Override - public String toString() { - return "PortletWebRequest: " + getDescription(true); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StandardPortletEnvironment.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StandardPortletEnvironment.java deleted file mode 100644 index e6a8172b8b..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StandardPortletEnvironment.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.servlet.ServletContext; - -import org.springframework.core.env.Environment; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertySource; -import org.springframework.core.env.PropertySource.StubPropertySource; -import org.springframework.core.env.StandardEnvironment; -import org.springframework.jndi.JndiLocatorDelegate; -import org.springframework.jndi.JndiPropertySource; -import org.springframework.web.context.support.StandardServletEnvironment; - -/** - * {@link Environment} implementation to be used by {@code Servlet}-based web - * applications. All Portlet-related {@code ApplicationContext} classes - * initialize an instance by default. - * - *

        Contributes {@code ServletContext}, {@code PortletContext}, - * {@code PortletConfig} and JNDI-based {@link PropertySource} instances. - * See the {@link #customizePropertySources} method for details. - * - * @author Chris Beams - * @author Juergen Hoeller - * @since 3.1 - * @see StandardEnvironment - * @see StandardServletEnvironment - */ -public class StandardPortletEnvironment extends StandardEnvironment { - - /** Portlet context init parameters property source name: {@value} */ - public static final String PORTLET_CONTEXT_PROPERTY_SOURCE_NAME = "portletContextInitParams"; - - /** Portlet config init parameters property source name: {@value} */ - public static final String PORTLET_CONFIG_PROPERTY_SOURCE_NAME = "portletConfigInitParams"; - - - /** - * Customize the set of property sources with those contributed by superclasses as - * well as those appropriate for standard portlet-based environments: - *

          - *
        • {@value #PORTLET_CONFIG_PROPERTY_SOURCE_NAME} - *
        • {@value #PORTLET_CONTEXT_PROPERTY_SOURCE_NAME} - *
        • {@linkplain StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME "servletContextInitParams"} - *
        • {@linkplain StandardServletEnvironment#JNDI_PROPERTY_SOURCE_NAME "jndiProperties"} - *
        - *

        Properties present in {@value #PORTLET_CONFIG_PROPERTY_SOURCE_NAME} will - * take precedence over those in {@value #PORTLET_CONTEXT_PROPERTY_SOURCE_NAME}, - * which takes precedence over those in {@linkplain - * StandardServletEnvironment#SERVLET_CONTEXT_PROPERTY_SOURCE_NAME "servletContextInitParams"} - * and so on. - *

        Properties in any of the above will take precedence over system properties and - * environment variables contributed by the {@link StandardEnvironment} superclass. - *

        The property sources are added as stubs for now, and will be - * {@linkplain PortletApplicationContextUtils#initPortletPropertySources fully - * initialized} once the actual {@link PortletConfig}, {@link PortletContext}, and - * {@link ServletContext} objects are available. - * @see StandardEnvironment#customizePropertySources - * @see org.springframework.core.env.AbstractEnvironment#customizePropertySources - * @see PortletConfigPropertySource - * @see PortletContextPropertySource - * @see PortletApplicationContextUtils#initPortletPropertySources - */ - @Override - protected void customizePropertySources(MutablePropertySources propertySources) { - propertySources.addLast(new StubPropertySource(PORTLET_CONFIG_PROPERTY_SOURCE_NAME)); - propertySources.addLast(new StubPropertySource(PORTLET_CONTEXT_PROPERTY_SOURCE_NAME)); - propertySources.addLast(new StubPropertySource(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME)); - if (JndiLocatorDelegate.isDefaultJndiEnvironmentAvailable()) { - propertySources.addLast(new JndiPropertySource(StandardServletEnvironment.JNDI_PROPERTY_SOURCE_NAME)); - } - super.customizePropertySources(propertySources); - } - - /** - * Replace any {@linkplain - * org.springframework.core.env.PropertySource.StubPropertySource stub property source} - * instances acting as placeholders with real portlet context/config property sources - * using the given parameters. - * @param servletContext the {@link ServletContext} (may be {@code null}) - * @param portletContext the {@link PortletContext} (may not be {@code null}) - * @param portletConfig the {@link PortletConfig} ({@code null} if not available) - * @see org.springframework.web.portlet.context.PortletApplicationContextUtils#initPortletPropertySources( - * org.springframework.core.env.MutablePropertySources, ServletContext, PortletContext, PortletConfig) - */ - public void initPropertySources(ServletContext servletContext, PortletContext portletContext, PortletConfig portletConfig) { - PortletApplicationContextUtils.initPortletPropertySources(getPropertySources(), servletContext, portletContext, portletConfig); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java deleted file mode 100644 index 1784829807..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/StaticPortletApplicationContext.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.servlet.ServletContext; - -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.StaticApplicationContext; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.io.Resource; -import org.springframework.core.io.support.ResourcePatternResolver; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.ServletContextAwareProcessor; - -/** - * Static Portlet-based {@link org.springframework.context.ApplicationContext} - * implementation for testing. Not intended for use in production applications. - * - *

        Implements the - * {@link org.springframework.web.portlet.context.ConfigurablePortletApplicationContext} - * interface to allow for direct replacement of an {@link XmlPortletApplicationContext}, - * despite not actually supporting external configuration files. - * - *

        Interprets resource paths as portlet context resources, that is, as paths - * beneath the portlet application root. Absolute paths, for example for files - * outside the portlet app root, can be accessed via "file:" URLs, as implemented - * by {@link org.springframework.core.io.DefaultResourceLoader}. - * - * @author Juergen Hoeller - * @author Mark Fisher - * @since 2.0 - */ -public class StaticPortletApplicationContext extends StaticApplicationContext - implements ConfigurablePortletApplicationContext { - - private ServletContext servletContext; - - private PortletContext portletContext; - - private PortletConfig portletConfig; - - private String namespace; - - - public StaticPortletApplicationContext() { - setDisplayName("Root Portlet ApplicationContext"); - } - - - /** - * Return a new {@link StandardPortletEnvironment} - */ - @Override - protected ConfigurableEnvironment createEnvironment() { - return new StandardPortletEnvironment(); - } - - /** - * {@inheritDoc} - *

        Replace {@code Portlet}- and {@code Servlet}-related property sources. - */ - @Override - protected void initPropertySources() { - PortletApplicationContextUtils.initPortletPropertySources(getEnvironment().getPropertySources(), - this.servletContext, this.portletContext, this.portletConfig); - } - - /** - * {@inheritDoc} - *

        The parent {@linkplain #getEnvironment() environment} is - * delegated to this (child) context if the parent is a - * {@link org.springframework.context.ConfigurableApplicationContext} implementation. - *

        The parent {@linkplain #getServletContext() servlet context} is - * delegated to this (child) context if the parent is a {@link WebApplicationContext} - * implementation. - */ - @Override - public void setParent(ApplicationContext parent) { - super.setParent(parent); - if (parent instanceof WebApplicationContext) { - this.servletContext = ((WebApplicationContext) parent).getServletContext(); - } - } - - @Override - public ServletContext getServletContext() { - return this.servletContext; - } - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - @Override - public void setPortletConfig(PortletConfig portletConfig) { - this.portletConfig = portletConfig; - if (portletConfig != null && this.portletContext == null) { - this.portletContext = portletConfig.getPortletContext(); - } - } - - @Override - public PortletConfig getPortletConfig() { - return this.portletConfig; - } - - @Override - public void setNamespace(String namespace) { - this.namespace = namespace; - if (namespace != null) { - setDisplayName("Portlet ApplicationContext for namespace '" + namespace + "'"); - } - } - - @Override - public String getNamespace() { - return this.namespace; - } - - /** - * The {@link StaticPortletApplicationContext} class does not support this method. - * @throws UnsupportedOperationException always - */ - @Override - public void setConfigLocation(String configLocation) { - if (configLocation != null) { - throw new UnsupportedOperationException("StaticPortletApplicationContext does not support config locations"); - } - } - - /** - * The {@link StaticPortletApplicationContext} class does not support this method. - * @throws UnsupportedOperationException always - */ - @Override - public void setConfigLocations(String... configLocations) { - if (configLocations != null) { - throw new UnsupportedOperationException("StaticPortletApplicationContext does not support config locations"); - } - } - - @Override - public String[] getConfigLocations() { - return null; - } - - - /** - * Register request/session scopes, a {@link PortletContextAwareProcessor}, etc. - */ - @Override - protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { - beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext)); - beanFactory.addBeanPostProcessor(new PortletContextAwareProcessor(this.portletContext, this.portletConfig)); - beanFactory.ignoreDependencyInterface(PortletContextAware.class); - beanFactory.ignoreDependencyInterface(PortletConfigAware.class); - - PortletApplicationContextUtils.registerPortletApplicationScopes(beanFactory, this.portletContext); - PortletApplicationContextUtils.registerEnvironmentBeans( - beanFactory, this.servletContext, this.portletContext, this.portletConfig); - } - - /** - * This implementation supports file paths beneath the root of the PortletContext. - * @see PortletContextResource - */ - @Override - protected Resource getResourceByPath(String path) { - return new PortletContextResource(this.portletContext, path); - } - - /** - * This implementation supports pattern matching in unexpanded WARs too. - * @see PortletContextResourcePatternResolver - */ - @Override - protected ResourcePatternResolver getResourcePatternResolver() { - return new PortletContextResourcePatternResolver(this); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/XmlPortletApplicationContext.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/XmlPortletApplicationContext.java deleted file mode 100644 index 83769628ac..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/XmlPortletApplicationContext.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * 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.context; - -import java.io.IOException; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.beans.factory.xml.ResourceEntityResolver; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; - -/** - * Portlet-based {@link org.springframework.web.context.WebApplicationContext} - * implementation which takes its configuration from XML documents, understood - * by an {@link org.springframework.beans.factory.xml.XmlBeanDefinitionReader}. - * This is essentially the equivalent of - * {@link org.springframework.context.support.AbstractXmlApplicationContext} - * for a portlet environment. - * - *

        By default, the configuration will be taken from "/WEB-INF/applicationContext.xml" - * for the root context, and "/WEB-INF/test-portlet.xml" for a context with the namespace - * "test-portlet" (like for a DispatcherPortlet instance with the portlet-name "test"). - * - *

        The config location defaults can be overridden via the "contextConfigLocation" - * portlet init-param of {@link org.springframework.web.portlet.FrameworkPortlet}. - * Config locations can either denote concrete files like "/WEB-INF/context.xml" - * or Ant-style patterns like "/WEB-INF/*-context.xml" (see - * {@link org.springframework.util.PathMatcher} javadoc for pattern details). - * - *

        Note: In case of multiple config locations, later bean definitions will - * override ones defined in earlier loaded files. This can be leveraged to - * deliberately override certain bean definitions via an extra XML file. - * - *

        For a Portlet-based context that reads in a different bean definition format, - * create an analogous subclass of {@link AbstractRefreshablePortletApplicationContext}. - * Such a context implementation can be specified as "contextClass" init-param - * for a FrameworkPortlet instance. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see #setNamespace - * @see #setConfigLocations - * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader - * @see org.springframework.web.portlet.FrameworkPortlet#initPortletApplicationContext - */ -public class XmlPortletApplicationContext extends AbstractRefreshablePortletApplicationContext { - - /** Default config location for the root context */ - public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml"; - - /** Default prefix for building a config location for a namespace */ - public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/"; - - /** Default suffix for building a config location for a namespace */ - public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml"; - - - /** - * Loads the bean definitions via an XmlBeanDefinitionReader. - * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader - * @see #initBeanDefinitionReader - * @see #loadBeanDefinitions - */ - @Override - protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { - // Create a new XmlBeanDefinitionReader for the given BeanFactory. - XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); - - // Configure the bean definition reader with this context's - // resource loading environment. - beanDefinitionReader.setEnvironment(this.getEnvironment()); - beanDefinitionReader.setResourceLoader(this); - beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); - - // Allow a subclass to provide custom initialization of the reader, - // then proceed with actually loading the bean definitions. - initBeanDefinitionReader(beanDefinitionReader); - loadBeanDefinitions(beanDefinitionReader); - } - - /** - * Initialize the bean definition reader used for loading the bean - * definitions of this context. Default implementation is empty. - *

        Can be overridden in subclasses, e.g. for turning off XML validation - * or using a different XmlBeanDefinitionParser implementation. - * @param beanDefinitionReader the bean definition reader used by this context - * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setValidationMode - * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader#setDocumentReaderClass - */ - protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) { - } - - /** - * Load the bean definitions with the given XmlBeanDefinitionReader. - *

        The lifecycle of the bean factory is handled by the refreshBeanFactory method; - * therefore this method is just supposed to load and/or register bean definitions. - *

        Delegates to a ResourcePatternResolver for resolving location patterns - * into Resource instances. - * @throws org.springframework.beans.BeansException in case of bean registration errors - * @throws java.io.IOException if the required XML document isn't found - * @see #refreshBeanFactory - * @see #getConfigLocations - * @see #getResources - * @see #getResourcePatternResolver - */ - protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { - String[] configLocations = getConfigLocations(); - if (configLocations != null) { - for (int i = 0; i < configLocations.length; i++) { - reader.loadBeanDefinitions(configLocations[i]); - } - } - } - - /** - * The default location for the root context is "/WEB-INF/applicationContext.xml", - * and "/WEB-INF/test-portlet.xml" for a context with the namespace "test-portlet" - * (like for a DispatcherPortlet instance with the portlet-name "test"). - */ - @Override - protected String[] getDefaultConfigLocations() { - if (getNamespace() != null) { - return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX}; - } - else { - return new String[] {DEFAULT_CONFIG_LOCATION}; - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/package-info.java deleted file mode 100644 index ae77aa4ebd..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/context/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Support for Spring's application context concept in a portlet environment, - * including ApplicationContext implementations and various utility classes. - */ -package org.springframework.web.portlet.context; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerExceptionResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerExceptionResolver.java deleted file mode 100644 index c6e700d640..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerExceptionResolver.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright 2002-2015 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 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; -import org.apache.commons.logging.LogFactory; - -import org.springframework.core.Ordered; -import org.springframework.web.portlet.HandlerExceptionResolver; -import org.springframework.web.portlet.ModelAndView; - -/** - * Abstract base class for {@link HandlerExceptionResolver} implementations. - * - *

        Provides a set of mapped handlers that the resolver should map to, - * and the {@link Ordered} implementation. - * - * @author Arjen Poutsma - * @author Juergen Hoeller - * @since 3.0 - */ -public abstract class AbstractHandlerExceptionResolver implements HandlerExceptionResolver, Ordered { - - /** Logger available to subclasses */ - protected final Log logger = LogFactory.getLog(getClass()); - - private int order = Ordered.LOWEST_PRECEDENCE; - - private Set mappedHandlers; - - private Class[] mappedHandlerClasses; - - private Log warnLogger; - - private boolean renderWhenMinimized = false; - - - public void setOrder(int order) { - this.order = order; - } - - @Override - public int getOrder() { - return this.order; - } - - /** - * Specify the set of handlers that this exception resolver should apply to. - *

        The exception mappings and the default error view will only apply to the specified handlers. - *

        If no handlers or handler classes are set, the exception mappings and the default error - * view will apply to all handlers. This means that a specified default error view will be used - * as a fallback for all exceptions; any further HandlerExceptionResolvers in the chain will be - * ignored in this case. - */ - public void setMappedHandlers(Set mappedHandlers) { - this.mappedHandlers = mappedHandlers; - } - - /** - * Specify the set of classes that this exception resolver should apply to. - *

        The exception mappings and the default error view will only apply to handlers of the - * specified types; the specified types may be interfaces or superclasses of handlers as well. - *

        If no handlers or handler classes are set, the exception mappings and the default error - * view will apply to all handlers. This means that a specified default error view will be used - * as a fallback for all exceptions; any further HandlerExceptionResolvers in the chain will be - * ignored in this case. - */ - public void setMappedHandlerClasses(Class... mappedHandlerClasses) { - this.mappedHandlerClasses = mappedHandlerClasses; - } - - /** - * Set the log category for warn logging. The name will be passed to the underlying logger - * implementation through Commons Logging, getting interpreted as a log category according - * to the logger's configuration. - *

        Default is no warn logging. Specify this setting to activate warn logging into a specific - * category. Alternatively, override the {@link #logException} method for custom logging. - * @see org.apache.commons.logging.LogFactory#getLog(String) - * @see org.apache.log4j.Logger#getLogger(String) - * @see java.util.logging.Logger#getLogger(String) - */ - public void setWarnLogCategory(String loggerName) { - this.warnLogger = LogFactory.getLog(loggerName); - } - - /** - * Set if the resolver should render a view when the portlet is in - * a minimized window. The default is "false". - * @see javax.portlet.RenderRequest#getWindowState() - * @see javax.portlet.WindowState#MINIMIZED - */ - public void setRenderWhenMinimized(boolean renderWhenMinimized) { - this.renderWhenMinimized = renderWhenMinimized; - } - - - /** - * Checks whether this resolver is supposed to apply (i.e. the handler - * matches in case of "mappedHandlers" having been specified), then - * delegates to the {@link #doResolveException} template method. - */ - @Override - public ModelAndView resolveException(RenderRequest request, RenderResponse response, Object handler, Exception ex) { - if (shouldApplyTo(request, handler)) { - return doResolveException(request, response, handler, ex); - } - else { - return null; - } - } - - @Override - 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. - *

        The default implementation checks against the specified mapped handlers - * and handler classes, if any, and also checks the window state (according - * to the "renderWhenMinimize" property). - * @param request current portlet request - * @param handler the executed handler, or {@code null} if none chosen at the - * time of the exception (for example, if multipart resolution failed) - * @return whether this resolved should proceed with resolving the exception - * for the given request and handler - * @see #setMappedHandlers - * @see #setMappedHandlerClasses - */ - 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 (Class mappedClass : this.mappedHandlerClasses) { - if (mappedClass.isInstance(handler)) { - return true; - } - } - } - } - // Else only apply if there are no explicit handler mappings. - return (this.mappedHandlers == null && this.mappedHandlerClasses == null); - } - - /** - * Log the given exception at warn level, provided that warn logging has been - * activated through the {@link #setWarnLogCategory "warnLogCategory"} property. - *

        Calls {@link #buildLogMessage} in order to determine the concrete message to log. - * @param ex the exception that got thrown during handler execution - * @param request current portlet request (useful for obtaining metadata) - * @see #setWarnLogCategory - * @see #buildLogMessage - * @see org.apache.commons.logging.Log#warn(Object, Throwable) - */ - protected void logException(Exception ex, PortletRequest request) { - if (this.warnLogger != null && this.warnLogger.isWarnEnabled()) { - this.warnLogger.warn(buildLogMessage(ex, request)); - } - } - - /** - * Build a log message for the given exception, occurred during processing the given request. - * @param ex the exception that got thrown during handler execution - * @param request current portlet request (useful for obtaining metadata) - * @return the log message to use - */ - protected String buildLogMessage(Exception ex, PortletRequest request) { - return "Handler execution resulted in exception: " + ex; - } - - - /** - * Actually resolve the given exception that got thrown during on handler execution, - * returning a ModelAndView that represents a specific error page if appropriate. - *

        Must be overridden in subclasses, in order to apply specific exception checks. - * Note that this template method will be invoked after checking whether this - * resolved applies ("mappedHandlers" etc), so an implementation may simply proceed - * with its actual exception handling. - * @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 - */ - protected abstract ModelAndView doResolveException(PortletRequest request, MimeResponse response, - Object handler, Exception ex); - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerMapping.java deleted file mode 100644 index 37d9d83c1e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractHandlerMapping.java +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright 2002-2014 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 java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.portlet.PortletRequest; - -import org.springframework.beans.BeansException; -import org.springframework.context.support.ApplicationObjectSupport; -import org.springframework.core.Ordered; -import org.springframework.web.context.request.WebRequestInterceptor; -import org.springframework.web.portlet.HandlerExecutionChain; -import org.springframework.web.portlet.HandlerInterceptor; -import org.springframework.web.portlet.HandlerMapping; - -/** - * Abstract base class for {@link org.springframework.web.portlet.HandlerMapping} - * implementations. Supports ordering, a default handler, and handler interceptors. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see #getHandlerInternal - * @see #setDefaultHandler - * @see #setInterceptors - * @see org.springframework.web.portlet.HandlerInterceptor - */ -public abstract class AbstractHandlerMapping extends ApplicationObjectSupport implements HandlerMapping, Ordered { - - private int order = Integer.MAX_VALUE; // default: same as non-Ordered - - private Object defaultHandler; - - private final List interceptors = new ArrayList(); - - private boolean applyWebRequestInterceptorsToRenderPhaseOnly = true; - - private HandlerInterceptor[] adaptedInterceptors; - - - /** - * Specify the order value for this HandlerMapping bean. - *

        Default value is {@code Integer.MAX_VALUE}, meaning that it's non-ordered. - * @see org.springframework.core.Ordered#getOrder() - */ - public final void setOrder(int order) { - this.order = order; - } - - @Override - public final int getOrder() { - return this.order; - } - - /** - * Set the default handler for this handler mapping. - * This handler will be returned if no specific mapping was found. - *

        Default is {@code null}, indicating no default handler. - */ - public void setDefaultHandler(Object defaultHandler) { - this.defaultHandler = defaultHandler; - } - - /** - * Return the default handler for this handler mapping, - * or {@code null} if none. - */ - public Object getDefaultHandler() { - return this.defaultHandler; - } - - /** - * Set the interceptors to apply for all handlers mapped by this handler mapping. - *

        Supported interceptor types are HandlerInterceptor and WebRequestInterceptor. - * Each given WebRequestInterceptor will be wrapped in a WebRequestHandlerInterceptorAdapter. - * @param interceptors array of handler interceptors, or {@code null} if none - * @see #adaptInterceptor - * @see org.springframework.web.portlet.HandlerInterceptor - * @see org.springframework.web.context.request.WebRequestInterceptor - */ - public void setInterceptors(Object[] interceptors) { - this.interceptors.addAll(Arrays.asList(interceptors)); - } - - /** - * Specify whether to apply WebRequestInterceptors to the Portlet render phase - * only ("true", or whether to apply them to the Portlet action phase as well - * ("false"). - *

        Default is "true", since WebRequestInterceptors are usually built for - * MVC-style handler execution plus rendering process (which is, for example, - * the primary target scenario for "Open Session in View" interceptors, - * offering lazy loading of persistent objects during view rendering). - * Set this to "false" to have WebRequestInterceptors apply to the action - * phase as well (for example, in case of an "Open Session in View" interceptor, - * to allow for lazy loading outside of a transaction during the action phase). - * @see #setInterceptors - * @see org.springframework.web.context.request.WebRequestInterceptor - * @see WebRequestHandlerInterceptorAdapter#WebRequestHandlerInterceptorAdapter(WebRequestInterceptor, boolean) - * @see org.springframework.orm.jpa.support.OpenEntityManagerInViewInterceptor - */ - public void setApplyWebRequestInterceptorsToRenderPhaseOnly(boolean applyWebRequestInterceptorsToRenderPhaseOnly) { - this.applyWebRequestInterceptorsToRenderPhaseOnly = applyWebRequestInterceptorsToRenderPhaseOnly; - } - - - /** - * Initializes the interceptors. - * @see #extendInterceptors(java.util.List) - * @see #initInterceptors() - */ - @Override - protected void initApplicationContext() throws BeansException { - extendInterceptors(this.interceptors); - initInterceptors(); - } - - /** - * Extension hook that subclasses can override to register additional interceptors, - * given the configured interceptors (see {@link #setInterceptors}). - *

        Will be invoked before {@link #initInterceptors()} adapts the specified - * interceptors into {@link HandlerInterceptor} instances. - *

        The default implementation is empty. - * @param interceptors the configured interceptor List (never {@code null}), - * allowing to add further interceptors before as well as after the existing - * interceptors - */ - protected void extendInterceptors(List interceptors) { - } - - /** - * Initialize the specified interceptors, adapting them where necessary. - * @see #setInterceptors - * @see #adaptInterceptor - */ - protected void initInterceptors() { - if (!this.interceptors.isEmpty()) { - this.adaptedInterceptors = new HandlerInterceptor[this.interceptors.size()]; - for (int i = 0; i < this.interceptors.size(); i++) { - Object interceptor = this.interceptors.get(i); - if (interceptor == null) { - throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null"); - } - this.adaptedInterceptors[i] = adaptInterceptor(interceptor); - } - } - } - - /** - * Adapt the given interceptor object to the HandlerInterceptor interface. - *

        Supported interceptor types are HandlerInterceptor and WebRequestInterceptor. - * Each given WebRequestInterceptor will be wrapped in a WebRequestHandlerInterceptorAdapter. - * Can be overridden in subclasses. - * @param interceptor the specified interceptor object - * @return the interceptor wrapped as HandlerInterceptor - * @see #setApplyWebRequestInterceptorsToRenderPhaseOnly - * @see org.springframework.web.portlet.HandlerInterceptor - * @see org.springframework.web.context.request.WebRequestInterceptor - * @see WebRequestHandlerInterceptorAdapter - */ - protected HandlerInterceptor adaptInterceptor(Object interceptor) { - if (interceptor instanceof HandlerInterceptor) { - return (HandlerInterceptor) interceptor; - } - else if (interceptor instanceof WebRequestInterceptor) { - return new WebRequestHandlerInterceptorAdapter( - (WebRequestInterceptor) interceptor, this.applyWebRequestInterceptorsToRenderPhaseOnly); - } - else { - throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName()); - } - } - - /** - * Return the adapted interceptors as HandlerInterceptor array. - * @return the array of HandlerInterceptors, or {@code null} if none - */ - protected final HandlerInterceptor[] getAdaptedInterceptors() { - return this.adaptedInterceptors; - } - - - /** - * Look up a handler for the given request, falling back to the default - * handler if no specific one is found. - * @param request current portlet request - * @return the corresponding handler instance, or the default handler - * @see #getHandlerInternal - */ - @Override - public final HandlerExecutionChain getHandler(PortletRequest request) throws Exception { - Object handler = getHandlerInternal(request); - if (handler == null) { - handler = getDefaultHandler(); - } - if (handler == null) { - return null; - } - // Bean name or resolved handler? - if (handler instanceof String) { - String handlerName = (String) handler; - handler = getApplicationContext().getBean(handlerName); - } - return getHandlerExecutionChain(handler, request); - } - - /** - * Look up a handler for the given request, returning {@code null} if no - * specific one is found. This method is called by {@link #getHandler}; - * a {@code null} return value will lead to the default handler, if one is set. - *

        Note: This method may also return a pre-built {@link HandlerExecutionChain}, - * combining a handler object with dynamically determined interceptors. - * Statically specified interceptors will get merged into such an existing chain. - * @param request current portlet request - * @return the corresponding handler instance, or {@code null} if none found - * @throws Exception if there is an internal error - * @see #getHandler - */ - protected abstract Object getHandlerInternal(PortletRequest request) throws Exception; - - /** - * Build a HandlerExecutionChain for the given handler, including applicable interceptors. - *

        The default implementation simply builds a standard HandlerExecutionChain with - * the given handler and this handler mapping's common interceptors. Subclasses may - * override this in order to extend/rearrange the list of interceptors. - *

        NOTE: The passed-in handler object may be a raw handler or a pre-built - * HandlerExecutionChain. This method should handle those two cases explicitly, - * either building a new HandlerExecutionChain or extending the existing chain. - *

        For simply adding an interceptor, consider calling {@code super.getHandlerExecutionChain} - * and invoking {@link HandlerExecutionChain#addInterceptor} on the returned chain object. - * @param handler the resolved handler instance (never {@code null}) - * @param request current portlet request - * @return the HandlerExecutionChain (never {@code null}) - * @see #getAdaptedInterceptors() - */ - protected HandlerExecutionChain getHandlerExecutionChain(Object handler, PortletRequest request) { - if (handler instanceof HandlerExecutionChain) { - HandlerExecutionChain chain = (HandlerExecutionChain) handler; - chain.addInterceptors(getAdaptedInterceptors()); - return chain; - } - else { - return new HandlerExecutionChain(handler, getAdaptedInterceptors()); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java deleted file mode 100644 index 29c3b8c3e9..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/AbstractMapBasedHandlerMapping.java +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright 2002-2012 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 java.util.Collections; -import java.util.HashMap; -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; -import org.springframework.util.Assert; - -/** - * Abstract base class for {@link org.springframework.web.portlet.HandlerMapping} - * implementations that rely on a map which caches handler objects per lookup key. - * Supports arbitrary lookup keys, and automatically resolves handler bean names - * into handler bean instances. - * - * @author Juergen Hoeller - * @since 2.0 - * @see #getLookupKey(javax.portlet.PortletRequest) - * @see #registerHandler(Object, Object) - */ -public abstract class AbstractMapBasedHandlerMapping extends AbstractHandlerMapping { - - private boolean lazyInitHandlers = false; - - private final Map handlerMap = new HashMap(); - - - /** - * Set whether to lazily initialize handlers. Only applicable to - * singleton handlers, as prototypes are always lazily initialized. - * Default is false, as eager initialization allows for more efficiency - * through referencing the handler objects directly. - *

        If you want to allow your handlers to be lazily initialized, - * make them "lazy-init" and set this flag to true. Just making them - * "lazy-init" will not work, as they are initialized through the - * references from the handler mapping in this case. - */ - public void setLazyInitHandlers(boolean lazyInitHandlers) { - this.lazyInitHandlers = lazyInitHandlers; - } - - - /** - * Determines a handler for the computed lookup key for the given request. - * @see #getLookupKey - */ - @Override - @SuppressWarnings("unchecked") - protected Object getHandlerInternal(PortletRequest request) throws Exception { - K lookupKey = getLookupKey(request); - Object handler = this.handlerMap.get(lookupKey); - if (handler != null && logger.isDebugEnabled()) { - logger.debug("Key [" + lookupKey + "] -> handler [" + handler + "]"); - } - if (handler instanceof Map) { - Map predicateMap = - (Map) handler; - List filtered = new LinkedList(); - for (PortletRequestMappingPredicate predicate : predicateMap.keySet()) { - if (predicate.match(request)) { - filtered.add(predicate); - } - } - if (filtered.isEmpty()) { - return null; - } - Collections.sort(filtered); - PortletRequestMappingPredicate predicate = filtered.get(0); - predicate.validate(request); - return predicateMap.get(predicate); - } - return handler; - } - - /** - * Build a lookup key for the given request. - * @param request current portlet request - * @return the lookup key (never {@code null}) - * @throws Exception if key computation failed - */ - protected abstract K getLookupKey(PortletRequest request) throws Exception; - - - /** - * Register all handlers specified in the Portlet mode map for the corresponding modes. - * @param handlerMap Map with lookup keys as keys and handler beans or bean names as values - * @throws BeansException if the handler couldn't be registered - */ - protected void registerHandlers(Map handlerMap) throws BeansException { - Assert.notNull(handlerMap, "Handler Map must not be null"); - for (Map.Entry entry : handlerMap.entrySet()) { - registerHandler(entry.getKey(), entry.getValue()); - } - } - - /** - * Register the given handler instance for the given parameter value. - * @param lookupKey the key to map the handler onto - * @param handler the handler instance or handler bean name String - * (a bean name will automatically be resolved into the corresponding handler bean) - * @throws BeansException if the handler couldn't be registered - * @throws IllegalStateException if there is a conflicting handler registered - */ - protected void registerHandler(K lookupKey, Object handler) throws BeansException, IllegalStateException { - registerHandler(lookupKey, handler, null); - } - - /** - * Register the given handler instance for the given parameter value. - * @param lookupKey the key to map the handler onto - * @param handler the handler instance or handler bean name String - * (a bean name will automatically be resolved into the corresponding handler bean) - * @param predicate a predicate object for this handler (may be {@code null}), - * determining a match with the primary lookup key - * @throws BeansException if the handler couldn't be registered - * @throws IllegalStateException if there is a conflicting handler registered - */ - @SuppressWarnings("unchecked") - protected void registerHandler(K lookupKey, Object handler, PortletRequestMappingPredicate predicate) - throws BeansException, IllegalStateException { - - Assert.notNull(lookupKey, "Lookup key must not be null"); - Assert.notNull(handler, "Handler object must not be null"); - Object resolvedHandler = handler; - - // Eagerly resolve handler if referencing singleton via name. - if (!this.lazyInitHandlers && handler instanceof String) { - String handlerName = (String) handler; - if (getApplicationContext().isSingleton(handlerName)) { - resolvedHandler = getApplicationContext().getBean(handlerName); - } - } - - // Check for duplicate mapping. - Object mappedHandler = this.handlerMap.get(lookupKey); - if (mappedHandler != null && !(mappedHandler instanceof Map)) { - if (mappedHandler != resolvedHandler) { - throw new IllegalStateException("Cannot map handler [" + handler + "] to key [" + lookupKey + - "]: There's already handler [" + mappedHandler + "] mapped."); - } - } - else { - if (predicate != null) { - // Add the handler to the predicate map. - Map predicateMap = - (Map) mappedHandler; - if (predicateMap == null) { - predicateMap = new LinkedHashMap(); - this.handlerMap.put(lookupKey, predicateMap); - } - predicateMap.put(predicate, resolvedHandler); - } - else { - // Add the single handler to the map. - this.handlerMap.put(lookupKey, resolvedHandler); - } - if (logger.isDebugEnabled()) { - logger.debug("Mapped key [" + lookupKey + "] onto handler [" + resolvedHandler + "]"); - } - } - } - - - /** - * Predicate interface for determining a match with a given request. - */ - protected interface PortletRequestMappingPredicate extends Comparable { - - /** - * Determine whether the given request matches this predicate. - * @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; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/HandlerInterceptorAdapter.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/HandlerInterceptorAdapter.java deleted file mode 100644 index 7b052cca12..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/HandlerInterceptorAdapter.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2002-2012 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.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.EventRequest; -import javax.portlet.EventResponse; -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.web.portlet.HandlerInterceptor; -import org.springframework.web.portlet.ModelAndView; - -/** - * Abstract adapter class for the {@link HandlerInterceptor} interface, - * for simplified implementation of pre-only/post-only interceptors. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - */ -public abstract class HandlerInterceptorAdapter implements HandlerInterceptor { - - /** - * This implementation delegates to {@link #preHandle}. - */ - @Override - public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) - throws Exception { - - return preHandle(request, response, handler); - } - - /** - * This implementation delegates to {@link #afterCompletion}. - */ - @Override - public void afterActionCompletion( - ActionRequest request, ActionResponse response, Object handler, Exception ex) - throws Exception { - - afterCompletion(request, response, handler, ex); - } - - - /** - * This implementation delegates to {@link #preHandle}. - */ - @Override - public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) - throws Exception { - - return preHandle(request, response, handler); - } - - /** - * This implementation is empty. - */ - @Override - public void postHandleRender( - RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView) - throws Exception { - } - - /** - * This implementation delegates to {@link #afterCompletion}. - */ - @Override - public void afterRenderCompletion( - RenderRequest request, RenderResponse response, Object handler, Exception ex) - throws Exception { - - afterCompletion(request, response, handler, ex); - } - - - /** - * This implementation delegates to {@link #preHandle}. - */ - @Override - public boolean preHandleResource(ResourceRequest request, ResourceResponse response, Object handler) - throws Exception { - - return preHandle(request, response, handler); - } - - /** - * This implementation is empty. - */ - @Override - public void postHandleResource( - ResourceRequest request, ResourceResponse response, Object handler, ModelAndView modelAndView) - throws Exception { - } - - /** - * This implementation delegates to {@link #afterCompletion}. - */ - @Override - public void afterResourceCompletion( - ResourceRequest request, ResourceResponse response, Object handler, Exception ex) - throws Exception { - - afterCompletion(request, response, handler, ex); - } - - - /** - * This implementation delegates to {@link #preHandle}. - */ - @Override - public boolean preHandleEvent(EventRequest request, EventResponse response, Object handler) - throws Exception { - - return preHandle(request, response, handler); - } - - /** - * This implementation delegates to {@link #afterCompletion}. - */ - @Override - 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. - *

        This implementation always returns {@code true}. - */ - protected boolean preHandle(PortletRequest request, PortletResponse response, Object handler) - throws Exception { - - return true; - } - - /** - * Default callback that all "after*" methods delegate to. - *

        This implementation is empty. - */ - protected void afterCompletion( - PortletRequest request, PortletResponse response, Object handler, Exception ex) - throws Exception { - - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java deleted file mode 100644 index ae24f49208..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterHandlerMapping.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2002-2012 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 java.util.Map; -import javax.portlet.PortletRequest; - -import org.springframework.beans.BeansException; -import org.springframework.util.Assert; - -/** - * Implementation of the {@link org.springframework.web.portlet.HandlerMapping} - * to map from a request parameter to request handler beans. - * - *

        The default name of the parameter is "action", but can be changed using - * {@link #setParameterName setParameterName()}. - * - *

        The bean configuration for this mapping will look somthing like this: - * - *

        - * <bean id="parameterHandlerMapping" class="org.springframework.web.portlet.handler.ParameterHandlerMapping">
        - *   <property name="parameterMap">
        - *     <map>
        - * 	     <entry key="add"><ref bean="addItemHandler"/></entry>
        - *       <entry key="edit"><ref bean="editItemHandler"/></entry>
        - *       <entry key="delete"><ref bean="deleteItemHandler"/></entry>
        - *     </map>
        - *   </property>
        - * </bean>
        - * - * Thanks to Rainer Schmitz for suggesting this mapping strategy! - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see ParameterMappingInterceptor - */ -public class ParameterHandlerMapping extends AbstractMapBasedHandlerMapping { - - /** - * Default request parameter name to use for mapping to handlers: "action". - */ - public final static String DEFAULT_PARAMETER_NAME = "action"; - - - private String parameterName = DEFAULT_PARAMETER_NAME; - - private Map parameterMap; - - - /** - * Set the name of the parameter used for mapping to handlers. - *

        Default is "action". - */ - public void setParameterName(String parameterName) { - Assert.hasText(parameterName, "'parameterName' must not be empty"); - this.parameterName = parameterName; - } - - /** - * Set a Map with parameters as keys and handler beans or bean names as values. - * Convenient for population with bean references. - * @param parameterMap map with parameters as keys and beans as values - */ - public void setParameterMap(Map parameterMap) { - this.parameterMap = parameterMap; - } - - - /** - * Calls the {@code registerHandlers} method in addition - * to the superclass's initialization. - * @see #registerHandlers - */ - @Override - public void initApplicationContext() throws BeansException { - super.initApplicationContext(); - registerHandlers(this.parameterMap); - } - - /** - * Uses the value of the specified parameter as lookup key. - * @see #setParameterName - */ - @Override - protected String getLookupKey(PortletRequest request) throws Exception { - return request.getParameter(this.parameterName); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterMappingInterceptor.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterMappingInterceptor.java deleted file mode 100644 index dc7166db01..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/ParameterMappingInterceptor.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2002-2012 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.ActionRequest; -import javax.portlet.ActionResponse; - -/** - * Interceptor to forward a request parameter from the {@code ActionRequest} to the - * {@code RenderRequest}. - * - *

        This can be useful when using {@link ParameterHandlerMapping ParameterHandlerMapping} - * or {@link PortletModeParameterHandlerMapping PortletModeParameterHandlerMapping}. - * It will ensure that the parameter that was used to map the {@code ActionRequest} - * to a handler will be forwarded to the {@code RenderRequest} so that it will also be - * mapped the same way. - * - *

        When using this Interceptor, you can still change the value of the mapping parameter - * in your handler in order to change where the render request will get mapped. - * - *

        Be aware that this Interceptor does call {@code ActionResponse.setRenderParameter}, - * which means that you will not be able to call {@code ActionResponse.sendRedirect} in - * your handler. If you may need to issue a redirect, then you should avoid this Interceptor - * and either write a different one that does this in a different way, or manually forward - * the parameter from within your handler(s). - * - *

        Thanks to Rainer Schmitz for suggesting this mapping strategy! - * - * @author John A. Lewis - * @since 2.0 - * @see ParameterHandlerMapping - * @see PortletModeParameterHandlerMapping - */ -public class ParameterMappingInterceptor extends HandlerInterceptorAdapter { - - /** Request parameter name to use for mapping to handlers */ - public final static String DEFAULT_PARAMETER_NAME = "action"; - - private String parameterName = DEFAULT_PARAMETER_NAME; - - - /** - * Set the name of the parameter used for mapping. - */ - public void setParameterName(String parameterName) { - this.parameterName = (parameterName != null ? parameterName : DEFAULT_PARAMETER_NAME); - } - - - /** - * If request is an {@link javax.portlet.ActionRequest ActionRequest}, - * get handler mapping parameter and add it to the ActionResponse. - */ - @Override - public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) { - String mappingParameter = request.getParameter(this.parameterName); - if (mappingParameter != null) { - response.setRenderParameter(parameterName, mappingParameter); - } - return true; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletContentGenerator.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletContentGenerator.java deleted file mode 100644 index 4ac0d32e41..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletContentGenerator.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2002-2012 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.MimeResponse; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; - -import org.springframework.web.portlet.context.PortletApplicationObjectSupport; - -/** - * Convenient superclass for any kind of web content generator, - * like {@link org.springframework.web.portlet.mvc.AbstractController}. - * Can also be used for custom handlers that have their own - * {@link org.springframework.web.portlet.HandlerAdapter}. - * - *

        Supports portlet cache control options. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see #setCacheSeconds - * @see #setRequireSession - */ -public abstract class PortletContentGenerator extends PortletApplicationObjectSupport { - - private boolean requireSession = false; - - private int cacheSeconds = -1; - - - /** - * Set whether a session should be required to handle requests. - */ - public final void setRequireSession(boolean requireSession) { - this.requireSession = requireSession; - } - - /** - * Return whether a session is required to handle requests. - */ - public final boolean isRequireSession() { - return this.requireSession; - } - - /** - * Cache content for the given number of seconds. Default is -1, - * indicating no override of portlet content caching. - *

        Only if this is set to 0 (no cache) or a positive value (cache for - * this many seconds) will this class override the portlet settings. - *

        The cache setting can be overwritten by subclasses, before content is generated. - */ - public final void setCacheSeconds(int seconds) { - this.cacheSeconds = seconds; - } - - /** - * Return the number of seconds that content is cached. - */ - public final int getCacheSeconds() { - return this.cacheSeconds; - } - - - /** - * Check and prepare the given request and response according to the settings - * of this generator. Checks for a required session, and applies the number of - * cache seconds configured for this generator (if it is a render request/response). - * @param request current portlet request - * @param response current portlet response - * @throws PortletException if the request cannot be handled because a check failed - */ - protected final void check(PortletRequest request, PortletResponse response) throws PortletException { - if (this.requireSession) { - if (request.getPortletSession(false) == null) { - throw new PortletSessionRequiredException("Pre-existing session required but none found"); - } - } - } - - /** - * Check and prepare the given request and response according to the settings - * of this generator. Checks for a required session, and applies the number of - * cache seconds configured for this generator (if it is a render request/response). - * @param request current portlet request - * @param response current portlet response - * @throws PortletException if the request cannot be handled because a check failed - */ - protected final void checkAndPrepare(PortletRequest request, MimeResponse response) - throws PortletException { - - checkAndPrepare(request, response, this.cacheSeconds); - } - - /** - * Check and prepare the given request and response according to the settings - * of this generator. Checks for a required session, and applies the given - * number of cache seconds (if it is a render request/response). - * @param request current portlet request - * @param response current portlet response - * @param cacheSeconds positive number of seconds into the future that the - * 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(PortletRequest request, MimeResponse response, int cacheSeconds) - throws PortletException { - - check(request, response); - applyCacheSeconds(response, cacheSeconds); - } - - /** - * Prevent the render response from being cached. - */ - protected final void preventCaching(MimeResponse response) { - cacheForSeconds(response, 0); - } - - /** - * Set portlet response to allow caching for the given number of seconds. - * @param response current portlet render response - * @param seconds number of seconds into the future that the response - * should be cacheable for - */ - protected final void cacheForSeconds(MimeResponse response, int seconds) { - response.setProperty(MimeResponse.EXPIRATION_CACHE, Integer.toString(seconds)); - } - - /** - * Apply the given cache seconds to the render response - * @param response current portlet render response - * @param seconds positive number of seconds into the future that the - * response should be cacheable for, 0 to prevent caching - */ - protected final void applyCacheSeconds(MimeResponse response, int seconds) { - if (seconds > 0) { - cacheForSeconds(response, seconds); - } - else if (seconds == 0) { - preventCaching(response); - } - // Leave caching to the portlet configuration otherwise. - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java deleted file mode 100644 index c4691860d8..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeHandlerMapping.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2002-2012 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 java.util.HashMap; -import java.util.Map; -import java.util.Properties; -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; - -import org.springframework.beans.BeansException; -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Implementation of the {@link org.springframework.web.portlet.HandlerMapping} - * interface to map from the current PortletMode to request handler beans. - * - *

        The bean configuration for this mapping will look something like this: - *

        - * 	<bean id="portletModeHandlerMapping" class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">
        - * 		<property name="portletModeMap">
        - * 			<map>
        - * 				<entry key="view"><ref bean="viewHandler"/></entry>
        - * 				<entry key="edit"><ref bean="editHandler"/></entry>
        - * 				<entry key="help"><ref bean="helpHandler"/></entry>
        - * 			</map>
        - * 		</property>
        - * 	</bean>
        - * 
        - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @since 2.0 - */ -public class PortletModeHandlerMapping extends AbstractMapBasedHandlerMapping { - - private final Map portletModeMap = new HashMap(); - - - /** - * Set PortletMode to handler bean name mappings from a Properties object. - * @param mappings properties with PortletMode names as keys and bean names as values - */ - public void setMappings(Properties mappings) { - CollectionUtils.mergePropertiesIntoMap(mappings, this.portletModeMap); - } - - /** - * Set a Map with PortletModes as keys and handler beans as values. - * Convenient for population with bean references. - * @param portletModeMap map with PortletMode names as keys and beans or bean names as values - */ - public void setPortletModeMap(Map portletModeMap) { - this.portletModeMap.putAll(portletModeMap); - } - - - /** - * Calls the {@code registerHandlers} method in addition - * to the superclass's initialization. - * @see #registerHandlers - */ - @Override - public void initApplicationContext() throws BeansException { - super.initApplicationContext(); - registerHandlersByMode(this.portletModeMap); - } - - /** - * Register all handlers specified in the Portlet mode map for the corresponding modes. - * @param portletModeMap Map with mode names as keys and handler beans or bean names as values - */ - protected void registerHandlersByMode(Map portletModeMap) { - Assert.notNull(portletModeMap, "'portletModeMap' must not be null"); - for (Map.Entry entry : portletModeMap.entrySet()) { - registerHandler(new PortletMode(entry.getKey()), entry.getValue()); - } - } - - - /** - * Uses the current PortletMode as lookup key. - */ - @Override - protected PortletMode getLookupKey(PortletRequest request) throws Exception { - return request.getPortletMode(); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java deleted file mode 100644 index e53dcb0b6d..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMapping.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright 2002-2012 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 java.util.HashSet; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; - -import org.springframework.beans.BeansException; -import org.springframework.util.Assert; - -/** - * Implementation of the {@link org.springframework.web.portlet.HandlerMapping} - * interface to map from the current PortletMode and a request parameter to - * request handler beans. The mapping consists of two levels: first the - * PortletMode and then the parameter value. In order to be mapped, - * both elements must match the mapping definition. - * - *

        This is a combination of the methods used in {@link PortletModeHandlerMapping PortletModeHandlerMapping} - * and {@link ParameterHandlerMapping ParameterHandlerMapping}. Unlike - * those two classes, this mapping cannot be initialized with properties since it - * requires a two-level map. - * - *

        The default name of the parameter is "action", but can be changed using - * {@link #setParameterName setParameterName()}. - * - *

        By default, the same parameter value may not be used in two different portlet - * modes. This is so that if the portal itself changes the portlet mode, the request - * will no longer be valid in the mapping. This behavior can be changed with - * {@link #setAllowDuplicateParameters setAllowDupParameters()}. - * - *

        The bean configuration for this mapping will look somthing like this: - * - *

        - * <bean id="portletModeParameterHandlerMapping" class="org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping">
        - *   <property name="portletModeParameterMap">
        - *     <map>
        - *       <entry key="view"> <!-- portlet mode: view -->
        - *         <map>
        - *           <entry key="add"><ref bean="addItemHandler"/></entry>
        - *           <entry key="edit"><ref bean="editItemHandler"/></entry>
        - *           <entry key="delete"><ref bean="deleteItemHandler"/></entry>
        - *         </map>
        - *       </entry>
        - *       <entry key="edit"> <!-- portlet mode: edit -->
        - *         <map>
        - *           <entry key="prefs"><ref bean="preferencesHandler"/></entry>
        - *           <entry key="resetPrefs"><ref bean="resetPreferencesHandler"/></entry>
        - *         </map>
        - *       </entry>
        - *     </map>
        - *   </property>
        - * </bean>
        - * - *

        This mapping can be chained ahead of a {@link PortletModeHandlerMapping PortletModeHandlerMapping}, - * which can then provide defaults for each mode and an overall default as well. - * - *

        Thanks to Rainer Schmitz and Yujin Kim for suggesting this mapping strategy! - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see ParameterMappingInterceptor - */ -public class PortletModeParameterHandlerMapping extends AbstractMapBasedHandlerMapping { - - /** - * Default request parameter name to use for mapping to handlers: "action". - */ - public final static String DEFAULT_PARAMETER_NAME = "action"; - - - private String parameterName = DEFAULT_PARAMETER_NAME; - - private Map> portletModeParameterMap; - - private boolean allowDuplicateParameters = false; - - private final Set parametersUsed = new HashSet(); - - - /** - * Set the name of the parameter used for mapping to handlers. - *

        Default is "action". - */ - public void setParameterName(String parameterName) { - Assert.hasText(parameterName, "'parameterName' must not be empty"); - this.parameterName = parameterName; - } - - /** - * Set a Map with portlet mode names as keys and another Map as values. - * The sub-map has parameter names as keys and handler bean or bean names as values. - *

        Convenient for population with bean references. - * @param portletModeParameterMap two-level map of portlet modes and parameters to handler beans - */ - public void setPortletModeParameterMap(Map> portletModeParameterMap) { - this.portletModeParameterMap = portletModeParameterMap; - } - - /** - * Set whether to allow duplicate parameter values across different portlet modes. - * Default is "false". - *

        Doing this is dangerous because the portlet mode can be changed by the - * portal itself and the only way to see that is a rerender of the portlet. - * If the same parameter value is legal in multiple modes, then a change in - * mode could result in a matched mapping that is not intended and the user - * could end up in a strange place in the application. - */ - public void setAllowDuplicateParameters(boolean allowDuplicateParameters) { - this.allowDuplicateParameters = allowDuplicateParameters; - } - - - /** - * Calls the {@code registerHandlers} method in addition - * to the superclass's initialization. - * @see #registerHandlers - */ - @Override - public void initApplicationContext() throws BeansException { - super.initApplicationContext(); - registerHandlersByModeAndParameter(this.portletModeParameterMap); - } - - /** - * Register all handlers specified in the Portlet mode map for the corresponding modes. - * @param portletModeParameterMap Map with mode names as keys and parameter Maps as values - */ - protected void registerHandlersByModeAndParameter(Map> portletModeParameterMap) { - Assert.notNull(portletModeParameterMap, "'portletModeParameterMap' must not be null"); - for (Map.Entry> entry : portletModeParameterMap.entrySet()) { - PortletMode mode = new PortletMode(entry.getKey()); - registerHandler(mode, entry.getValue()); - } - } - - /** - * Register all handlers specified in the given parameter map. - * @param parameterMap Map with parameter names as keys and handler beans or bean names as values - */ - protected void registerHandler(PortletMode mode, Map parameterMap) { - for (Map.Entry entry : parameterMap.entrySet()) { - registerHandler(mode, entry.getKey(), entry.getValue()); - } - } - - /** - * Register the given handler instance for the given PortletMode and parameter value, - * under an appropriate lookup key. - * @param mode the PortletMode for which this mapping is valid - * @param parameter the parameter value to which this handler is mapped - * @param handler the handler instance bean - * @throws BeansException if the handler couldn't be registered - * @throws IllegalStateException if there is a conflicting handler registered - * @see #registerHandler(Object, Object) - */ - protected void registerHandler(PortletMode mode, String parameter, Object handler) - throws BeansException, IllegalStateException { - - // Check for duplicate parameter values across all portlet modes. - if (!this.allowDuplicateParameters && this.parametersUsed.contains(parameter)) { - throw new IllegalStateException( - "Duplicate entries for parameter [" + parameter + "] in different Portlet modes"); - } - this.parametersUsed.add(parameter); - - registerHandler(new PortletModeParameterLookupKey(mode, parameter), handler); - } - - /** - * Returns a lookup key that combines the current PortletMode and the current - * value of the specified parameter. - * @see javax.portlet.PortletRequest#getPortletMode() - * @see #setParameterName - */ - @Override - protected PortletModeParameterLookupKey getLookupKey(PortletRequest request) throws Exception { - PortletMode mode = request.getPortletMode(); - String parameter = request.getParameter(this.parameterName); - return new PortletModeParameterLookupKey(mode, parameter); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java deleted file mode 100644 index dd47407172..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletModeParameterLookupKey.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * 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.PortletMode; - -import org.springframework.util.ObjectUtils; - -/** - * Internal class used as lookup key, combining PortletMode and parameter value. - * - * @author Juergen Hoeller - */ -class PortletModeParameterLookupKey { - - private final PortletMode mode; - - private final String parameter; - - - public PortletModeParameterLookupKey(PortletMode portletMode, String parameter) { - this.mode = portletMode; - this.parameter = parameter; - } - - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!(other instanceof PortletModeParameterLookupKey)) { - return false; - } - PortletModeParameterLookupKey otherKey = (PortletModeParameterLookupKey) other; - return (this.mode.equals(otherKey.mode) && - ObjectUtils.nullSafeEquals(this.parameter, otherKey.parameter)); - } - - @Override - public int hashCode() { - return (this.mode.hashCode() * 29 + ObjectUtils.nullSafeHashCode(this.parameter)); - } - - @Override - public String toString() { - return "Portlet mode '" + this.mode + "', parameter '" + this.parameter + "'"; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletRequestMethodNotSupportedException.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletRequestMethodNotSupportedException.java deleted file mode 100644 index 7037f83126..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletRequestMethodNotSupportedException.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2002-2012 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 - */ -@SuppressWarnings("serial") -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 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; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletSessionRequiredException.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletSessionRequiredException.java deleted file mode 100644 index 0911834e61..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/PortletSessionRequiredException.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2002-2012 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; - -/** - * Exception thrown when a portlet content generator requires a pre-existing session. - * - * @author John A. Lewis - * @since 2.0 - * @see org.springframework.web.portlet.handler.PortletContentGenerator - */ -@SuppressWarnings("serial") -public class PortletSessionRequiredException extends PortletException { - - /** - * Create a new PortletSessionRequiredException. - * @param msg the detail message - */ - public PortletSessionRequiredException(String msg) { - super(msg); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolver.java deleted file mode 100644 index 2704be2e0c..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolver.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright 2002-2015 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 java.util.Enumeration; -import java.util.Properties; -import javax.portlet.MimeResponse; -import javax.portlet.PortletRequest; - -import org.springframework.web.portlet.ModelAndView; - -/** - * {@link org.springframework.web.portlet.HandlerExceptionResolver} implementation - * that allows for mapping exception class names to view names, either for a - * set of given handlers or for all handlers in the DispatcherPortlet. - * - *

        Error views are analogous to error page JSPs, but can be used with any - * kind of exception including any checked one, with fine-granular mappings for - * specific handlers. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @author Arjen Poutsma - * @since 2.0 - */ -public class SimpleMappingExceptionResolver extends AbstractHandlerExceptionResolver { - - /** - * The default name of the exception attribute: "exception". - */ - public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception"; - - private Properties exceptionMappings; - - private String defaultErrorView; - - private String exceptionAttribute = DEFAULT_EXCEPTION_ATTRIBUTE; - - /** - * Set the mappings between exception class names and error view names. - * The exception class name can be a substring, with no wildcard support - * at present. A value of "PortletException" would match - * {@code javax.portet.PortletException} and subclasses, for example. - *

        NB: Consider carefully how specific the pattern is, and whether - * to include package information (which isn't mandatory). For example, - * "Exception" will match nearly anything, and will probably hide other rules. - * "java.lang.Exception" would be correct if "Exception" was meant to define - * a rule for all checked exceptions. With more unusual exception names such - * as "BaseBusinessException" there's no need to use a FQN. - *

        Follows the same matching algorithm as RuleBasedTransactionAttribute - * and RollbackRuleAttribute. - * @param mappings exception patterns (can also be fully qualified class names) - * as keys, and error view names as values - * @see org.springframework.transaction.interceptor.RuleBasedTransactionAttribute - * @see org.springframework.transaction.interceptor.RollbackRuleAttribute - */ - public void setExceptionMappings(Properties mappings) { - this.exceptionMappings = mappings; - } - - /** - * Set the name of the default error view. - * This view will be returned if no specific mapping was found. - *

        Default is none. - */ - public void setDefaultErrorView(String defaultErrorView) { - this.defaultErrorView = defaultErrorView; - } - - /** - * Set the name of the model attribute as which the exception should - * be exposed. Default is "exception". - * @see #DEFAULT_EXCEPTION_ATTRIBUTE - */ - public void setExceptionAttribute(String exceptionAttribute) { - this.exceptionAttribute = exceptionAttribute; - } - - /** - * Actually 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 - */ - @Override - protected ModelAndView doResolveException( - PortletRequest request, MimeResponse response, Object handler, Exception ex) { - - // Log exception, both at debug log level and at warn level, if desired. - if (logger.isDebugEnabled()) { - logger.debug("Resolving exception from handler [" + handler + "]: " + ex); - } - logException(ex, request); - - // Expose ModelAndView for chosen error view. - String viewName = determineViewName(ex, request); - if (viewName != null) { - return getModelAndView(viewName, ex, request); - } - else { - return null; - } - } - - /** - * Determine the view name for the given exception, searching the - * {@link #setExceptionMappings "exceptionMappings"}, using the - * {@link #setDefaultErrorView "defaultErrorView"} as fallback. - * @param ex the exception that got thrown during handler execution - * @param request current portlet request (useful for obtaining metadata) - * @return the resolved view name, or {@code null} if none found - */ - protected String determineViewName(Exception ex, PortletRequest request) { - String viewName = null; - // Check for specific exception mappings. - if (this.exceptionMappings != null) { - viewName = findMatchingViewName(this.exceptionMappings, ex); - } - // Return default error view else, if defined. - if (viewName == null && this.defaultErrorView != null) { - if (logger.isDebugEnabled()) { - logger.debug("Resolving to default view '" + this.defaultErrorView + - "' for exception of type [" + ex.getClass().getName() + "]"); - } - viewName = this.defaultErrorView; - } - return viewName; - } - - /** - * Find a matching view name in the given exception mappings - * @param exceptionMappings mappings between exception class names and error view names - * @param ex the exception that got thrown during handler execution - * @return the view name, or {@code null} if none found - * @see #setExceptionMappings - */ - protected String findMatchingViewName(Properties exceptionMappings, Exception ex) { - String viewName = null; - String dominantMapping = null; - int deepest = Integer.MAX_VALUE; - for (Enumeration names = exceptionMappings.propertyNames(); names.hasMoreElements();) { - String exceptionMapping = (String) names.nextElement(); - int depth = getDepth(exceptionMapping, ex); - if (depth >= 0 && (depth < deepest || (depth == deepest && - dominantMapping != null && exceptionMapping.length() > dominantMapping.length()))) { - deepest = depth; - dominantMapping = exceptionMapping; - viewName = exceptionMappings.getProperty(exceptionMapping); - } - } - if (viewName != null && logger.isDebugEnabled()) { - logger.debug("Resolving to view '" + viewName + "' for exception of type [" + ex.getClass().getName() + - "], based on exception mapping [" + dominantMapping + "]"); - } - return viewName; - } - - /** - * Return the depth to the superclass matching. - *

        0 means ex matches exactly. Returns -1 if there's no match. - * Otherwise, returns depth. Lowest depth wins. - *

        Follows the same algorithm as - * {@link org.springframework.transaction.interceptor.RollbackRuleAttribute}. - */ - protected int getDepth(String exceptionMapping, Exception ex) { - return getDepth(exceptionMapping, ex.getClass(), 0); - } - - private int getDepth(String exceptionMapping, Class exceptionClass, int depth) { - if (exceptionClass.getName().contains(exceptionMapping)) { - // Found it! - return depth; - } - // If we've gone as far as we can go and haven't found it... - if (exceptionClass == Throwable.class) { - return -1; - } - return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1); - } - - - /** - * Return a ModelAndView for the given request, view name and exception. - * Default implementation delegates to {@code getModelAndView(viewName, ex)}. - * @param viewName the name of the error view - * @param ex the exception that got thrown during handler execution - * @param request current portlet request (useful for obtaining metadata) - * @return the ModelAndView instance - * @see #getModelAndView(String, Exception) - */ - protected ModelAndView getModelAndView(String viewName, Exception ex, PortletRequest request) { - return getModelAndView(viewName, ex); - } - - /** - * Return a ModelAndView for the given view name and exception. - * Default implementation adds the specified exception attribute. - * Can be overridden in subclasses. - * @param viewName the name of the error view - * @param ex the exception that got thrown during handler execution - * @return the ModelAndView instance - * @see #setExceptionAttribute - */ - protected ModelAndView getModelAndView(String viewName, Exception ex) { - ModelAndView mv = new ModelAndView(viewName); - if (this.exceptionAttribute != null) { - if (logger.isDebugEnabled()) { - logger.debug("Exposing Exception as model attribute '" + this.exceptionAttribute + "'"); - } - mv.addObject(this.exceptionAttribute, ex); - } - return mv; - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletHandlerAdapter.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletHandlerAdapter.java deleted file mode 100644 index f7a884dad9..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletHandlerAdapter.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2002-2012 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.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.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; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Adapter to use the Portlet interface with the generic DispatcherPortlet. - * Calls the Portlet's {@code render} and {@code processAction} - * methods to handle a request. - * - *

        This adapter is not activated by default; it needs to be defined as a - * bean in the DispatcherPortlet context. It will automatically apply to - * mapped handler beans that implement the Portlet interface then. - * - *

        Note that Portlet instances defined as bean will not receive initialization - * and destruction callbacks, unless a special post-processor such as - * SimplePortletPostProcessor is defined in the DispatcherPortlet context. - * - *

        Alternatively, consider wrapping a Portlet with Spring's - * PortletWrappingController. This is particularly appropriate for - * existing Portlet classes, allowing to specify Portlet initialization - * parameters, etc. - * - * @author John A. Lewis - * @since 2.0 - * @see javax.portlet.Portlet - * @see SimplePortletPostProcessor - * @see org.springframework.web.portlet.mvc.PortletWrappingController - */ -public class SimplePortletHandlerAdapter implements HandlerAdapter, PortletContextAware { - - private PortletContext portletContext; - - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - - @Override - public boolean supports(Object handler) { - return (handler instanceof Portlet); - } - - @Override - public void handleAction(ActionRequest request, ActionResponse response, Object handler) - throws Exception { - - ((Portlet) handler).processAction(request, response); - } - - @Override - public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object handler) - throws Exception { - - ((Portlet) handler).render(request, response); - return null; - } - - @Override - public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler) - throws Exception { - - if (handler instanceof ResourceServingPortlet) { - ((ResourceServingPortlet) handler).serveResource(request, response); - } - else { - // roughly equivalent to Portlet 2.0 GenericPortlet - PortletUtils.serveResource(request, response, this.portletContext); - } - return null; - } - - @Override - 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); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletPostProcessor.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletPostProcessor.java deleted file mode 100644 index ba3939489d..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/SimplePortletPostProcessor.java +++ /dev/null @@ -1,216 +0,0 @@ -/* - * Copyright 2002-2016 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 java.util.Collections; -import java.util.Enumeration; -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; -import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; -import org.springframework.web.portlet.context.PortletConfigAware; -import org.springframework.web.portlet.context.PortletContextAware; - -/** - * {@link org.springframework.beans.factory.config.BeanPostProcessor} - * that applies initialization and destruction callbacks to beans that - * implement the {@link javax.portlet.Portlet} interface. - * - *

        After initialization of the bean instance, the Portlet {@code init} - * method will be called with a PortletConfig that contains the bean name - * of the Portlet and the PortletContext that it is running in. - * - *

        Before destruction of the bean instance, the Portlet {@code destroy} - * will be called. - * - *

        Note that this post-processor does not support Portlet initialization - * parameters. Bean instances that implement the Portlet interface are - * supposed to be configured like any other Spring bean, that is, through - * constructor arguments or bean properties. - * - *

        For reuse of a Portlet implementation in a plain Portlet container - * and as a bean in a Spring context, consider deriving from Spring's - * {@link org.springframework.web.portlet.GenericPortletBean} base class that - * applies Portlet initialization parameters as bean properties, supporting - * both the standard Portlet and the Spring bean initialization style. - * - *

        Alternatively, consider wrapping a Portlet with Spring's - * {@link org.springframework.web.portlet.mvc.PortletWrappingController}. - * This is particularly appropriate for existing Portlet classes, - * allowing to specify Portlet initialization parameters etc. - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - * @see javax.portlet.Portlet - * @see javax.portlet.PortletConfig - * @see SimplePortletHandlerAdapter - * @see org.springframework.web.portlet.GenericPortletBean - * @see org.springframework.web.portlet.mvc.PortletWrappingController - */ -public class SimplePortletPostProcessor - implements DestructionAwareBeanPostProcessor, PortletContextAware, PortletConfigAware { - - private boolean useSharedPortletConfig = true; - - private PortletContext portletContext; - - private PortletConfig portletConfig; - - - /** - * Set whether to use the shared PortletConfig object passed in - * through {@code setPortletConfig}, if available. - *

        Default is "true". Turn this setting to "false" to pass in - * a mock PortletConfig object with the bean name as portlet name, - * holding the current PortletContext. - * @see #setPortletConfig - */ - public void setUseSharedPortletConfig(boolean useSharedPortletConfig) { - this.useSharedPortletConfig = useSharedPortletConfig; - } - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - @Override - public void setPortletConfig(PortletConfig portletConfig) { - this.portletConfig = portletConfig; - } - - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof Portlet) { - PortletConfig config = this.portletConfig; - if (config == null || !this.useSharedPortletConfig) { - config = new DelegatingPortletConfig(beanName, this.portletContext, this.portletConfig); - } - try { - ((Portlet) bean).init(config); - } - catch (PortletException ex) { - throw new BeanInitializationException("Portlet.init threw exception", ex); - } - } - return bean; - } - - @Override - public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { - if (bean instanceof Portlet) { - ((Portlet) bean).destroy(); - } - } - - @Override - public boolean requiresDestruction(Object bean) { - return (bean instanceof Portlet); - } - - - /** - * Internal implementation of the PortletConfig interface, to be passed - * to the wrapped servlet. - */ - private static class DelegatingPortletConfig implements PortletConfig { - - private final String portletName; - - private final PortletContext portletContext; - - private final PortletConfig portletConfig; - - public DelegatingPortletConfig(String portletName, PortletContext portletContext, PortletConfig portletConfig) { - this.portletName = portletName; - this.portletContext = portletContext; - this.portletConfig = portletConfig; - } - - @Override - public String getPortletName() { - return this.portletName; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - @Override - public String getInitParameter(String paramName) { - return null; - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public ResourceBundle getResourceBundle(Locale locale) { - return (this.portletConfig != null ? this.portletConfig.getResourceBundle(locale) : null); - } - - @Override - public Enumeration getPublicRenderParameterNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public String getDefaultNamespace() { - return XMLConstants.NULL_NS_URI; - } - - @Override - public Enumeration getPublishingEventQNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public Enumeration getProcessingEventQNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public Enumeration getSupportedLocales() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public Map getContainerRuntimeOptions() { - return (this.portletConfig != null ? this.portletConfig.getContainerRuntimeOptions() : null); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptor.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptor.java deleted file mode 100644 index 4e192c6529..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptor.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2002-2014 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 java.io.IOException; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSecurityException; - -/** - * Interceptor that checks the authorization of the current user via the - * user's roles, as evaluated by PortletRequest's isUserInRole method. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see javax.portlet.PortletRequest#isUserInRole - */ -public class UserRoleAuthorizationInterceptor extends HandlerInterceptorAdapter { - - private String[] authorizedRoles; - - - /** - * Set the roles that this interceptor should treat as authorized. - * @param authorizedRoles array of role names - */ - public final void setAuthorizedRoles(String... authorizedRoles) { - this.authorizedRoles = authorizedRoles; - } - - - @Override - public final boolean preHandle(PortletRequest request, PortletResponse response, Object handler) - throws PortletException, IOException { - - if (this.authorizedRoles != null) { - for (String role : this.authorizedRoles) { - if (request.isUserInRole(role)) { - return true; - } - } - } - handleNotAuthorized(request, response, handler); - return false; - } - - /** - * Handle a request that is not authorized according to this interceptor. - * Default implementation throws a new PortletSecurityException. - *

        This method can be overridden to write a custom message, forward or - * redirect to some error page or login page, or throw a PortletException. - * @param request current portlet request - * @param response current portlet response - * @param handler chosen handler to execute, for type and/or instance evaluation - * @throws javax.portlet.PortletException if there is an internal error - * @throws java.io.IOException in case of an I/O error when writing the response - */ - protected void handleNotAuthorized(PortletRequest request, PortletResponse response, Object handler) - throws PortletException, IOException { - - throw new PortletSecurityException("Request not authorized"); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/WebRequestHandlerInterceptorAdapter.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/WebRequestHandlerInterceptorAdapter.java deleted file mode 100644 index b871ed7059..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/WebRequestHandlerInterceptorAdapter.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2002-2012 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.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; -import org.springframework.web.portlet.HandlerInterceptor; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.context.PortletWebRequest; - -/** - * Adapter that implements the Portlet HandlerInterceptor interface - * and wraps an underlying WebRequestInterceptor. - * - *

        NOTE: The WebRequestInterceptor is by default only applied to the Portlet - * render phase, which is dealing with preparing and rendering a Portlet view. - * The Portlet action phase will only be intercepted with WebRequestInterceptor calls - * if the {@code renderPhaseOnly} flag is explicitly set to {@code false}. - * In general, it is recommended to use the Portlet-specific HandlerInterceptor - * mechanism for differentiating between action and render interception. - * - * @author Juergen Hoeller - * @since 2.0 - * @see org.springframework.web.context.request.WebRequestInterceptor - * @see org.springframework.web.portlet.HandlerInterceptor - */ -public class WebRequestHandlerInterceptorAdapter implements HandlerInterceptor { - - private final WebRequestInterceptor requestInterceptor; - - private final boolean renderPhaseOnly; - - - /** - * Create a new WebRequestHandlerInterceptorAdapter for the given WebRequestInterceptor, - * applying to the render phase only. - * @param requestInterceptor the WebRequestInterceptor to wrap - */ - public WebRequestHandlerInterceptorAdapter(WebRequestInterceptor requestInterceptor) { - this(requestInterceptor, true); - } - - /** - * Create a new WebRequestHandlerInterceptorAdapter for the given WebRequestInterceptor. - * @param requestInterceptor the WebRequestInterceptor to wrap - * @param renderPhaseOnly whether to apply to the render phase only ({@code true}) - * or to the action phase as well ({@code false}) - */ - public WebRequestHandlerInterceptorAdapter(WebRequestInterceptor requestInterceptor, boolean renderPhaseOnly) { - Assert.notNull(requestInterceptor, "WebRequestInterceptor must not be null"); - this.requestInterceptor = requestInterceptor; - this.renderPhaseOnly = renderPhaseOnly; - } - - - @Override - public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) throws Exception { - if (!this.renderPhaseOnly) { - this.requestInterceptor.preHandle(new PortletWebRequest(request)); - } - return true; - } - - @Override - public void afterActionCompletion( - ActionRequest request, ActionResponse response, Object handler, Exception ex) throws Exception { - - if (!this.renderPhaseOnly) { - this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex); - } - } - - @Override - public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception { - this.requestInterceptor.preHandle(new PortletWebRequest(request)); - return true; - } - - @Override - public void postHandleRender( - RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView) throws Exception { - - this.requestInterceptor.postHandle(new PortletWebRequest(request), - (modelAndView != null && !modelAndView.wasCleared() ? modelAndView.getModelMap() : null)); - } - - @Override - public void afterRenderCompletion( - RenderRequest request, RenderResponse response, Object handler, Exception ex) throws Exception { - - this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex); - } - - @Override - public boolean preHandleResource(ResourceRequest request, ResourceResponse response, Object handler) - throws Exception { - - this.requestInterceptor.preHandle(new PortletWebRequest(request)); - return true; - } - - @Override - public void postHandleResource(ResourceRequest request, ResourceResponse response, Object handler, ModelAndView modelAndView) - throws Exception { - - this.requestInterceptor.postHandle(new PortletWebRequest(request), - (modelAndView != null ? modelAndView.getModelMap() : null)); - } - - @Override - public void afterResourceCompletion(ResourceRequest request, ResourceResponse response, Object handler, - Exception ex) throws Exception { - - this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex); - } - - @Override - public boolean preHandleEvent(EventRequest request, EventResponse response, Object handler) throws Exception { - this.requestInterceptor.preHandle(new PortletWebRequest(request)); - return true; - } - - @Override - public void afterEventCompletion(EventRequest request, EventResponse response, Object handler, Exception ex) - throws Exception { - - this.requestInterceptor.afterCompletion(new PortletWebRequest(request), ex); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/package-info.java deleted file mode 100644 index 08e03ce4fb..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/handler/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Provides standard HandlerMapping implementations, - * including abstract base classes for custom implementations. - */ -package org.springframework.web.portlet.handler; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java deleted file mode 100644 index 2644f2c845..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/CommonsPortletMultipartResolver.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2002-2015 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.multipart; - -import java.util.List; -import javax.portlet.ActionRequest; -import javax.portlet.PortletContext; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileItemFactory; -import org.apache.commons.fileupload.FileUpload; -import org.apache.commons.fileupload.FileUploadBase; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.portlet.PortletFileUpload; - -import org.springframework.util.Assert; -import org.springframework.web.multipart.MaxUploadSizeExceededException; -import org.springframework.web.multipart.MultipartException; -import org.springframework.web.multipart.commons.CommonsFileUploadSupport; -import org.springframework.web.portlet.context.PortletContextAware; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * {@link PortletMultipartResolver} implementation for - * Apache Commons FileUpload - * 1.2 or above. - * - *

        Provides "maxUploadSize", "maxInMemorySize" and "defaultEncoding" settings as - * bean properties (inherited from {@link CommonsFileUploadSupport}). See corresponding - * PortletFileUpload / DiskFileItemFactory properties ("sizeMax", "sizeThreshold", - * "headerEncoding") for details in terms of defaults and accepted values. - * - *

        Saves temporary files to the portlet container's temporary directory. - * Needs to be initialized either by an application context or - * via the constructor that takes a PortletContext (for standalone usage). - * - * @author Juergen Hoeller - * @since 2.0 - * @see #CommonsPortletMultipartResolver(javax.portlet.PortletContext) - * @see #setResolveLazily - * @see org.springframework.web.multipart.commons.CommonsMultipartResolver - * @see org.apache.commons.fileupload.portlet.PortletFileUpload - * @see org.apache.commons.fileupload.disk.DiskFileItemFactory - */ -public class CommonsPortletMultipartResolver extends CommonsFileUploadSupport - implements PortletMultipartResolver, PortletContextAware { - - private boolean resolveLazily = false; - - - /** - * Constructor for use as bean. Determines the portlet container's - * temporary directory via the PortletContext passed in as through the - * PortletContextAware interface (typically by an ApplicationContext). - * @see #setPortletContext - * @see org.springframework.web.portlet.context.PortletContextAware - */ - public CommonsPortletMultipartResolver() { - super(); - } - - /** - * Constructor for standalone usage. Determines the portlet container's - * temporary directory via the given PortletContext. - * @param portletContext the PortletContext to use - */ - public CommonsPortletMultipartResolver(PortletContext portletContext) { - this(); - setPortletContext(portletContext); - } - - - /** - * Set whether to resolve the multipart request lazily at the time of - * file or parameter access. - *

        Default is "false", resolving the multipart elements immediately, throwing - * corresponding exceptions at the time of the {@link #resolveMultipart} call. - * Switch this to "true" for lazy multipart parsing, throwing parse exceptions - * once the application attempts to obtain multipart files or parameters. - */ - public void setResolveLazily(boolean resolveLazily) { - this.resolveLazily = resolveLazily; - } - - /** - * Initialize the underlying {@code org.apache.commons.fileupload.portlet.PortletFileUpload} - * instance. Can be overridden to use a custom subclass, e.g. for testing purposes. - * @return the new PortletFileUpload instance - */ - @Override - protected FileUpload newFileUpload(FileItemFactory fileItemFactory) { - return new PortletFileUpload(fileItemFactory); - } - - @Override - public void setPortletContext(PortletContext portletContext) { - if (!isUploadTempDirSpecified()) { - getFileItemFactory().setRepository(PortletUtils.getTempDir(portletContext)); - } - } - - - @Override - public boolean isMultipart(ActionRequest request) { - return (request != null && PortletFileUpload.isMultipartContent(request)); - } - - @Override - public MultipartActionRequest resolveMultipart(final ActionRequest request) throws MultipartException { - Assert.notNull(request, "Request must not be null"); - if (this.resolveLazily) { - return new DefaultMultipartActionRequest(request) { - @Override - protected void initializeMultipart() { - MultipartParsingResult parsingResult = parseRequest(request); - setMultipartFiles(parsingResult.getMultipartFiles()); - setMultipartParameters(parsingResult.getMultipartParameters()); - setMultipartParameterContentTypes(parsingResult.getMultipartParameterContentTypes()); - } - }; - } - else { - MultipartParsingResult parsingResult = parseRequest(request); - return new DefaultMultipartActionRequest(request, parsingResult.getMultipartFiles(), - parsingResult.getMultipartParameters(), parsingResult.getMultipartParameterContentTypes()); - } - } - - /** - * Parse the given portlet request, resolving its multipart elements. - * @param request the request to parse - * @return the parsing result - * @throws MultipartException if multipart resolution failed. - */ - protected MultipartParsingResult parseRequest(ActionRequest request) throws MultipartException { - String encoding = determineEncoding(request); - FileUpload fileUpload = prepareFileUpload(encoding); - try { - List fileItems = ((PortletFileUpload) fileUpload).parseRequest(request); - return parseFileItems(fileItems, encoding); - } - catch (FileUploadBase.SizeLimitExceededException ex) { - throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex); - } - catch (FileUploadException ex) { - throw new MultipartException("Could not parse multipart portlet request", ex); - } - } - - /** - * Determine the encoding for the given request. - * Can be overridden in subclasses. - *

        The default implementation checks the request encoding, - * falling back to the default encoding specified for this resolver. - * @param request current portlet request - * @return the encoding for the request (never {@code null}) - * @see javax.portlet.ActionRequest#getCharacterEncoding - * @see #setDefaultEncoding - */ - protected String determineEncoding(ActionRequest request) { - String encoding = request.getCharacterEncoding(); - if (encoding == null) { - encoding = getDefaultEncoding(); - } - return encoding; - } - - @Override - public void cleanupMultipart(MultipartActionRequest request) { - if (request != null) { - try { - cleanupFileItems(request.getMultiFileMap()); - } - catch (Throwable ex) { - logger.warn("Failed to perform multipart cleanup for portlet request", ex); - } - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java deleted file mode 100644 index 5f13ba989e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/DefaultMultipartActionRequest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright 2002-2012 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.multipart; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import javax.portlet.ActionRequest; -import javax.portlet.filter.ActionRequestWrapper; - -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.multipart.MultipartFile; - -/** - * Default implementation of the {@link MultipartActionRequest} interface. - * Provides management of pre-generated parameter values. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @since 2.0 - * @see PortletMultipartResolver - */ -public class DefaultMultipartActionRequest extends ActionRequestWrapper implements MultipartActionRequest { - - private MultiValueMap multipartFiles; - - private Map multipartParameters; - - private Map multipartParameterContentTypes; - - - /** - * Wrap the given Portlet ActionRequest in a MultipartActionRequest. - * @param request the request to wrap - * @param mpFiles a map of the multipart files - * @param mpParams a map of the parameters to expose, - * with Strings as keys and String arrays as values - */ - public DefaultMultipartActionRequest(ActionRequest request, MultiValueMap mpFiles, - Map mpParams, Map mpParamContentTypes) { - - super(request); - setMultipartFiles(mpFiles); - setMultipartParameters(mpParams); - setMultipartParameterContentTypes(mpParamContentTypes); - } - - /** - * Wrap the given Portlet ActionRequest in a MultipartActionRequest. - * @param request the request to wrap - */ - protected DefaultMultipartActionRequest(ActionRequest request) { - super(request); - } - - - @Override - public Iterator getFileNames() { - return getMultipartFiles().keySet().iterator(); - } - - @Override - public MultipartFile getFile(String name) { - return getMultipartFiles().getFirst(name); - } - - @Override - public List getFiles(String name) { - List multipartFiles = getMultipartFiles().get(name); - if (multipartFiles != null) { - return multipartFiles; - } - else { - return Collections.emptyList(); - } - } - - - @Override - public Map getFileMap() { - return getMultipartFiles().toSingleValueMap(); - } - - @Override - public MultiValueMap getMultiFileMap() { - return getMultipartFiles(); - } - - @Override - public Enumeration getParameterNames() { - Set paramNames = new HashSet(); - Enumeration paramEnum = super.getParameterNames(); - while (paramEnum.hasMoreElements()) { - paramNames.add(paramEnum.nextElement()); - } - paramNames.addAll(getMultipartParameters().keySet()); - return Collections.enumeration(paramNames); - } - - @Override - public String getParameter(String name) { - String[] values = getMultipartParameters().get(name); - if (values != null) { - return (values.length > 0 ? values[0] : null); - } - return super.getParameter(name); - } - - @Override - public String[] getParameterValues(String name) { - String[] values = getMultipartParameters().get(name); - if (values != null) { - return values; - } - return super.getParameterValues(name); - } - - @Override - public Map getParameterMap() { - Map paramMap = new HashMap(); - paramMap.putAll(super.getParameterMap()); - paramMap.putAll(getMultipartParameters()); - return paramMap; - } - - @Override - public String getMultipartContentType(String paramOrFileName) { - MultipartFile file = getFile(paramOrFileName); - if (file != null) { - return file.getContentType(); - } - else { - return getMultipartParameterContentTypes().get(paramOrFileName); - } - } - - - /** - * Set a Map with parameter names as keys and list of MultipartFile objects as values. - * To be invoked by subclasses on initialization. - */ - protected final void setMultipartFiles(MultiValueMap multipartFiles) { - this.multipartFiles = - new LinkedMultiValueMap(Collections.unmodifiableMap(multipartFiles)); - } - - /** - * Obtain the MultipartFile Map for retrieval, - * lazily initializing it if necessary. - * @see #initializeMultipart() - */ - protected MultiValueMap getMultipartFiles() { - if (this.multipartFiles == null) { - initializeMultipart(); - } - return this.multipartFiles; - } - - /** - * Set a Map with parameter names as keys and String array objects as values. - * To be invoked by subclasses on initialization. - */ - protected final void setMultipartParameters(Map multipartParameters) { - this.multipartParameters = multipartParameters; - } - - /** - * Obtain the multipart parameter Map for retrieval, - * lazily initializing it if necessary. - * @see #initializeMultipart() - */ - protected Map getMultipartParameters() { - if (this.multipartParameters == null) { - initializeMultipart(); - } - return this.multipartParameters; - } - - /** - * Set a Map with parameter names as keys and content type Strings as values. - * To be invoked by subclasses on initialization. - */ - protected final void setMultipartParameterContentTypes(Map multipartParameterContentTypes) { - this.multipartParameterContentTypes = multipartParameterContentTypes; - } - - /** - * Obtain the multipart parameter content type Map for retrieval, - * lazily initializing it if necessary. - * @see #initializeMultipart() - */ - protected Map getMultipartParameterContentTypes() { - if (this.multipartParameterContentTypes == null) { - initializeMultipart(); - } - return this.multipartParameterContentTypes; - } - - - /** - * Lazily initialize the multipart request, if possible. - * Only called if not already eagerly initialized. - */ - protected void initializeMultipart() { - throw new IllegalStateException("Multipart request not initialized"); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/MultipartActionRequest.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/MultipartActionRequest.java deleted file mode 100644 index 4e44f015fb..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/MultipartActionRequest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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. - * 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.multipart; - -import javax.portlet.ActionRequest; - -import org.springframework.web.multipart.MultipartRequest; - -/** - * Interface which provides additional methods for dealing with multipart - * content within a portlet request, allowing to access uploaded files. - * Implementations also need to override the standard ActionRequest - * methods for parameter access, making multipart parameters available. - * - *

        A concrete implementation is {@link DefaultMultipartActionRequest}. - * - * @author Juergen Hoeller - * @since 2.0 - * @see PortletMultipartResolver - * @see org.springframework.web.multipart.MultipartFile - * @see javax.portlet.ActionRequest#getParameter - * @see javax.portlet.ActionRequest#getParameterNames - * @see javax.portlet.ActionRequest#getParameterMap - */ -public interface MultipartActionRequest extends ActionRequest, MultipartRequest { - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/PortletMultipartResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/PortletMultipartResolver.java deleted file mode 100644 index 81ec128966..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/PortletMultipartResolver.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2002-2015 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.multipart; - -import javax.portlet.ActionRequest; - -import org.springframework.web.multipart.MultipartException; - -/** - * Portlet version of Spring's multipart resolution strategy for file uploads - * as defined in RFC 1867. - * - *

        Implementations are typically usable both within any application context - * and standalone. - * - *

        There is one concrete implementation included in Spring: - *

          - *
        • {@link org.springframework.web.multipart.commons.CommonsMultipartResolver} - * for Apache Commons FileUpload - *
        - * - *

        There is no default resolver implementation used for Spring - * {@link org.springframework.web.portlet.DispatcherPortlet DispatcherPortlets}, - * as an application might choose to parse its multipart requests itself. To - * define an implementation, create a bean with the id "portletMultipartResolver" - * in a {@code DispatcherPortlet's} application context. Such a resolver - * gets applied to all requests handled by that {@code DispatcherPortlet}. - * - *

        If a {@code DispatcherPortlet} detects a multipart request, it will - * resolve it via the configured - * {@link org.springframework.web.portlet.multipart.PortletMultipartResolver} - * and pass on a wrapped Portlet {@link ActionRequest}. Controllers can then - * cast their given request to the {@link MultipartActionRequest} interface, - * being able to access {@code MultipartFiles}. Note that this cast is only - * supported in case of an actual multipart request. - * - *

         public void handleActionRequest(ActionRequest request, ActionResponse response) {
        - *   MultipartActionRequest multipartRequest = (MultipartActionRequest) request;
        - *   MultipartFile multipartFile = multipartRequest.getFile("image");
        - *   ...
        - * }
        - * - * Instead of direct access, command or form controllers can register a - * {@link org.springframework.web.multipart.support.ByteArrayMultipartFileEditor} - * or {@link org.springframework.web.multipart.support.StringMultipartFileEditor} - * with their data binder, to automatically apply multipart content to form - * bean properties. - * - *

        Note: There is hardly ever a need to access the {@code MultipartResolver} - * itself from application code. It will simply do its work behind the scenes, - * making {@code MultipartActionRequests} available to controllers. - * - * @author Juergen Hoeller - * @since 2.0 - * @see MultipartActionRequest - * @see org.springframework.web.multipart.MultipartFile - * @see CommonsPortletMultipartResolver - * @see org.springframework.web.multipart.support.ByteArrayMultipartFileEditor - * @see org.springframework.web.multipart.support.StringMultipartFileEditor - * @see org.springframework.web.portlet.DispatcherPortlet - */ -public interface PortletMultipartResolver { - - /** - * Determine if the given request contains multipart content. - *

        Will typically check for content type - * "{@code multipart/form-data}", but the actually accepted requests - * might depend on the capabilities of the resolver implementation. - * @param request the portlet request to be evaluated - * @return whether the request contains multipart content - */ - boolean isMultipart(ActionRequest request); - - /** - * Parse the given portlet request into multipart files and parameters, - * and wrap the request inside a MultipartActionRequest object - * that provides access to file descriptors and makes contained - * parameters accessible via the standard PortletRequest methods. - * @param request the portlet request to wrap (must be of a multipart content type) - * @return the wrapped portlet request - * @throws org.springframework.web.multipart.MultipartException if the portlet request - * is not multipart, or if implementation-specific problems are encountered - * (such as exceeding file size limits) - * @see org.springframework.web.portlet.multipart.MultipartActionRequest#getFile - * @see org.springframework.web.portlet.multipart.MultipartActionRequest#getFileNames - * @see org.springframework.web.portlet.multipart.MultipartActionRequest#getFileMap - * @see javax.portlet.ActionRequest#getParameter - * @see javax.portlet.ActionRequest#getParameterNames - * @see javax.portlet.ActionRequest#getParameterMap - */ - MultipartActionRequest resolveMultipart(ActionRequest request) throws MultipartException; - - /** - * Cleanup any resources used for the multipart handling, - * such as storage for any uploaded file(s). - * @param request the request to cleanup resources for - */ - void cleanupMultipart(MultipartActionRequest request); - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/package-info.java deleted file mode 100644 index dcaf6514a5..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/multipart/package-info.java +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Multipart resolution framework for handling file uploads. - * Provides a PortletMultipartResolver strategy interface, - * and a generic extension of the ActionRequest interface - * for accessing multipart files in web application code. - */ -package org.springframework.web.portlet.multipart; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractController.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractController.java deleted file mode 100644 index cc703aee27..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/AbstractController.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Copyright 2002-2014 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.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletException; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.WindowState; - -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.handler.PortletContentGenerator; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Convenient superclass for controller implementations, using the Template - * Method design pattern. - * - *

        As stated in the {@link Controller Controller} - * interface, a lot of functionality is already provided by certain abstract - * base controllers. The AbstractController is one of the most important - * abstract base controller providing basic features such controlling if a - * session is required and render caching. - * - *

        Workflow - * (and that defined by interface):
        - *

          - *
        1. If this is an action request, {@link #handleActionRequest handleActionRequest} - * will be called by the DispatcherPortlet once to perform the action defined by this - * controller.
        2. - *
        3. If a session is required, try to get it (PortletException if not found).
        4. - *
        5. Call method {@link #handleActionRequestInternal handleActionRequestInternal}, - * (optionally synchronizing around the call on the PortletSession), - * which should be overridden by extending classes to provide actual functionality to - * perform the desired action of the controller. This will be executed only once.
        6. - *
        7. For a straight render request, or the render phase of an action request (assuming the - * same controller is called for the render phase -- see tip below), - * {@link #handleRenderRequest handleRenderRequest} will be called by the DispatcherPortlet - * repeatedly to render the display defined by this controller.
        8. - *
        9. If a session is required, try to get it (PortletException if none found).
        10. - *
        11. It will control caching as defined by the cacheSeconds property.
        12. - *
        13. Call method {@link #handleRenderRequestInternal handleRenderRequestInternal}, - * (optionally synchronizing around the call on the PortletSession), - * which should be overridden by extending classes to provide actual functionality to - * return {@link org.springframework.web.portlet.ModelAndView ModelAndView} objects. - * This will be executed repeatedly as the portal updates the current displayed page.
        14. - *
        - * - *

        Exposed configuration properties - * (and those defined by interface):
        - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
        name - * defaultdescription
        requireSessionfalsewhether a session should be required for requests to be able to - * be handled by this controller. This ensures, derived controller - * can - without fear of Nullpointers - call request.getSession() to - * retrieve a session. If no session can be found while processing - * the request, a PortletException will be thrown
        synchronizeOnSessionfalsewhether the calls to {@code handleRenderRequestInternal} and - * {@code handleRenderRequestInternal} should be synchronized around - * the PortletSession, to serialize invocations from the same client. - * No effect if there is no PortletSession. - *
        cacheSeconds-1indicates the amount of seconds to specify caching is allowed in - * the render response generatedby this request. 0 (zero) will indicate - * no caching is allowed at all, -1 (the default) will not override the - * portlet configuration and any positive number will cause the render - * response to declare the amount indicated as seconds to cache the content
        renderWhenMinimizedfalsewhether should be rendered when the portlet is in a minimized state -- - * will return null for the ModelandView when the portlet is minimized - * and this is false
        - * - *

        TIP: The controller mapping will be run twice by the PortletDispatcher for - * action requests -- once for the action phase and again for the render phase. You can - * reach the render phase of a different controller by simply changing the values for the - * criteria your mapping is using, such as portlet mode or a request parameter, during the - * action phase of your controller. This is very handy since redirects within the portlet - * are apparently impossible. Before doing this, it is usually wise to call - * {@code clearAllRenderParameters} and then explicitly set all the parameters that - * you want the new controller to see. This avoids unexpected parameters from being passed - * to the render phase of the second controller, such as the parameter indicating a form - * submit ocurred in an {@code AbstractFormController}. - * - *

        Thanks to Rainer Schmitz and Nick Lothian for their suggestions! - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - * @see ResourceAwareController - * @see EventAwareController - */ -public abstract class AbstractController extends PortletContentGenerator implements Controller { - - private boolean synchronizeOnSession = false; - - private boolean renderWhenMinimized = false; - - - /** - * Set if controller execution should be synchronized on the session, - * to serialize parallel invocations from the same client. - *

        More specifically, the execution of the {@code handleActionRequestInternal} - * method will get synchronized if this flag is "true". The best available - * session mutex will be used for the synchronization; ideally, this will - * be a mutex exposed by HttpSessionMutexListener. - *

        The session mutex is guaranteed to be the same object during - * the entire lifetime of the session, available under the key defined - * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a - * safe reference to synchronize on for locking on the current session. - *

        In many cases, the PortletSession reference itself is a safe mutex - * as well, since it will always be the same object reference for the - * same active logical session. However, this is not guaranteed across - * different servlet containers; the only 100% safe way is a session mutex. - * @see #handleActionRequestInternal - * @see org.springframework.web.util.HttpSessionMutexListener - * @see org.springframework.web.portlet.util.PortletUtils#getSessionMutex(javax.portlet.PortletSession) - */ - public final void setSynchronizeOnSession(boolean synchronizeOnSession) { - this.synchronizeOnSession = synchronizeOnSession; - } - - /** - * Return whether controller execution should be synchronized on the session. - */ - public final boolean isSynchronizeOnSession() { - return this.synchronizeOnSession; - } - - /** - * Set if the controller should render an view when the portlet is in - * a minimized window. The default is false. - * @see javax.portlet.RenderRequest#getWindowState - * @see javax.portlet.WindowState#MINIMIZED - */ - public final void setRenderWhenMinimized(boolean renderWhenMinimized) { - this.renderWhenMinimized = renderWhenMinimized; - } - - /** - * Return whether controller will render when portlet is minimized. - */ - public final boolean isRenderWhenMinimized() { - return this.renderWhenMinimized; - } - - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) throws Exception { - // Delegate to PortletContentGenerator for checking and preparing. - check(request, response); - - // Execute in synchronized block if required. - if (this.synchronizeOnSession) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - Object mutex = PortletUtils.getSessionMutex(session); - synchronized (mutex) { - handleActionRequestInternal(request, response); - return; - } - } - } - - handleActionRequestInternal(request, response); - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - // If the portlet is minimized and we don't want to render then return null. - if (WindowState.MINIMIZED.equals(request.getWindowState()) && !this.renderWhenMinimized) { - return null; - } - - // Delegate to PortletContentGenerator for checking and preparing. - checkAndPrepare(request, response); - - // Execute in synchronized block if required. - if (this.synchronizeOnSession) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - Object mutex = PortletUtils.getSessionMutex(session); - synchronized (mutex) { - return handleRenderRequestInternal(request, response); - } - } - } - - return handleRenderRequestInternal(request, response); - } - - - /** - * Subclasses are meant to override this method if the controller - * is expected to handle action requests. The contract is the same as - * for {@code handleActionRequest}. - *

        The default implementation throws a PortletException. - * @see #handleActionRequest - * @see #handleRenderRequestInternal - */ - protected void handleActionRequestInternal(ActionRequest request, ActionResponse response) - throws Exception { - - throw new PortletException("[" + getClass().getName() + "] does not handle action requests"); - } - - /** - * Subclasses are meant to override this method if the controller - * is expected to handle render requests. The contract is the same as - * for {@code handleRenderRequest}. - *

        The default implementation throws a PortletException. - * @see #handleRenderRequest - * @see #handleActionRequestInternal - */ - protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) - throws Exception { - - throw new PortletException("[" + getClass().getName() + "] does not handle render requests"); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/Controller.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/Controller.java deleted file mode 100644 index 38bfb5075e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/Controller.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2002-2012 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.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.springframework.web.portlet.ModelAndView; - -/** - * Base portlet Controller interface, representing a component that receives - * RenderRequest/RenderResponse and ActionRequest/ActionResponse like a - * {@code Portlet} but is able to participate in an MVC workflow. - * - *

        Any implementation of the portlet Controller interface should be a - * reusable, threadsafe class, capable of handling multiple - * portlet requests throughout the lifecycle of an application. To be able to - * configure Controller(s) in an easy way, Controllers are usually JavaBeans.

        - * - *

        Workflow:

        - * - *

        After the DispatcherPortlet has received a request and has done its work - * to resolve locales, themes and suchlike, it tries to resolve a - * Controller to handle that request, using a - * {@link org.springframework.web.portlet.HandlerMapping HandlerMapping}. - * When a Controller has been found, the - * {@link #handleRenderRequest handleRenderRequest} or {@link #handleActionRequest handleActionRequest} - * method will be invoked, which is responsible for handling the actual - * 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.

        - * - *

        So basically any direct implementation of the Controller interface - * just handles RenderRequests/ActionRequests and should return a ModelAndView, to be - * further used by the DispatcherPortlet. Any additional functionality such as - * optional validation, form handling, etc should be obtained through extending - * one of the abstract controller classes mentioned above.

        - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @since 2.0 - * @see ResourceAwareController - * @see EventAwareController - * @see SimpleControllerHandlerAdapter - * @see AbstractController - * @see org.springframework.web.portlet.context.PortletContextAware - */ -public interface Controller { - - /** - * 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 - */ - void handleActionRequest(ActionRequest request, ActionResponse response) throws Exception; - - /** - * Process the render request and return a ModelAndView object which the DispatcherPortlet - * will render. A {@code null} 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 render request - * @param response current portlet render response - * @return a ModelAndView to render, or null if handled directly - * @throws Exception in case of errors - */ - ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/EventAwareController.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/EventAwareController.java deleted file mode 100644 index bd2519ea22..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/EventAwareController.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ParameterizableViewController.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ParameterizableViewController.java deleted file mode 100644 index 7dc8640578..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ParameterizableViewController.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2002-2014 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.RenderRequest; -import javax.portlet.RenderResponse; - -import org.springframework.web.portlet.ModelAndView; - -/** - * Trivial controller that always returns a named view. The view can be configured - * using an exposed configuration property. This controller offers an alternative - * to sending a request straight to a view such as a JSP. The advantage here is - * that the client is not exposed to the concrete view technology but rather just - * to the controller URL; the concrete view will be determined by the ViewResolver. - * - *

        Workflow - * (and that defined by superclass): - *

          - *
        1. Render request is received by the controller
        2. - *
        3. call to {@link #handleRenderRequestInternal handleRenderRequestInternal} which - * just returns the view, named by the configuration property {@code viewName}.
        4. - *
        - * - *

        This controller does not handle action requests. - * - *

        Exposed configuration properties - * (and those defined by superclass): - * - * - * - * - * - * - * - * - * - * - * - *
        namedefaultdescription
        viewNamenullthe name of the view the viewResolver will use to forward to (if this property - * is not set, an exception will be thrown during initialization)
        - * - * @author John A. Lewis - * @since 2.0 - */ -public class ParameterizableViewController extends AbstractController { - - private String viewName; - - - /** - * Set the name of the view to delegate to. - */ - public void setViewName(String viewName) { - this.viewName = viewName; - } - - /** - * Return the name of the view to delegate to. - */ - public String getViewName() { - return this.viewName; - } - - @Override - protected void initApplicationContext() { - if (this.viewName == null) { - throw new IllegalArgumentException("Property 'viewName' is required"); - } - } - - - /** - * Return a ModelAndView object with the specified view name. - */ - @Override - protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) - throws Exception { - - return new ModelAndView(getViewName()); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletModeNameViewController.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletModeNameViewController.java deleted file mode 100644 index 59e90c27af..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletModeNameViewController.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2002-2012 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.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletException; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.springframework.web.portlet.ModelAndView; - -/** - *

        Trivial controller that transforms the PortletMode to a view name. - * The advantage here is that the client is not exposed to - * the concrete view technology but rather just to the controller URL; - * the concrete view will be determined by the ViewResolver.

        - * - *

        Example: PortletMode.VIEW -> "view"

        - * - *

        This controller does not handle action requests.

        - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @since 2.0 - */ -public class PortletModeNameViewController implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) throws Exception { - throw new PortletException("PortletModeNameViewController does not handle action requests"); - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) { - return new ModelAndView(request.getPortletMode().toString()); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletWrappingController.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletWrappingController.java deleted file mode 100644 index e14cf7ea7e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/PortletWrappingController.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright 2002-2016 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 java.util.Collections; -import java.util.Enumeration; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; -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.PortletConfig; -import javax.portlet.PortletContext; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.ResourceRequest; -import javax.portlet.ResourceResponse; -import javax.portlet.ResourceServingPortlet; -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.NoHandlerFoundException; -import org.springframework.web.portlet.context.PortletConfigAware; -import org.springframework.web.portlet.context.PortletContextAware; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * {@link Controller} implementation that wraps a portlet instance which it manages - * internally. Such a wrapped portlet is not known outside of this controller; - * its entire lifecycle is covered here. - * - *

        Useful to invoke an existing portlet via Spring's dispatching infrastructure, - * for example to apply Spring - * {@link org.springframework.web.portlet.HandlerInterceptor HandlerInterceptors} - * to its requests. - * - *

        Example: - * - *

        <bean id="wrappingController" class="org.springframework.web.portlet.mvc.PortletWrappingController">
        - *   <property name="portletClass">
        - *     <value>org.springframework.web.portlet.sample.HelloWorldPortlet</value>
        - *   </property>
        - *   <property name="portletName">
        - *     <value>hello-world</value>
        - *   </property>
        - *   <property name="initParameters">
        - *     <props>
        - *       <prop key="config">/WEB-INF/hello-world-portlet-config.xml</prop>
        - *     </props>
        - *   </property>
        - * </bean>
        - * - * @author Juergen Hoeller - * @author John A. Lewis - * @since 2.0 - */ -public class PortletWrappingController extends AbstractController - implements ResourceAwareController, EventAwareController, - BeanNameAware, InitializingBean, DisposableBean, PortletContextAware, PortletConfigAware { - - private boolean useSharedPortletConfig = true; - - private PortletContext portletContext; - - private PortletConfig portletConfig; - - private Class portletClass; - - private String portletName; - - private Map initParameters = new LinkedHashMap(); - - private String beanName; - - private Portlet portletInstance; - - - /** - * Set whether to use the shared PortletConfig object passed in - * through {@code setPortletConfig}, if available. - *

        Default is "true". Turn this setting to "false" to pass in - * a mock PortletConfig object with the bean name as portlet name, - * holding the current PortletContext. - * @see #setPortletConfig - */ - public void setUseSharedPortletConfig(boolean useSharedPortletConfig) { - this.useSharedPortletConfig = useSharedPortletConfig; - } - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - @Override - public void setPortletConfig(PortletConfig portletConfig) { - this.portletConfig = portletConfig; - } - - /** - * Set the class of the Portlet to wrap. - * Needs to implement {@code javax.portlet.Portlet}. - * @see javax.portlet.Portlet - */ - public void setPortletClass(Class portletClass) { - this.portletClass = portletClass; - } - - /** - * Set the name of the Portlet to wrap. - * Default is the bean name of this controller. - */ - public void setPortletName(String portletName) { - this.portletName = portletName; - } - - /** - * Specify init parameters for the portlet to wrap, - * as name-value pairs. - */ - public void setInitParameters(Map initParameters) { - this.initParameters = initParameters; - } - - @Override - public void setBeanName(String name) { - this.beanName = name; - } - - - @Override - public void afterPropertiesSet() throws Exception { - if (this.portletClass == null) { - throw new IllegalArgumentException("portletClass is required"); - } - if (!Portlet.class.isAssignableFrom(this.portletClass)) { - throw new IllegalArgumentException("portletClass [" + this.portletClass.getName() + - "] needs to implement interface [javax.portlet.Portlet]"); - } - if (this.portletName == null) { - this.portletName = this.beanName; - } - PortletConfig config = this.portletConfig; - if (config == null || !this.useSharedPortletConfig) { - config = new DelegatingPortletConfig(); - } - this.portletInstance = (Portlet) this.portletClass.newInstance(); - this.portletInstance.init(config); - } - - - @Override - protected void handleActionRequestInternal( - ActionRequest request, ActionResponse response) throws Exception { - - this.portletInstance.processAction(request, response); - } - - @Override - protected ModelAndView handleRenderRequestInternal( - RenderRequest request, RenderResponse response) throws Exception { - - this.portletInstance.render(request, response); - return null; - } - - @Override - public ModelAndView handleResourceRequest( - ResourceRequest request, ResourceResponse response) throws Exception { - - if (!(this.portletInstance instanceof ResourceServingPortlet)) { - throw new NoHandlerFoundException("Cannot handle resource request - target portlet [" + - this.portletInstance.getClass() + " does not implement ResourceServingPortlet"); - } - ResourceServingPortlet resourcePortlet = (ResourceServingPortlet) this.portletInstance; - - // Delegate to PortletContentGenerator for checking and preparing. - checkAndPrepare(request, response); - - // Execute in synchronized block if required. - if (isSynchronizeOnSession()) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - Object mutex = PortletUtils.getSessionMutex(session); - synchronized (mutex) { - resourcePortlet.serveResource(request, response); - return null; - } - } - } - - resourcePortlet.serveResource(request, response); - return null; - } - - @Override - public void handleEventRequest( - EventRequest request, EventResponse response) throws Exception { - - if (!(this.portletInstance instanceof EventPortlet)) { - logger.debug("Ignoring event request for non-event target portlet: " + this.portletInstance.getClass()); - return; - } - EventPortlet eventPortlet = (EventPortlet) this.portletInstance; - - // Delegate to PortletContentGenerator for checking and preparing. - check(request, response); - - // Execute in synchronized block if required. - if (isSynchronizeOnSession()) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - Object mutex = PortletUtils.getSessionMutex(session); - synchronized (mutex) { - eventPortlet.processEvent(request, response); - return; - } - } - } - - eventPortlet.processEvent(request, response); - } - - - @Override - public void destroy() { - this.portletInstance.destroy(); - } - - - /** - * Internal implementation of the PortletConfig interface, to be passed - * to the wrapped portlet. - *

        Delegates to {@link PortletWrappingController} fields - * and methods to provide init parameters and other environment info. - */ - private class DelegatingPortletConfig implements PortletConfig { - - @Override - public String getPortletName() { - return portletName; - } - - @Override - public PortletContext getPortletContext() { - return portletContext; - } - - @Override - public String getInitParameter(String paramName) { - return initParameters.get(paramName); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(initParameters.keySet()); - } - - @Override - public ResourceBundle getResourceBundle(Locale locale) { - return (portletConfig != null ? portletConfig.getResourceBundle(locale) : null); - } - - @Override - public Enumeration getPublicRenderParameterNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public String getDefaultNamespace() { - return XMLConstants.NULL_NS_URI; - } - - @Override - public Enumeration getPublishingEventQNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public Enumeration getProcessingEventQNames() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public Enumeration getSupportedLocales() { - return Collections.enumeration(Collections.emptySet()); - } - - @Override - public Map getContainerRuntimeOptions() { - return (portletConfig != null ? portletConfig.getContainerRuntimeOptions() : null); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ResourceAwareController.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ResourceAwareController.java deleted file mode 100644 index 3d679dccff..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/ResourceAwareController.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2002-2012 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} 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; - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleControllerHandlerAdapter.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleControllerHandlerAdapter.java deleted file mode 100644 index bae04e4d30..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/SimpleControllerHandlerAdapter.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2002-2012 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.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.EventRequest; -import javax.portlet.EventResponse; -import javax.portlet.PortletContext; -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; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Adapter to use the Controller workflow interface with the generic DispatcherPortlet. - * - *

        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 - * @see ResourceAwareController - * @see EventAwareController - */ -public class SimpleControllerHandlerAdapter implements HandlerAdapter, PortletContextAware { - - private PortletContext portletContext; - - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - - @Override - public boolean supports(Object handler) { - return (handler instanceof Controller); - } - - @Override - public void handleAction(ActionRequest request, ActionResponse response, Object handler) - throws Exception { - - ((Controller) handler).handleActionRequest(request, response); - } - - @Override - public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object handler) - throws Exception { - - return ((Controller) handler).handleRenderRequest(request, response); - } - - @Override - 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 - PortletUtils.serveResource(request, response, this.portletContext); - return null; - } - } - - @Override - 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); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java deleted file mode 100644 index 017bc18aed..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +++ /dev/null @@ -1,846 +0,0 @@ -/* - * Copyright 2002-2015 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.annotation; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -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; -import javax.portlet.PortletPreferences; -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.StateAwareResponse; -import javax.portlet.WindowState; -import javax.servlet.http.Cookie; - -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.BeanExpressionContext; -import org.springframework.beans.factory.config.BeanExpressionResolver; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.core.DefaultParameterNameDiscoverer; -import org.springframework.core.Ordered; -import org.springframework.core.ParameterNameDiscoverer; -import org.springframework.core.annotation.AnnotationUtils; -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.support.DefaultSessionAttributeStore; -import org.springframework.web.bind.support.SessionAttributeStore; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.bind.support.WebBindingInitializer; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.RequestScope; -import org.springframework.web.multipart.MultipartRequest; -import org.springframework.web.portlet.HandlerAdapter; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.NoHandlerFoundException; -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; -import org.springframework.web.portlet.util.PortletUtils; -import org.springframework.web.servlet.View; -import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; - -/** - * Implementation of the {@link org.springframework.web.portlet.HandlerAdapter} - * interface that maps handler methods based on portlet modes, action/render phases - * and request parameters expressed through the {@link RequestMapping} annotation. - * - *

        Supports request parameter binding through the {@link RequestParam} annotation. - * Also supports the {@link ModelAttribute} annotation for exposing model attribute - * values to the view, as well as {@link InitBinder} for binder initialization methods - * and {@link SessionAttributes} for automatic session management of specific attributes. - * - *

        This adapter can be customized through various bean properties. - * A common use case is to apply shared binder initialization logic through - * a custom {@link #setWebBindingInitializer WebBindingInitializer}. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @since 2.5 - * @see #setWebBindingInitializer - * @see #setSessionAttributeStore - */ -public class AnnotationMethodHandlerAdapter extends PortletContentGenerator - implements HandlerAdapter, Ordered, BeanFactoryAware { - - public static final String IMPLICIT_MODEL_SESSION_ATTRIBUTE = - AnnotationMethodHandlerAdapter.class.getName() + ".IMPLICIT_MODEL"; - - public static final String IMPLICIT_MODEL_RENDER_PARAMETER = "implicitModel"; - - - private WebBindingInitializer webBindingInitializer; - - private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore(); - - private int cacheSecondsForSessionAttributeHandlers = 0; - - private boolean synchronizeOnSession = false; - - private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); - - private WebArgumentResolver[] customArgumentResolvers; - - private ModelAndViewResolver[] customModelAndViewResolvers; - - private int order = Ordered.LOWEST_PRECEDENCE; - - private ConfigurableBeanFactory beanFactory; - - private BeanExpressionContext expressionContext; - - private final Map, PortletHandlerMethodResolver> methodResolverCache = - new ConcurrentHashMap, PortletHandlerMethodResolver>(64); - - - /** - * Specify a WebBindingInitializer which will apply pre-configured - * configuration to every DataBinder that this controller uses. - */ - public void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) { - this.webBindingInitializer = webBindingInitializer; - } - - /** - * Specify the strategy to store session attributes with. - *

        Default is {@link org.springframework.web.bind.support.DefaultSessionAttributeStore}, - * storing session attributes in the PortletSession, using the same - * attribute name as in the model. - */ - public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) { - Assert.notNull(sessionAttributeStore, "SessionAttributeStore must not be null"); - this.sessionAttributeStore = sessionAttributeStore; - } - - /** - * Cache content produced by {@code @SessionAttributes} annotated handlers - * for the given number of seconds. Default is 0, preventing caching completely. - *

        In contrast to the "cacheSeconds" property which will apply to all general - * handlers (but not to {@code @SessionAttributes} annotated handlers), this - * setting will apply to {@code @SessionAttributes} annotated handlers only. - * @see #setCacheSeconds - * @see org.springframework.web.bind.annotation.SessionAttributes - */ - public void setCacheSecondsForSessionAttributeHandlers(int cacheSecondsForSessionAttributeHandlers) { - this.cacheSecondsForSessionAttributeHandlers = cacheSecondsForSessionAttributeHandlers; - } - - /** - * Set if controller execution should be synchronized on the session, - * to serialize parallel invocations from the same client. - *

        More specifically, the execution of each handler method will get - * synchronized if this flag is "true". The best available session mutex - * will be used for the synchronization; ideally, this will be a mutex - * exposed by HttpSessionMutexListener. - *

        The session mutex is guaranteed to be the same object during - * the entire lifetime of the session, available under the key defined - * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a - * safe reference to synchronize on for locking on the current session. - *

        In many cases, the PortletSession reference itself is a safe mutex - * as well, since it will always be the same object reference for the - * same active logical session. However, this is not guaranteed across - * different servlet containers; the only 100% safe way is a session mutex. - * @see org.springframework.web.util.HttpSessionMutexListener - * @see org.springframework.web.portlet.util.PortletUtils#getSessionMutex(javax.portlet.PortletSession) - */ - public void setSynchronizeOnSession(boolean synchronizeOnSession) { - this.synchronizeOnSession = synchronizeOnSession; - } - - /** - * Set the ParameterNameDiscoverer to use for resolving method parameter - * names if needed (e.g. for default attribute names). - *

        Default is a {@link org.springframework.core.DefaultParameterNameDiscoverer}. - */ - public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) { - this.parameterNameDiscoverer = parameterNameDiscoverer; - } - - /** - * Set a custom WebArgumentResolver to use for special method parameter types. - * Such a custom WebArgumentResolver will kick in first, having a chance to - * resolve an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolver(WebArgumentResolver argumentResolver) { - this.customArgumentResolvers = new WebArgumentResolver[] {argumentResolver}; - } - - /** - * Set one or more custom WebArgumentResolvers to use for special method - * parameter types. Any such custom WebArgumentResolver will kick in first, - * having a chance to resolve an argument value before the standard - * argument handling kicks in. - */ - public void setCustomArgumentResolvers(WebArgumentResolver... argumentResolvers) { - this.customArgumentResolvers = argumentResolvers; - } - - /** - * Set a custom ModelAndViewResolvers to use for special method return types. - * Such a custom ModelAndViewResolver will kick in first, having a chance to - * resolve an return value before the standard ModelAndView handling kicks in. - */ - public void setCustomModelAndViewResolver(ModelAndViewResolver customModelAndViewResolver) { - this.customModelAndViewResolvers = new ModelAndViewResolver[]{customModelAndViewResolver}; - } - - /** - * Set one or more custom ModelAndViewResolvers to use for special method return types. - * Any such custom ModelAndViewResolver will kick in first, having a chance to - * resolve an return value before the standard ModelAndView handling kicks in. - */ - public void setCustomModelAndViewResolvers(ModelAndViewResolver... customModelAndViewResolvers) { - this.customModelAndViewResolvers = customModelAndViewResolvers; - } - - /** - * Specify the order value for this HandlerAdapter bean. - *

        Default value is {@code Integer.MAX_VALUE}, meaning that it's non-ordered. - * @see org.springframework.core.Ordered#getOrder() - */ - public void setOrder(int order) { - this.order = order; - } - - @Override - public int getOrder() { - return this.order; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - if (beanFactory instanceof ConfigurableBeanFactory) { - this.beanFactory = (ConfigurableBeanFactory) beanFactory; - this.expressionContext = new BeanExpressionContext(this.beanFactory, new RequestScope()); - } - } - - - @Override - public boolean supports(Object handler) { - return getMethodResolver(handler).hasHandlerMethods(); - } - - @Override - public void handleAction(ActionRequest request, ActionResponse response, Object handler) throws Exception { - Object returnValue = doHandle(request, response, handler); - if (returnValue != null) { - throw new IllegalStateException("Invalid action method return value: " + returnValue); - } - } - - @Override - public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object handler) throws Exception { - checkAndPrepare(request, response); - return doHandle(request, response, handler); - } - - @Override - public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler) throws Exception { - checkAndPrepare(request, response); - return doHandle(request, response, handler); - } - - @Override - public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception { - Object returnValue = doHandle(request, response, handler); - if (returnValue != null) { - throw new IllegalStateException("Invalid event method return value: " + returnValue); - } - } - - - protected ModelAndView doHandle(PortletRequest request, PortletResponse response, Object handler) throws Exception { - ExtendedModelMap implicitModel = null; - - if (response instanceof MimeResponse) { - MimeResponse mimeResponse = (MimeResponse) response; - // Detect implicit model from associated action phase. - if (response instanceof RenderResponse) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - if (request.getParameter(IMPLICIT_MODEL_RENDER_PARAMETER) != null) { - implicitModel = (ExtendedModelMap) session.getAttribute(IMPLICIT_MODEL_SESSION_ATTRIBUTE); - } - else { - session.removeAttribute(IMPLICIT_MODEL_SESSION_ATTRIBUTE); - } - } - } - if (handler.getClass().getAnnotation(SessionAttributes.class) != null) { - // Always prevent caching in case of session attribute management. - checkAndPrepare(request, mimeResponse, this.cacheSecondsForSessionAttributeHandlers); - } - else { - // Uses configured default cacheSeconds setting. - checkAndPrepare(request, mimeResponse); - } - } - - if (implicitModel == null) { - implicitModel = new BindingAwareModelMap(); - } - - // Execute invokeHandlerMethod in synchronized block if required. - if (this.synchronizeOnSession) { - PortletSession session = request.getPortletSession(false); - if (session != null) { - Object mutex = PortletUtils.getSessionMutex(session); - synchronized (mutex) { - return invokeHandlerMethod(request, response, handler, implicitModel); - } - } - } - - return invokeHandlerMethod(request, response, handler, implicitModel); - } - - @SuppressWarnings("unchecked") - private ModelAndView invokeHandlerMethod( - PortletRequest request, PortletResponse response, Object handler, ExtendedModelMap implicitModel) - throws Exception { - - PortletWebRequest webRequest = new PortletWebRequest(request, response); - PortletHandlerMethodResolver methodResolver = getMethodResolver(handler); - Method handlerMethod = methodResolver.resolveHandlerMethod(request); - PortletHandlerMethodInvoker methodInvoker = new PortletHandlerMethodInvoker(methodResolver); - - Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel); - ModelAndView mav = methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, - webRequest); - methodInvoker.updateModelAttributes( - handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest); - - // Expose implicit model for subsequent render phase. - if (response instanceof StateAwareResponse && !implicitModel.isEmpty()) { - StateAwareResponse stateResponse = (StateAwareResponse) response; - Map modelToStore = implicitModel; - try { - stateResponse.setRenderParameter(IMPLICIT_MODEL_RENDER_PARAMETER, Boolean.TRUE.toString()); - if (response instanceof EventResponse) { - // Update the existing model, if any, when responding to an event - - // whereas we're replacing the model in case of an action response. - Map existingModel = (Map) - request.getPortletSession().getAttribute(IMPLICIT_MODEL_SESSION_ATTRIBUTE); - if (existingModel != null) { - existingModel.putAll(implicitModel); - modelToStore = existingModel; - } - } - request.getPortletSession().setAttribute(IMPLICIT_MODEL_SESSION_ATTRIBUTE, modelToStore); - } - catch (IllegalStateException ex) { - // Probably sendRedirect called... no need to expose model to render phase. - } - } - - return mav; - } - - /** - * Build a HandlerMethodResolver for the given handler type. - */ - private PortletHandlerMethodResolver getMethodResolver(Object handler) { - Class handlerClass = ClassUtils.getUserClass(handler); - PortletHandlerMethodResolver resolver = this.methodResolverCache.get(handlerClass); - if (resolver == null) { - synchronized (this.methodResolverCache) { - resolver = this.methodResolverCache.get(handlerClass); - if (resolver == null) { - resolver = new PortletHandlerMethodResolver(handlerClass); - this.methodResolverCache.put(handlerClass, resolver); - } - } - } - return resolver; - } - - /** - * Template method for creating a new PortletRequestDataBinder instance. - *

        The default implementation creates a standard PortletRequestDataBinder. - * This can be overridden for custom PortletRequestDataBinder subclasses. - * @param request current portlet request - * @param target the target object to bind onto (or {@code null} - * if the binder is just used to convert a plain parameter value) - * @param objectName the objectName of the target object - * @return the PortletRequestDataBinder instance to use - * @throws Exception in case of invalid state or arguments - * @see PortletRequestDataBinder#bind(javax.portlet.PortletRequest) - */ - protected PortletRequestDataBinder createBinder(PortletRequest request, Object target, String objectName) throws Exception { - return new PortletRequestDataBinder(target, objectName); - } - - - /** - * Portlet-specific subclass of {@code HandlerMethodResolver}. - */ - @SuppressWarnings("deprecation") - private static class PortletHandlerMethodResolver extends org.springframework.web.bind.annotation.support.HandlerMethodResolver { - - private final Map mappings = new HashMap(); - - public PortletHandlerMethodResolver(Class handlerType) { - init(handlerType); - } - - @Override - protected boolean isHandlerMethod(Method method) { - if (this.mappings.containsKey(method)) { - return true; - } - RequestMappingInfo mappingInfo = new RequestMappingInfo(); - 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); - RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); - if (actionMapping != null) { - mappingInfo.initPhaseMapping(PortletRequest.ACTION_PHASE, actionMapping.name(), actionMapping.params()); - } - if (renderMapping != null) { - mappingInfo.initPhaseMapping(PortletRequest.RENDER_PHASE, renderMapping.windowState(), renderMapping.params()); - } - if (resourceMapping != null) { - mappingInfo.initPhaseMapping(PortletRequest.RESOURCE_PHASE, resourceMapping.value(), new String[0]); - } - if (eventMapping != null) { - mappingInfo.initPhaseMapping(PortletRequest.EVENT_PHASE, eventMapping.value(), new String[0]); - } - if (requestMapping != null) { - mappingInfo.initStandardMapping(requestMapping.value(), requestMapping.method(), - requestMapping.params(), requestMapping.headers()); - if (mappingInfo.phase == null) { - mappingInfo.phase = determineDefaultPhase(method); - } - } - if (mappingInfo.phase != null) { - this.mappings.put(method, mappingInfo); - return true; - } - return false; - } - - public Method resolveHandlerMethod(PortletRequest request) throws PortletException { - Map targetHandlerMethods = new LinkedHashMap(); - for (Method handlerMethod : getHandlerMethods()) { - 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 '" + - 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!"); - } - } - } - if (!targetHandlerMethods.isEmpty()) { - if (targetHandlerMethods.size() == 1) { - return targetHandlerMethods.values().iterator().next(); - } - else { - RequestMappingInfo bestMappingMatch = null; - for (RequestMappingInfo mapping : targetHandlerMethods.keySet()) { - if (bestMappingMatch == null) { - bestMappingMatch = mapping; - } - else { - if (mapping.isBetterMatchThan(bestMappingMatch)) { - bestMappingMatch = mapping; - } - } - } - return targetHandlerMethods.get(bestMappingMatch); - } - } - else { - throw new NoHandlerFoundException("No matching handler method found for portlet request", request); - } - } - - private String determineDefaultPhase(Method handlerMethod) { - if (void.class != handlerMethod.getReturnType()) { - 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 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 ""; - } - } - - - /** - * Portlet-specific subclass of {@code HandlerMethodInvoker}. - */ - @SuppressWarnings("deprecation") - private class PortletHandlerMethodInvoker extends org.springframework.web.bind.annotation.support.HandlerMethodInvoker { - - public PortletHandlerMethodInvoker(org.springframework.web.bind.annotation.support.HandlerMethodResolver resolver) { - super(resolver, webBindingInitializer, sessionAttributeStore, - parameterNameDiscoverer, customArgumentResolvers, null); - } - - @Override - protected void raiseMissingParameterException(String paramName, Class paramType) throws Exception { - throw new MissingPortletRequestParameterException(paramName, paramType.getSimpleName()); - } - - @Override - protected void raiseSessionRequiredException(String message) throws Exception { - throw new PortletSessionRequiredException(message); - } - - @Override - protected WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) - throws Exception { - - return AnnotationMethodHandlerAdapter.this.createBinder( - webRequest.getNativeRequest(PortletRequest.class), target, objectName); - } - - @Override - protected void doBind(WebDataBinder binder, NativeWebRequest webRequest) throws Exception { - PortletRequestDataBinder portletBinder = (PortletRequestDataBinder) binder; - portletBinder.bind(webRequest.getNativeRequest(PortletRequest.class)); - } - - @Override - protected Object resolveDefaultValue(String value) { - if (beanFactory == null) { - return value; - } - String placeholdersResolved = beanFactory.resolveEmbeddedValue(value); - BeanExpressionResolver exprResolver = beanFactory.getBeanExpressionResolver(); - if (exprResolver == null) { - return value; - } - return exprResolver.evaluate(placeholdersResolved, expressionContext); - } - - @Override - protected Object resolveCookieValue(String cookieName, Class paramType, NativeWebRequest webRequest) - throws Exception { - - PortletRequest portletRequest = webRequest.getNativeRequest(PortletRequest.class); - Cookie cookieValue = PortletUtils.getCookie(portletRequest, cookieName); - if (Cookie.class.isAssignableFrom(paramType)) { - return cookieValue; - } - else if (cookieValue != null) { - return cookieValue.getValue(); - } - else { - return null; - } - } - - @Override - protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest) - throws Exception { - - PortletRequest request = webRequest.getNativeRequest(PortletRequest.class); - PortletResponse response = webRequest.getNativeResponse(PortletResponse.class); - - if (PortletRequest.class.isAssignableFrom(parameterType) || - MultipartRequest.class.isAssignableFrom(parameterType)) { - Object nativeRequest = webRequest.getNativeRequest(parameterType); - if (nativeRequest == null) { - throw new IllegalStateException( - "Current request is not of type [" + parameterType.getName() + "]: " + request); - } - return nativeRequest; - } - else if (PortletResponse.class.isAssignableFrom(parameterType)) { - Object nativeResponse = webRequest.getNativeResponse(parameterType); - if (nativeResponse == null) { - throw new IllegalStateException( - "Current response is not of type [" + parameterType.getName() + "]: " + response); - } - return nativeResponse; - } - else if (PortletSession.class.isAssignableFrom(parameterType)) { - return request.getPortletSession(); - } - else if (PortletPreferences.class.isAssignableFrom(parameterType)) { - return request.getPreferences(); - } - else if (PortletMode.class.isAssignableFrom(parameterType)) { - return request.getPortletMode(); - } - else if (WindowState.class.isAssignableFrom(parameterType)) { - return request.getWindowState(); - } - else if (PortalContext.class.isAssignableFrom(parameterType)) { - return request.getPortalContext(); - } - else if (Principal.class.isAssignableFrom(parameterType)) { - return request.getUserPrincipal(); - } - else if (Locale.class == parameterType) { - return request.getLocale(); - } - else if (InputStream.class.isAssignableFrom(parameterType)) { - if (!(request instanceof ClientDataRequest)) { - throw new IllegalStateException("InputStream can only get obtained for Action/ResourceRequest"); - } - return ((ClientDataRequest) request).getPortletInputStream(); - } - else if (Reader.class.isAssignableFrom(parameterType)) { - if (!(request instanceof ClientDataRequest)) { - throw new IllegalStateException("Reader can only get obtained for Action/ResourceRequest"); - } - return ((ClientDataRequest) request).getReader(); - } - else if (OutputStream.class.isAssignableFrom(parameterType)) { - if (!(response instanceof MimeResponse)) { - throw new IllegalStateException("OutputStream can only get obtained for Render/ResourceResponse"); - } - return ((MimeResponse) response).getPortletOutputStream(); - } - else if (Writer.class.isAssignableFrom(parameterType)) { - if (!(response instanceof MimeResponse)) { - throw new IllegalStateException("Writer can only get obtained for Render/ResourceResponse"); - } - return ((MimeResponse) response).getWriter(); - } - else if (Event.class == parameterType) { - if (!(request instanceof EventRequest)) { - throw new IllegalStateException("Event can only get obtained from EventRequest"); - } - return ((EventRequest) request).getEvent(); - } - return super.resolveStandardArgument(parameterType, webRequest); - } - - @SuppressWarnings("unchecked") - public ModelAndView getModelAndView(Method handlerMethod, Class handlerType, Object returnValue, ExtendedModelMap implicitModel, - PortletWebRequest webRequest) { - // Invoke custom resolvers if present... - if (customModelAndViewResolvers != null) { - for (ModelAndViewResolver mavResolver : customModelAndViewResolvers) { - org.springframework.web.servlet.ModelAndView smav = - mavResolver.resolveModelAndView(handlerMethod, handlerType, returnValue, implicitModel, webRequest); - if (smav != ModelAndViewResolver.UNRESOLVED) { - return (smav.isReference() ? - new ModelAndView(smav.getViewName(), smav.getModelMap()) : - new ModelAndView(smav.getView(), smav.getModelMap())); - } - } - } - - if (returnValue instanceof ModelAndView) { - ModelAndView mav = (ModelAndView) returnValue; - mav.getModelMap().mergeAttributes(implicitModel); - return mav; - } - else if (returnValue instanceof org.springframework.web.servlet.ModelAndView) { - org.springframework.web.servlet.ModelAndView smav = (org.springframework.web.servlet.ModelAndView) returnValue; - ModelAndView mav = (smav.isReference() ? - new ModelAndView(smav.getViewName(), smav.getModelMap()) : - new ModelAndView(smav.getView(), smav.getModelMap())); - mav.getModelMap().mergeAttributes(implicitModel); - return mav; - } - else if (returnValue instanceof Model) { - return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap()); - } - else if (returnValue instanceof View) { - return new ModelAndView(returnValue).addAllObjects(implicitModel); - } - else if (handlerMethod.isAnnotationPresent(ModelAttribute.class)) { - addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel); - return new ModelAndView().addAllObjects(implicitModel); - } - else if (returnValue instanceof Map) { - return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue); - } - else if (returnValue instanceof String) { - return new ModelAndView((String) returnValue).addAllObjects(implicitModel); - } - else if (returnValue == null) { - // Either returned null or was 'void' return. - return null; - } - else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) { - // Assume a single model attribute... - addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel); - return new ModelAndView().addAllObjects(implicitModel); - } - else { - throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); - } - } - } - - - /** - * Holder for request mapping metadata. Allows for finding a best matching candidate. - */ - private static class RequestMappingInfo { - - public final Set modes = new HashSet(); - - public String phase; - - public String value; - - public final Set methods = new HashSet(); - - public String[] params = new String[0]; - - public String[] headers = new String[0]; - - public void initStandardMapping(String[] modes, RequestMethod[] methods, String[] params, String[] headers) { - 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); - this.headers = StringUtils.mergeStringArrays(this.headers, headers); - } - - 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 + "'"); - } - 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 (PortletAnnotationMappingUtils.checkRequestMethod(this.methods, request) && - PortletAnnotationMappingUtils.checkParameters(this.params, request) && - PortletAnnotationMappingUtils.checkHeaders(this.headers, 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) && - Arrays.equals(this.headers, other.headers)); - } - - @Override - public int hashCode() { - return (ObjectUtils.nullSafeHashCode(this.modes) * 29 + this.phase.hashCode()); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java deleted file mode 100644 index 765dfa67c0..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java +++ /dev/null @@ -1,408 +0,0 @@ -/* - * Copyright 2002-2015 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.annotation; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import javax.portlet.ClientDataRequest; -import javax.portlet.Event; -import javax.portlet.EventRequest; -import javax.portlet.MimeResponse; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletPreferences; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; -import javax.portlet.WindowState; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpSession; - -import org.springframework.core.ExceptionDepthComparator; -import org.springframework.core.GenericTypeResolver; -import org.springframework.core.MethodParameter; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.annotation.SynthesizingMethodParameter; -import org.springframework.ui.Model; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.ReflectionUtils; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.context.PortletWebRequest; -import org.springframework.web.portlet.handler.AbstractHandlerExceptionResolver; -import org.springframework.web.servlet.View; - -/** - * Implementation of the {@link org.springframework.web.portlet.HandlerExceptionResolver} interface that handles - * exceptions through the {@link ExceptionHandler} annotation. - * - *

        This exception resolver is enabled by default in the {@link org.springframework.web.portlet.DispatcherPortlet}. - * - * @author Arjen Poutsma - * @author Juergen Hoeller - * @since 3.0 - */ -public class AnnotationMethodHandlerExceptionResolver extends AbstractHandlerExceptionResolver { - - /** - * Arbitrary {@link Method} reference, indicating no method found in the cache. - */ - private static final Method NO_METHOD_FOUND = ClassUtils.getMethodIfAvailable(System.class, "currentTimeMillis"); - - - private final Map, Map, Method>> exceptionHandlerCache = - new ConcurrentHashMap, Map, Method>>(64); - - private WebArgumentResolver[] customArgumentResolvers; - - - /** - * Set a custom ArgumentResolvers to use for special method parameter types. - *

        Such a custom ArgumentResolver will kick in first, having a chance to resolve - * an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolver(WebArgumentResolver argumentResolver) { - this.customArgumentResolvers = new WebArgumentResolver[]{argumentResolver}; - } - - /** - * Set one or more custom ArgumentResolvers to use for special method parameter types. - *

        Any such custom ArgumentResolver will kick in first, having a chance to resolve - * an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolvers(WebArgumentResolver[] argumentResolvers) { - this.customArgumentResolvers = argumentResolvers; - } - - - @Override - protected ModelAndView doResolveException( - PortletRequest request, MimeResponse response, Object handler, Exception ex) { - - if (handler != null) { - Method handlerMethod = findBestExceptionHandlerMethod(handler, ex); - if (handlerMethod != null) { - NativeWebRequest webRequest = new PortletWebRequest(request, response); - try { - Object[] args = resolveHandlerArguments(handlerMethod, handler, webRequest, ex); - if (logger.isDebugEnabled()) { - logger.debug("Invoking request handler method: " + handlerMethod); - } - Object retVal = doInvokeMethod(handlerMethod, handler, args); - return getModelAndView(retVal); - } - catch (Exception invocationEx) { - logger.error("Invoking request method resulted in exception : " + handlerMethod, invocationEx); - } - } - } - return null; - } - - /** - * Finds the handler method that matches the thrown exception best. - * @param handler the handler object - * @param thrownException the exception to be handled - * @return the best matching method; or {@code null} if none is found - */ - private Method findBestExceptionHandlerMethod(Object handler, final Exception thrownException) { - final Class handlerType = handler.getClass(); - final Class thrownExceptionType = thrownException.getClass(); - Method handlerMethod; - - Map, Method> handlers = this.exceptionHandlerCache.get(handlerType); - if (handlers != null) { - handlerMethod = handlers.get(thrownExceptionType); - if (handlerMethod != null) { - return (handlerMethod == NO_METHOD_FOUND ? null : handlerMethod); - } - } - else { - handlers = new ConcurrentHashMap, Method>(16); - this.exceptionHandlerCache.put(handlerType, handlers); - } - - final Map, Method> matchedHandlers = new HashMap, Method>(); - - ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) { - method = ClassUtils.getMostSpecificMethod(method, handlerType); - List> handledExceptions = getHandledExceptions(method); - for (Class handledException : handledExceptions) { - if (handledException.isAssignableFrom(thrownExceptionType)) { - if (!matchedHandlers.containsKey(handledException)) { - matchedHandlers.put(handledException, method); - } - else { - Method oldMappedMethod = matchedHandlers.get(handledException); - if (!oldMappedMethod.equals(method)) { - throw new IllegalStateException( - "Ambiguous exception handler mapped for " + handledException + "]: {" + - oldMappedMethod + ", " + method + "}."); - } - } - } - } - } - }); - - handlerMethod = getBestMatchingMethod(matchedHandlers, thrownException); - handlers.put(thrownExceptionType, (handlerMethod == null ? NO_METHOD_FOUND : handlerMethod)); - return handlerMethod; - } - - /** - * Returns all the exception classes handled by the given method. - *

        Default implementation looks for exceptions in the {@linkplain ExceptionHandler#value() annotation}, - * or - if that annotation element is empty - any exceptions listed in the method parameters if the - * method is annotated with {@code @ExceptionHandler}. - * @param method the method - * @return the handled exceptions - */ - @SuppressWarnings("unchecked") - protected List> getHandledExceptions(Method method) { - List> result = new ArrayList>(); - ExceptionHandler exceptionHandler = AnnotationUtils.findAnnotation(method, ExceptionHandler.class); - if (exceptionHandler != null) { - if (!ObjectUtils.isEmpty(exceptionHandler.value())) { - result.addAll(Arrays.asList(exceptionHandler.value())); - } - else { - for (Class param : method.getParameterTypes()) { - if (Throwable.class.isAssignableFrom(param)) { - result.add((Class) param); - } - } - } - } - return result; - } - - /** - * Uses the {@link ExceptionDepthComparator} to find the best matching method. - * @return the best matching method, or {@code null} if none found - */ - private Method getBestMatchingMethod( - Map, Method> resolverMethods, Exception thrownException) { - - if (resolverMethods.isEmpty()) { - return null; - } - Class closestMatch = - ExceptionDepthComparator.findClosestMatch(resolverMethods.keySet(), thrownException); - Method method = resolverMethods.get(closestMatch); - return (method == null || NO_METHOD_FOUND == method ? null : method); - } - - /** - * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}. - */ - private Object[] resolveHandlerArguments(Method handlerMethod, Object handler, - NativeWebRequest webRequest, Exception thrownException) throws Exception { - - Class[] paramTypes = handlerMethod.getParameterTypes(); - Object[] args = new Object[paramTypes.length]; - Class handlerType = handler.getClass(); - for (int i = 0; i < args.length; i++) { - MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i); - GenericTypeResolver.resolveParameterType(methodParam, handlerType); - Class paramType = methodParam.getParameterType(); - Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException); - if (argValue != WebArgumentResolver.UNRESOLVED) { - args[i] = argValue; - } - else { - throw new IllegalStateException("Unsupported argument [" + paramType.getName() + - "] for @ExceptionHandler method: " + handlerMethod); - } - } - return args; - } - - /** - * Resolves common method arguments. Delegates to registered - * {@link #setCustomArgumentResolver argumentResolvers} first, - * then checking {@link #resolveStandardArgument}. - * @param methodParameter the method parameter - * @param webRequest the request - * @param thrownException the exception thrown - * @return the argument value, or {@link org.springframework.web.bind.support.WebArgumentResolver#UNRESOLVED} - */ - protected Object resolveCommonArgument(MethodParameter methodParameter, NativeWebRequest webRequest, - Exception thrownException) throws Exception { - - // Invoke custom argument resolvers if present... - if (this.customArgumentResolvers != null) { - for (WebArgumentResolver argumentResolver : this.customArgumentResolvers) { - Object value = argumentResolver.resolveArgument(methodParameter, webRequest); - if (value != WebArgumentResolver.UNRESOLVED) { - return value; - } - } - } - - // Resolution of standard parameter types... - Class paramType = methodParameter.getParameterType(); - Object value = resolveStandardArgument(paramType, webRequest, thrownException); - if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) { - throw new IllegalStateException("Standard argument type [" + paramType.getName() + - "] resolved to incompatible value of type [" + (value != null ? value.getClass() : null) + - "]. Consider declaring the argument type in a less specific fashion."); - } - return value; - } - - /** - * Resolves standard method arguments. The default implementation handles {@link NativeWebRequest}, - * {@link ServletRequest}, {@link ServletResponse}, {@link HttpSession}, {@link Principal}, - * {@link Locale}, request {@link InputStream}, request {@link Reader}, response {@link OutputStream}, - * response {@link Writer}, and the given {@code thrownException}. - * @param parameterType the method parameter type - * @param webRequest the request - * @param thrownException the exception thrown - * @return the argument value, or {@link org.springframework.web.bind.support.WebArgumentResolver#UNRESOLVED} - */ - protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest, - Exception thrownException) throws Exception { - - if (parameterType.isInstance(thrownException)) { - return thrownException; - } - else if (WebRequest.class.isAssignableFrom(parameterType)) { - return webRequest; - } - - PortletRequest request = webRequest.getNativeRequest(PortletRequest.class); - PortletResponse response = webRequest.getNativeResponse(PortletResponse.class); - - if (PortletRequest.class.isAssignableFrom(parameterType)) { - return request; - } - else if (PortletResponse.class.isAssignableFrom(parameterType)) { - return response; - } - else if (PortletSession.class.isAssignableFrom(parameterType)) { - return request.getPortletSession(); - } - else if (PortletPreferences.class.isAssignableFrom(parameterType)) { - return request.getPreferences(); - } - else if (PortletMode.class.isAssignableFrom(parameterType)) { - return request.getPortletMode(); - } - else if (WindowState.class.isAssignableFrom(parameterType)) { - return request.getWindowState(); - } - else if (PortalContext.class.isAssignableFrom(parameterType)) { - return request.getPortalContext(); - } - else if (Principal.class.isAssignableFrom(parameterType)) { - return request.getUserPrincipal(); - } - else if (Locale.class == parameterType) { - return request.getLocale(); - } - else if (InputStream.class.isAssignableFrom(parameterType)) { - if (!(request instanceof ClientDataRequest)) { - throw new IllegalStateException("InputStream can only get obtained for Action/ResourceRequest"); - } - return ((ClientDataRequest) request).getPortletInputStream(); - } - else if (Reader.class.isAssignableFrom(parameterType)) { - if (!(request instanceof ClientDataRequest)) { - throw new IllegalStateException("Reader can only get obtained for Action/ResourceRequest"); - } - return ((ClientDataRequest) request).getReader(); - } - else if (OutputStream.class.isAssignableFrom(parameterType)) { - if (!(response instanceof MimeResponse)) { - throw new IllegalStateException("OutputStream can only get obtained for Render/ResourceResponse"); - } - return ((MimeResponse) response).getPortletOutputStream(); - } - else if (Writer.class.isAssignableFrom(parameterType)) { - if (!(response instanceof MimeResponse)) { - throw new IllegalStateException("Writer can only get obtained for Render/ResourceResponse"); - } - return ((MimeResponse) response).getWriter(); - } - else if (Event.class == parameterType) { - if (!(request instanceof EventRequest)) { - throw new IllegalStateException("Event can only get obtained from EventRequest"); - } - return ((EventRequest) request).getEvent(); - } - else { - return WebArgumentResolver.UNRESOLVED; - } - } - - private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception { - ReflectionUtils.makeAccessible(method); - try { - return method.invoke(target, args); - } - catch (InvocationTargetException ex) { - ReflectionUtils.rethrowException(ex.getTargetException()); - } - throw new IllegalStateException("Should never get here"); - } - - @SuppressWarnings("unchecked") - private ModelAndView getModelAndView(Object returnValue) { - if (returnValue instanceof ModelAndView) { - return (ModelAndView) returnValue; - } - else if (returnValue instanceof Model) { - return new ModelAndView().addAllObjects(((Model) returnValue).asMap()); - } - else if (returnValue instanceof Map) { - return new ModelAndView().addAllObjects((Map) returnValue); - } - else if (returnValue instanceof View) { - return new ModelAndView(returnValue); - } - else if (returnValue instanceof String) { - return new ModelAndView((String) returnValue); - } - else if (returnValue == null) { - return new ModelAndView(); - } - else { - throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java deleted file mode 100644 index ef792dd036..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/DefaultAnnotationHandlerMapping.java +++ /dev/null @@ -1,472 +0,0 @@ -/* - * Copyright 2002-2015 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.annotation; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import javax.portlet.ActionRequest; -import javax.portlet.ClientDataRequest; -import javax.portlet.Event; -import javax.portlet.EventRequest; -import javax.portlet.PortletException; -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; -import javax.portlet.ResourceRequest; -import javax.portlet.WindowState; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -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.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.portlet.bind.PortletRequestBindingException; -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.handler.AbstractMapBasedHandlerMapping; -import org.springframework.web.portlet.handler.PortletRequestMethodNotSupportedException; - -/** - * Implementation of the {@link org.springframework.web.portlet.HandlerMapping} - * interface that maps handlers based on portlet modes expressed through the - * {@link RequestMapping} annotation at the type or method level. - * - *

        Registered by default in {@link org.springframework.web.portlet.DispatcherPortlet}. - * NOTE: If you define custom HandlerMapping beans in your DispatcherPortlet context, - * you need to add a DefaultAnnotationHandlerMapping bean explicitly, since custom - * HandlerMapping beans replace the default mapping strategies. Defining a - * DefaultAnnotationHandlerMapping also allows for registering custom interceptors: - * - *

        - * <bean class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        - *   <property name="interceptors">
        - *     ...
        - *   </property>
        - * </bean>
        - * - * Annotated controllers are usually marked with the {@link Controller} stereotype - * at the type level. This is not strictly necessary when {@link RequestMapping} is - * applied at the type level (since such a handler usually implements the - * {@link org.springframework.web.portlet.mvc.Controller} interface). However, - * {@link Controller} is required for detecting {@link RequestMapping} annotations - * at the method level. - * - *

        NOTE: Method-level mappings are only allowed to narrow the mapping - * expressed at the class level (if any). A portlet mode in combination with specific - * parameter conditions needs to uniquely map onto one specific handler bean, - * not spread across multiple handler beans. It is strongly recommended to - * co-locate related handler methods into the same bean. - * - *

        The {@link AnnotationMethodHandlerAdapter} is responsible for processing - * annotated handler methods, as mapped by this HandlerMapping. For - * {@link RequestMapping} at the type level, specific HandlerAdapters such as - * {@link org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter} apply. - * - * @author Juergen Hoeller - * @since 2.5 - * @see RequestMapping - * @see AnnotationMethodHandlerAdapter - */ -public class DefaultAnnotationHandlerMapping extends AbstractMapBasedHandlerMapping { - - /** - * Calls the {@code registerHandlers} method in addition - * to the superclass's initialization. - * @see #detectHandlers - */ - @Override - public void initApplicationContext() throws BeansException { - super.initApplicationContext(); - detectHandlers(); - } - - /** - * Register all handlers specified in the Portlet mode map for the corresponding modes. - * @throws org.springframework.beans.BeansException if the handler couldn't be registered - */ - protected void detectHandlers() throws BeansException { - ApplicationContext context = getApplicationContext(); - String[] beanNames = context.getBeanNamesForType(Object.class); - for (String beanName : beanNames) { - Class handlerType = context.getType(beanName); - RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class); - if (mapping != null) { - // @RequestMapping found at type level - String[] modeKeys = mapping.value(); - String[] params = mapping.params(); - boolean registerHandlerType = true; - if (modeKeys.length == 0 || params.length == 0) { - registerHandlerType = !detectHandlerMethods(handlerType, beanName, mapping); - } - if (registerHandlerType) { - AbstractParameterMappingPredicate predicate = new TypeLevelMappingPredicate( - params, mapping.headers(), mapping.method()); - for (String modeKey : modeKeys) { - registerHandler(new PortletMode(modeKey), beanName, predicate); - } - } - } - else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) { - detectHandlerMethods(handlerType, beanName, mapping); - } - } - } - - /** - * Derive portlet mode mappings from the handler's method-level mappings. - * @param handlerType the handler type to introspect - * @param beanName the name of the bean introspected - * @param typeMapping the type level mapping (if any) - * @return {@code true} if at least 1 handler method has been registered; - * {@code false} otherwise - */ - protected boolean detectHandlerMethods(Class handlerType, final String beanName, final RequestMapping typeMapping) { - final Set handlersRegistered = new HashSet(1); - Set> handlerTypes = new LinkedHashSet>(); - handlerTypes.add(handlerType); - handlerTypes.addAll(Arrays.asList(handlerType.getInterfaces())); - for (Class currentHandlerType : handlerTypes) { - ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) { - PortletRequestMappingPredicate predicate = null; - String[] modeKeys = new String[0]; - String[] params = new String[0]; - if (typeMapping != null) { - params = StringUtils.mergeStringArrays(typeMapping.params(), params); - } - 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); - RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); - if (actionMapping != null) { - params = StringUtils.mergeStringArrays(params, actionMapping.params()); - predicate = new ActionMappingPredicate(actionMapping.name(), params); - } - else if (renderMapping != null) { - params = StringUtils.mergeStringArrays(params, renderMapping.params()); - predicate = new RenderMappingPredicate(renderMapping.windowState(), params); - } - else if (resourceMapping != null) { - predicate = new ResourceMappingPredicate(resourceMapping.value()); - } - else if (eventMapping != null) { - predicate = new EventMappingPredicate(eventMapping.value()); - } - if (requestMapping != null) { - modeKeys = requestMapping.value(); - if (typeMapping != null) { - if (!PortletAnnotationMappingUtils.validateModeMapping(modeKeys, typeMapping.value())) { - throw new IllegalStateException("Mode mappings conflict between method and type level: " + - Arrays.asList(modeKeys) + " versus " + Arrays.asList(typeMapping.value())); - } - } - params = StringUtils.mergeStringArrays(params, requestMapping.params()); - if (predicate == null) { - predicate = new MethodLevelMappingPredicate(params); - } - } - if (predicate != null) { - if (modeKeys.length == 0) { - if (typeMapping != null) { - modeKeys = typeMapping.value(); - } - if (modeKeys.length == 0) { - throw new IllegalStateException( - "No portlet mode mappings specified - neither at type nor at method level"); - } - } - for (String modeKey : modeKeys) { - registerHandler(new PortletMode(modeKey), beanName, predicate); - handlersRegistered.add(Boolean.TRUE); - } - } - } - }, ReflectionUtils.USER_DECLARED_METHODS); - } - return !handlersRegistered.isEmpty(); - } - - /** - * Uses the current PortletMode as lookup key. - */ - @Override - protected PortletMode getLookupKey(PortletRequest request) throws Exception { - return request.getPortletMode(); - } - - - private interface SpecialRequestTypePredicate { - } - - - private static abstract class AbstractParameterMappingPredicate implements PortletRequestMappingPredicate { - - private final String[] params; - - public AbstractParameterMappingPredicate(String[] params) { - this.params = params; - } - - @Override - public boolean match(PortletRequest request) { - return PortletAnnotationMappingUtils.checkParameters(this.params, request); - } - - protected int compareParams(AbstractParameterMappingPredicate other) { - return new Integer(other.params.length).compareTo(this.params.length); - } - - protected int compareParams(Object other) { - if (other instanceof AbstractParameterMappingPredicate) { - return compareParams((AbstractParameterMappingPredicate) other); - } - return 0; - } - } - - - private static class TypeLevelMappingPredicate extends AbstractParameterMappingPredicate { - - private final String[] headers; - - private final Set methods = new HashSet(); - - public TypeLevelMappingPredicate(String[] params, String[] headers, RequestMethod[] methods) { - super(params); - this.headers = headers; - if (methods != null) { - for (RequestMethod method : methods) { - this.methods.add(method.name()); - } - } - } - - @Override - public void validate(PortletRequest request) throws PortletException { - if (!PortletAnnotationMappingUtils.checkHeaders(this.headers, request)) { - throw new PortletRequestBindingException("Header conditions \"" + - StringUtils.arrayToDelimitedString(this.headers, ", ") + - "\" not met for actual request"); - } - 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)); - } - } - } - - @Override - public int compareTo(PortletRequestMappingPredicate other) { - return (other instanceof SpecialRequestTypePredicate ? -1 : compareParams(other)); - } - } - - - private static class MethodLevelMappingPredicate extends AbstractParameterMappingPredicate { - - public MethodLevelMappingPredicate(String[] params) { - super(params); - } - - @Override - public void validate(PortletRequest request) throws PortletException { - } - - @Override - public int compareTo(PortletRequestMappingPredicate other) { - return (other instanceof SpecialRequestTypePredicate ? 1 : compareParams(other)); - } - } - - - private static class ActionMappingPredicate extends AbstractParameterMappingPredicate implements SpecialRequestTypePredicate { - - private final String actionName; - - public ActionMappingPredicate(String actionName, String[] params) { - super(params); - this.actionName = actionName; - } - - @Override - public boolean match(PortletRequest request) { - return (PortletRequest.ACTION_PHASE.equals(request.getAttribute(PortletRequest.LIFECYCLE_PHASE)) && - ("".equals(this.actionName) || this.actionName.equals(request.getParameter(ActionRequest.ACTION_NAME))) && - super.match(request)); - } - - @Override - public void validate(PortletRequest request) { - } - - @Override - public int compareTo(PortletRequestMappingPredicate other) { - if (other instanceof TypeLevelMappingPredicate) { - return 1; - } - else if (other instanceof ActionMappingPredicate) { - ActionMappingPredicate otherAction = (ActionMappingPredicate) other; - boolean hasActionName = "".equals(this.actionName); - boolean otherHasActionName = "".equals(otherAction.actionName); - if (hasActionName != otherHasActionName) { - return (hasActionName ? -1 : 1); - } - else { - return compareParams(otherAction); - } - } - if (other instanceof SpecialRequestTypePredicate) { - return this.getClass().getName().compareTo(other.getClass().getName()); - } - return -1; - } - } - - - private static class RenderMappingPredicate extends AbstractParameterMappingPredicate implements SpecialRequestTypePredicate{ - - private final WindowState windowState; - - public RenderMappingPredicate(String windowState, String[] params) { - super(params); - this.windowState = ("".equals(windowState) ? null : new WindowState(windowState)); - } - - @Override - public boolean match(PortletRequest request) { - return (PortletRequest.RENDER_PHASE.equals(request.getAttribute(PortletRequest.LIFECYCLE_PHASE)) && - (this.windowState == null || this.windowState.equals(request.getWindowState())) && - super.match(request)); - } - - @Override - public void validate(PortletRequest request) { - } - - @Override - public int compareTo(PortletRequestMappingPredicate other) { - if (other instanceof TypeLevelMappingPredicate) { - return 1; - } - else if (other instanceof RenderMappingPredicate) { - RenderMappingPredicate otherRender = (RenderMappingPredicate) other; - boolean hasWindowState = (this.windowState != null); - boolean otherHasWindowState = (otherRender.windowState != null); - if (hasWindowState != otherHasWindowState) { - return (hasWindowState ? -1 : 1); - } - else { - return compareParams(otherRender); - } - } - if (other instanceof SpecialRequestTypePredicate) { - return this.getClass().getName().compareTo(other.getClass().getName()); - } - return -1; - } - } - - - private static class ResourceMappingPredicate implements PortletRequestMappingPredicate, SpecialRequestTypePredicate { - - private final String resourceId; - - public ResourceMappingPredicate(String resourceId) { - this.resourceId = resourceId; - } - - @Override - public boolean match(PortletRequest request) { - return (PortletRequest.RESOURCE_PHASE.equals(request.getAttribute(PortletRequest.LIFECYCLE_PHASE)) && - ("".equals(this.resourceId) || this.resourceId.equals(((ResourceRequest) request).getResourceID()))); - } - - @Override - public void validate(PortletRequest request) { - } - - @Override - public int compareTo(PortletRequestMappingPredicate other) { - if (other instanceof ResourceMappingPredicate) { - boolean hasResourceId = !"".equals(this.resourceId); - boolean otherHasResourceId = !"".equals(((ResourceMappingPredicate) other).resourceId); - if (hasResourceId != otherHasResourceId) { - return (hasResourceId ? -1 : 1); - } - } - if (other instanceof SpecialRequestTypePredicate) { - return this.getClass().getName().compareTo(other.getClass().getName()); - } - return -1; - } - } - - - private static class EventMappingPredicate implements PortletRequestMappingPredicate, SpecialRequestTypePredicate { - - private final String eventName; - - public EventMappingPredicate(String eventName) { - this.eventName = eventName; - } - - @Override - public boolean match(PortletRequest request) { - if (!PortletRequest.EVENT_PHASE.equals(request.getAttribute(PortletRequest.LIFECYCLE_PHASE))) { - return false; - } - if ("".equals(this.eventName)) { - return true; - } - Event event = ((EventRequest) request).getEvent(); - return (this.eventName.equals(event.getName()) || this.eventName.equals(event.getQName().toString())); - } - - @Override - public void validate(PortletRequest request) { - } - - @Override - public int compareTo(PortletRequestMappingPredicate other) { - if (other instanceof EventMappingPredicate) { - boolean hasEventName = !"".equals(this.eventName); - boolean otherHasEventName = !"".equals(((EventMappingPredicate) other).eventName); - if (hasEventName != otherHasEventName) { - return (hasEventName ? -1 : 1); - } - } - if (other instanceof SpecialRequestTypePredicate) { - return this.getClass().getName().compareTo(other.getClass().getName()); - } - return -1; - } - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationMappingUtils.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationMappingUtils.java deleted file mode 100644 index f1796355cf..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationMappingUtils.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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.annotation; - -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import javax.portlet.ClientDataRequest; -import javax.portlet.PortletRequest; - -import org.springframework.http.MediaType; -import org.springframework.util.ObjectUtils; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.portlet.util.PortletUtils; - -/** - * Helper class for annotation-based request mapping. - * - * @author Juergen Hoeller - * @since 2.5.2 - */ -abstract class PortletAnnotationMappingUtils { - - /** - * 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 - */ - public static boolean validateModeMapping(String[] modes, String[] typeLevelModes) { - if (!ObjectUtils.isEmpty(modes) && !ObjectUtils.isEmpty(typeLevelModes)) { - for (String mode : modes) { - boolean match = false; - for (String typeLevelMode : typeLevelModes) { - if (mode.equalsIgnoreCase(typeLevelMode)) { - match = true; - } - } - if (!match) { - return false; - } - } - } - 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(RequestMethod[] methods, PortletRequest request) { - if (methods.length == 0) { - return true; - } - if (!(request instanceof ClientDataRequest)) { - return false; - } - String method = ((ClientDataRequest) request).getMethod(); - for (RequestMethod candidate : methods) { - if (method.equals(candidate.name())) { - return true; - } - } - return false; - } - - /** - * 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 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 request to check - */ - public static boolean checkParameters(String[] params, PortletRequest request) { - if (!ObjectUtils.isEmpty(params)) { - for (String param : params) { - int separator = param.indexOf('='); - if (separator == -1) { - if (param.startsWith("!")) { - if (PortletUtils.hasSubmitParameter(request, param.substring(1))) { - return false; - } - } - else if (!PortletUtils.hasSubmitParameter(request, param)) { - return false; - } - } - else { - String key = param.substring(0, separator); - String value = param.substring(separator + 1); - if (!value.equals(request.getParameter(key))) { - return false; - } - } - } - } - return true; - } - - /** - * Check whether the given request matches the specified header conditions. - * @param headers the header conditions, following {@link RequestMapping#headers()} - * @param request the current HTTP request to check - */ - public static boolean checkHeaders(String[] headers, PortletRequest request) { - if (!ObjectUtils.isEmpty(headers)) { - for (String header : headers) { - int separator = header.indexOf('='); - if (separator == -1) { - if (header.startsWith("!")) { - if (request.getProperty(header.substring(1)) != null) { - return false; - } - } - else if (request.getProperty(header) == null) { - return false; - } - } - else { - String key = header.substring(0, separator); - String value = header.substring(separator + 1); - if (isMediaTypeHeader(key)) { - List requestMediaTypes = MediaType.parseMediaTypes(request.getProperty(key)); - List valueMediaTypes = MediaType.parseMediaTypes(value); - boolean found = false; - for (Iterator valIter = valueMediaTypes.iterator(); valIter.hasNext() && !found;) { - MediaType valueMediaType = valIter.next(); - for (Iterator reqIter = requestMediaTypes.iterator(); reqIter.hasNext() && !found;) { - MediaType requestMediaType = reqIter.next(); - if (valueMediaType.includes(requestMediaType)) { - found = true; - } - } - - } - if (!found) { - return false; - } - } - else if (!value.equals(request.getProperty(key))) { - return false; - } - } - } - } - return true; - } - - private static boolean isMediaTypeHeader(String headerName) { - return "Accept".equalsIgnoreCase(headerName) || "Content-Type".equalsIgnoreCase(headerName); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/package-info.java deleted file mode 100644 index eeea1da306..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/annotation/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Support package for annotation-based Portlet MVC controllers. - */ -package org.springframework.web.portlet.mvc.annotation; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/package-info.java deleted file mode 100644 index ca742a5aba..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/mvc/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** - * Standard controller implementations for the Portlet MVC framework that comes with - * Spring. Provides various controller styles, including an annotation-based model. - */ -package org.springframework.web.portlet.mvc; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/package-info.java deleted file mode 100644 index b825239ac0..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Provides JSR-286 portlets that integrate with the application context - * infrastructure, and the core interfaces and classes for the Portlet - * variant of Spring's web MVC framework. - */ -package org.springframework.web.portlet; diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java deleted file mode 100644 index a63754b45e..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/PortletUtils.java +++ /dev/null @@ -1,539 +0,0 @@ -/* - * Copyright 2002-2012 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.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletContext; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; -import javax.portlet.ResourceRequest; -import javax.portlet.ResourceResponse; -import javax.portlet.filter.PortletRequestWrapper; -import javax.portlet.filter.PortletResponseWrapper; -import javax.servlet.http.Cookie; - -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; -import org.springframework.web.util.WebUtils; - -/** - * Miscellaneous utilities for portlet applications. - * Used by various framework classes. - * - * @author Juergen Hoeller - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @since 2.0 - */ -public abstract class PortletUtils { - - /** - * Return the temporary directory for the current web application, - * as provided by the portlet container. - * @param portletContext the portlet context of the web application - * @return the File representing the temporary directory - */ - public static File getTempDir(PortletContext portletContext) { - Assert.notNull(portletContext, "PortletContext must not be null"); - return (File) portletContext.getAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE); - } - - /** - * Return the real path of the given path within the web application, - * as provided by the portlet container. - *

        Prepends a slash if the path does not already start with a slash, - * and throws a {@link java.io.FileNotFoundException} if the path cannot - * be resolved to a resource (in contrast to - * {@link javax.portlet.PortletContext#getRealPath PortletContext's {@code getRealPath}}, - * which simply returns {@code null}). - * @param portletContext the portlet context of the web application - * @param path the relative path within the web application - * @return the corresponding real path - * @throws FileNotFoundException if the path cannot be resolved to a resource - * @see javax.portlet.PortletContext#getRealPath - */ - public static String getRealPath(PortletContext portletContext, String path) throws FileNotFoundException { - Assert.notNull(portletContext, "PortletContext must not be null"); - // Interpret location as relative to the web application root directory. - if (!path.startsWith("/")) { - path = "/" + path; - } - String realPath = portletContext.getRealPath(path); - if (realPath == null) { - throw new FileNotFoundException( - "PortletContext resource [" + path + "] cannot be resolved to absolute file path - " + - "web application archive not expanded?"); - } - return realPath; - } - - - /** - * Check the given request for a session attribute of the given name under the - * {@link javax.portlet.PortletSession#PORTLET_SCOPE}. - * Returns {@code null} if there is no session or if the session has no such attribute in that scope. - * Does not create a new session if none has existed before! - * @param request current portlet request - * @param name the name of the session attribute - * @return the value of the session attribute, or {@code null} if not found - */ - public static Object getSessionAttribute(PortletRequest request, String name) { - return getSessionAttribute(request, name, PortletSession.PORTLET_SCOPE); - } - - /** - * Check the given request for a session attribute of the given name in the given scope. - * Returns {@code null} if there is no session or if the session has no such attribute in that scope. - * Does not create a new session if none has existed before! - * @param request current portlet request - * @param name the name of the session attribute - * @param scope session scope of this attribute - * @return the value of the session attribute, or {@code null} if not found - */ - public static Object getSessionAttribute(PortletRequest request, String name, int scope) { - Assert.notNull(request, "Request must not be null"); - PortletSession session = request.getPortletSession(false); - return (session != null ? session.getAttribute(name, scope) : null); - } - - /** - * Check the given request for a session attribute of the given name - * under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}. - * Throws an exception if there is no session or if the session has - * no such attribute in that scope. - *

        Does not create a new session if none has existed before! - * @param request current portlet request - * @param name the name of the session attribute - * @return the value of the session attribute - * @throws IllegalStateException if the session attribute could not be found - */ - public static Object getRequiredSessionAttribute(PortletRequest request, String name) - throws IllegalStateException { - - return getRequiredSessionAttribute(request, name, PortletSession.PORTLET_SCOPE); - } - - /** - * Check the given request for a session attribute of the given name in the given scope. - * Throws an exception if there is no session or if the session has no such attribute - * in that scope. - *

        Does not create a new session if none has existed before! - * @param request current portlet request - * @param name the name of the session attribute - * @param scope session scope of this attribute - * @return the value of the session attribute - * @throws IllegalStateException if the session attribute could not be found - */ - public static Object getRequiredSessionAttribute(PortletRequest request, String name, int scope) - throws IllegalStateException { - Object attr = getSessionAttribute(request, name, scope); - if (attr == null) { - throw new IllegalStateException("No session attribute '" + name + "' found"); - } - return attr; - } - - /** - * Set the session attribute with the given name to the given value under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}. - * Removes the session attribute if value is {@code null}, if a session existed at all. - * Does not create a new session if not necessary! - * @param request current portlet request - * @param name the name of the session attribute - * @param value the value of the session attribute - */ - public static void setSessionAttribute(PortletRequest request, String name, Object value) { - setSessionAttribute(request, name, value, PortletSession.PORTLET_SCOPE); - } - - /** - * Set the session attribute with the given name to the given value in the given scope. - * Removes the session attribute if value is {@code null}, if a session existed at all. - * Does not create a new session if not necessary! - * @param request current portlet request - * @param name the name of the session attribute - * @param value the value of the session attribute - * @param scope session scope of this attribute - */ - public static void setSessionAttribute(PortletRequest request, String name, Object value, int scope) { - Assert.notNull(request, "Request must not be null"); - if (value != null) { - request.getPortletSession().setAttribute(name, value, scope); - } - else { - PortletSession session = request.getPortletSession(false); - if (session != null) { - session.removeAttribute(name, scope); - } - } - } - - /** - * Get the specified session attribute under the {@link javax.portlet.PortletSession#PORTLET_SCOPE}, - * creating and setting a new attribute if no existing found. The given class - * needs to have a public no-arg constructor. - * Useful for on-demand state objects in a web tier, like shopping carts. - * @param session current portlet session - * @param name the name of the session attribute - * @param clazz the class to instantiate for a new attribute - * @return the value of the session attribute, newly created if not found - * @throws IllegalArgumentException if the session attribute could not be instantiated - */ - public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz) - throws IllegalArgumentException { - - return getOrCreateSessionAttribute(session, name, clazz, PortletSession.PORTLET_SCOPE); - } - - /** - * Get the specified session attribute in the given scope, - * creating and setting a new attribute if no existing found. The given class - * needs to have a public no-arg constructor. - * Useful for on-demand state objects in a web tier, like shopping carts. - * @param session current portlet session - * @param name the name of the session attribute - * @param clazz the class to instantiate for a new attribute - * @param scope the session scope of this attribute - * @return the value of the session attribute, newly created if not found - * @throws IllegalArgumentException if the session attribute could not be instantiated - */ - public static Object getOrCreateSessionAttribute(PortletSession session, String name, Class clazz, int scope) - throws IllegalArgumentException { - - Assert.notNull(session, "Session must not be null"); - Object sessionObject = session.getAttribute(name, scope); - if (sessionObject == null) { - Assert.notNull(clazz, "Class must not be null if attribute value is to be instantiated"); - try { - sessionObject = clazz.newInstance(); - } - catch (InstantiationException ex) { - throw new IllegalArgumentException( - "Could not instantiate class [" + clazz.getName() + - "] for session attribute '" + name + "': " + ex.getMessage()); - } - catch (IllegalAccessException ex) { - throw new IllegalArgumentException( - "Could not access default constructor of class [" + clazz.getName() + - "] for session attribute '" + name + "': " + ex.getMessage()); - } - session.setAttribute(name, sessionObject, scope); - } - return sessionObject; - } - - /** - * Return the best available mutex for the given session: - * that is, an object to synchronize on for the given session. - *

        Returns the session mutex attribute if available; usually, - * this means that the - * {@link org.springframework.web.util.HttpSessionMutexListener} - * needs to be defined in {@code web.xml}. Falls back to the - * {@link javax.portlet.PortletSession} itself if no mutex attribute found. - *

        The session mutex is guaranteed to be the same object during - * the entire lifetime of the session, available under the key defined - * by the {@link org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE} - * constant. It serves as a safe reference to synchronize on for locking - * on the current session. - *

        In many cases, the {@link javax.portlet.PortletSession} reference - * itself is a safe mutex as well, since it will always be the same - * object reference for the same active logical session. However, this is - * not guaranteed across different servlet containers; the only 100% safe - * way is a session mutex. - * @param session the HttpSession to find a mutex for - * @return the mutex object (never {@code null}) - * @see org.springframework.web.util.WebUtils#SESSION_MUTEX_ATTRIBUTE - * @see org.springframework.web.util.HttpSessionMutexListener - */ - public static Object getSessionMutex(PortletSession session) { - Assert.notNull(session, "Session must not be null"); - Object mutex = session.getAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE, PortletSession.APPLICATION_SCOPE); - if (mutex == null) { - mutex = session; - } - return mutex; - } - - - /** - * Return an appropriate request object of the specified type, if available, - * unwrapping the given request as far as necessary. - * @param request the portlet request to introspect - * @param requiredType the desired type of request object - * @return the matching request object, or {@code null} if none - * of that type is available - */ - @SuppressWarnings("unchecked") - public static T getNativeRequest(PortletRequest request, Class requiredType) { - if (requiredType != null) { - if (requiredType.isInstance(request)) { - return (T) request; - } - else if (request instanceof PortletRequestWrapper) { - return getNativeRequest(((PortletRequestWrapper) request).getRequest(), requiredType); - } - } - return null; - } - - /** - * Return an appropriate response object of the specified type, if available, - * unwrapping the given response as far as necessary. - * @param response the portlet response to introspect - * @param requiredType the desired type of response object - * @return the matching response object, or {@code null} if none - * of that type is available - */ - @SuppressWarnings("unchecked") - public static T getNativeResponse(PortletResponse response, Class requiredType) { - if (requiredType != null) { - if (requiredType.isInstance(response)) { - return (T) response; - } - else if (response instanceof PortletResponseWrapper) { - return getNativeResponse(((PortletResponseWrapper) response).getResponse(), requiredType); - } - } - return null; - } - - /** - * Expose the given Map as request attributes, using the keys as attribute names - * and the values as corresponding attribute values. Keys must be Strings. - * @param request current portlet request - * @param attributes the attributes Map - */ - public static void exposeRequestAttributes(PortletRequest request, Map attributes) { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(attributes, "Attributes Map must not be null"); - for (Map.Entry entry : attributes.entrySet()) { - request.setAttribute(entry.getKey(), entry.getValue()); - } - } - - /** - * Retrieve the first cookie with the given name. Note that multiple - * cookies can have the same name but different paths or domains. - * @param request current portlet request - * @param name cookie name - * @return the first cookie with the given name, or {@code null} if none is found - */ - public static Cookie getCookie(PortletRequest request, String name) { - Assert.notNull(request, "Request must not be null"); - Cookie cookies[] = request.getCookies(); - if (cookies != null) { - for (Cookie cookie : cookies) { - if (name.equals(cookie.getName())) { - return cookie; - } - } - } - return null; - } - - /** - * Check if a specific input type="submit" parameter was sent in the request, - * either via a button (directly with name) or via an image (name + ".x" or - * name + ".y"). - * @param request current portlet request - * @param name name of the parameter - * @return if the parameter was sent - * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES - */ - public static boolean hasSubmitParameter(PortletRequest request, String name) { - return getSubmitParameter(request, name) != null; - } - - /** - * Return the full name of a specific input type="submit" parameter - * if it was sent in the request, either via a button (directly with name) - * or via an image (name + ".x" or name + ".y"). - * @param request current portlet request - * @param name name of the parameter - * @return the actual parameter name with suffix if needed - null if not present - * @see org.springframework.web.util.WebUtils#SUBMIT_IMAGE_SUFFIXES - */ - public static String getSubmitParameter(PortletRequest request, String name) { - Assert.notNull(request, "Request must not be null"); - if (request.getParameter(name) != null) { - return name; - } - for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) { - String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i]; - String parameter = name + suffix; - if (request.getParameter(parameter) != null) { - return parameter; - } - } - return null; - } - - /** - * Return a map containing all parameters with the given prefix. - * Maps single values to String and multiple values to String array. - *

        For example, with a prefix of "spring_", "spring_param1" and - * "spring_param2" result in a Map with "param1" and "param2" as keys. - *

        Similar to portlet - * {@link javax.portlet.PortletRequest#getParameterMap()}, - * but more flexible. - * @param request portlet request in which to look for parameters - * @param prefix the beginning of parameter names - * (if this is {@code null} or the empty string, all parameters will match) - * @return map containing request parameters without the prefix, - * containing either a String or a String array as values - * @see javax.portlet.PortletRequest#getParameterNames - * @see javax.portlet.PortletRequest#getParameterValues - * @see javax.portlet.PortletRequest#getParameterMap - */ - public static Map getParametersStartingWith(PortletRequest request, String prefix) { - Assert.notNull(request, "Request must not be null"); - Enumeration paramNames = request.getParameterNames(); - Map params = new TreeMap(); - if (prefix == null) { - prefix = ""; - } - while (paramNames != null && paramNames.hasMoreElements()) { - String paramName = paramNames.nextElement(); - if ("".equals(prefix) || paramName.startsWith(prefix)) { - String unprefixed = paramName.substring(prefix.length()); - String[] values = request.getParameterValues(paramName); - if (values == null || values.length == 0) { - // Do nothing, no values found at all. - } - else if (values.length > 1) { - params.put(unprefixed, values); - } - else { - params.put(unprefixed, values[0]); - } - } - } - return params; - } - - /** - * Return the target page specified in the request. - * @param request current portlet request - * @param paramPrefix the parameter prefix to check for - * (e.g. "_target" for parameters like "_target1" or "_target2") - * @param currentPage the current page, to be returned as fallback - * if no target page specified - * @return the page specified in the request, or current page if not found - */ - public static int getTargetPage(PortletRequest request, String paramPrefix, int currentPage) { - Enumeration paramNames = request.getParameterNames(); - while (paramNames.hasMoreElements()) { - String paramName = paramNames.nextElement(); - if (paramName.startsWith(paramPrefix)) { - for (int i = 0; i < WebUtils.SUBMIT_IMAGE_SUFFIXES.length; i++) { - String suffix = WebUtils.SUBMIT_IMAGE_SUFFIXES[i]; - if (paramName.endsWith(suffix)) { - paramName = paramName.substring(0, paramName.length() - suffix.length()); - } - } - return Integer.parseInt(paramName.substring(paramPrefix.length())); - } - } - return currentPage; - } - - - /** - * Pass all the action request parameters to the render phase by putting them into - * the action response object. This may not be called when the action will call - * {@link javax.portlet.ActionResponse#sendRedirect sendRedirect}. - * @param request the current action request - * @param response the current action response - * @see javax.portlet.ActionResponse#setRenderParameter - */ - public static void passAllParametersToRenderPhase(ActionRequest request, ActionResponse response) { - try { - Enumeration en = request.getParameterNames(); - while (en.hasMoreElements()) { - String param = en.nextElement(); - String values[] = request.getParameterValues(param); - response.setRenderParameter(param, values); - } - } - catch (IllegalStateException ex) { - // Ignore in case sendRedirect was already set. - } - } - - /** - * Clear all the render parameters from the {@link javax.portlet.ActionResponse}. - * This may not be called when the action will call - * {@link ActionResponse#sendRedirect sendRedirect}. - * @param response the current action response - * @see ActionResponse#setRenderParameters - */ - public static void clearAllRenderParameters(ActionResponse response) { - try { - response.setRenderParameters(new HashMap(0)); - } - catch (IllegalStateException ex) { - // Ignore in case sendRedirect was already set. - } - } - - /** - * Serve the resource as specified in the given request to the given response, - * using the PortletContext's request dispatcher. - *

        This is roughly equivalent to Portlet 2.0 GenericPortlet. - * @param request the current resource request - * @param response the current resource response - * @param context the current Portlet's PortletContext - * @throws PortletException propagated from Portlet API's forward method - * @throws IOException propagated from Portlet API's forward method - */ - public static void serveResource(ResourceRequest request, ResourceResponse response, PortletContext context) - throws PortletException, IOException { - - String id = request.getResourceID(); - if (id != null) { - if (!PortletUtils.isProtectedResource(id)) { - PortletRequestDispatcher rd = context.getRequestDispatcher(id); - if (rd != null) { - rd.forward(request, response); - return; - } - } - response.setProperty(ResourceResponse.HTTP_STATUS_CODE, "404"); - } - } - - /** - * Check whether the specified path indicates a resource in the protected - * WEB-INF or META-INF directories. - * @param path the path to check - */ - private static boolean isProtectedResource(String path) { - return (StringUtils.startsWithIgnoreCase(path, "/WEB-INF") || - StringUtils.startsWithIgnoreCase(path, "/META-INF")); - } - -} diff --git a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/package-info.java b/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/package-info.java deleted file mode 100644 index c91ad0532f..0000000000 --- a/spring-webmvc-portlet/src/main/java/org/springframework/web/portlet/util/package-info.java +++ /dev/null @@ -1,4 +0,0 @@ -/** - * Miscellaneous Portlet utility classes. - */ -package org.springframework.web.portlet.util; diff --git a/spring-webmvc-portlet/src/main/java/overview.html b/spring-webmvc-portlet/src/main/java/overview.html deleted file mode 100644 index 9f31873b6b..0000000000 --- a/spring-webmvc-portlet/src/main/java/overview.html +++ /dev/null @@ -1,7 +0,0 @@ - - -

        -Spring's MVC framework in its Portlet API version. Includes common Portlet support packages. -

        - - \ No newline at end of file diff --git a/spring-webmvc-portlet/src/main/resources/org/springframework/web/portlet/DispatcherPortlet.properties b/spring-webmvc-portlet/src/main/resources/org/springframework/web/portlet/DispatcherPortlet.properties deleted file mode 100644 index 35e056826c..0000000000 --- a/spring-webmvc-portlet/src/main/resources/org/springframework/web/portlet/DispatcherPortlet.properties +++ /dev/null @@ -1,12 +0,0 @@ -# Default implementation classes for DispatcherPortlet's strategy interfaces. -# Used as fallback when no matching beans are found in the DispatcherPortlet context. -# Not meant to be customized by application developers. - -org.springframework.web.portlet.HandlerMapping=org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping - -org.springframework.web.portlet.HandlerAdapter=org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter,\ - org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter - -org.springframework.web.portlet.HandlerExceptionResolver=org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - -org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/ACATester.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/ACATester.java deleted file mode 100644 index c6a63ddb62..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/ACATester.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import java.util.Locale; - -public class ACATester implements ApplicationContextAware { - - private ApplicationContext ac; - - @Override - public void setApplicationContext(ApplicationContext ctx) throws ApplicationContextException { - // check reinitialization - if (this.ac != null) { - throw new IllegalStateException("Already initialized"); - } - - // check message source availability - if (ctx != null) { - try { - ctx.getMessage("code1", null, Locale.getDefault()); - } - catch (NoSuchMessageException ex) { - // expected - } - } - - this.ac = ctx; - } - - public ApplicationContext getApplicationContext() { - return ac; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatBroadcasts.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatBroadcasts.java deleted file mode 100644 index f4454c64da..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatBroadcasts.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -/** - * @author Juergen Hoeller - */ -public class BeanThatBroadcasts implements ApplicationContextAware { - - public ApplicationContext applicationContext; - - public int receivedCount; - - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - if (applicationContext.getDisplayName().indexOf("listener") != -1) { - applicationContext.getBean("listener"); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java deleted file mode 100644 index d6f4b6ab91..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/BeanThatListens.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import java.util.Map; - -/** - * A stub {@link ApplicationListener}. - * - * @author Thomas Risberg - * @author Juergen Hoeller - */ -public class BeanThatListens implements ApplicationListener { - - private BeanThatBroadcasts beanThatBroadcasts; - - private int eventCount; - - - public BeanThatListens() { - } - - public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) { - this.beanThatBroadcasts = beanThatBroadcasts; - Map beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class); - if (!beans.isEmpty()) { - throw new IllegalStateException("Shouldn't have found any BeanThatListens instances"); - } - } - - - @Override - public void onApplicationEvent(ApplicationEvent event) { - eventCount++; - if (beanThatBroadcasts != null) { - beanThatBroadcasts.receivedCount++; - } - } - - public int getEventCount() { - return eventCount; - } - - public void zero() { - eventCount = 0; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java deleted file mode 100644 index 37d4c9715f..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.springframework.context; - - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.tests.sample.beans.LifecycleBean; - -/** - * Simple bean to test ApplicationContext lifecycle methods for beans - * - * @author Colin Sampaleanu - * @since 03.07.2004 - */ -public class LifecycleContextBean extends LifecycleBean implements ApplicationContextAware { - - protected ApplicationContext owningContext; - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - super.setBeanFactory(beanFactory); - if (this.owningContext != null) - throw new RuntimeException("Factory called setBeanFactory after setApplicationContext"); - } - - @Override - public void afterPropertiesSet() { - super.afterPropertiesSet(); - if (this.owningContext == null) - throw new RuntimeException("Factory didn't call setAppliationContext before afterPropertiesSet on lifecycle bean"); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - if (this.owningFactory == null) - throw new RuntimeException("Factory called setApplicationContext before setBeanFactory"); - - this.owningContext = applicationContext; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java deleted file mode 100644 index 0cc1979022..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/TestListener.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -/** - * Listener that maintains a global count of events. - * - * @author Rod Johnson - * @since January 21, 2001 - */ -public class TestListener implements ApplicationListener { - - private int eventCount; - - public int getEventCount() { - return eventCount; - } - - public void zeroCounter() { - eventCount = 0; - } - - @Override - public void onApplicationEvent(ApplicationEvent e) { - ++eventCount; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionRequest.java deleted file mode 100644 index a687ccb671..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionRequest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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.mock.web.portlet; - -import javax.portlet.ActionRequest; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; - -/** - * Mock implementation of the {@link javax.portlet.ActionRequest} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockActionRequest extends MockClientDataRequest implements ActionRequest { - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - * @see org.springframework.mock.web.portlet.MockPortletContext - */ - public MockActionRequest() { - super(); - } - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param actionName the name of the action to trigger - */ - public MockActionRequest(String actionName) { - super(); - setParameter(ActionRequest.ACTION_NAME, actionName); - } - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param portletMode the mode that the portlet runs in - */ - public MockActionRequest(PortletMode portletMode) { - super(); - setPortletMode(portletMode); - } - - /** - * Create a new MockActionRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockActionRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockActionRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockActionRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - @Override - protected String getLifecyclePhase() { - return ACTION_PHASE; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionResponse.java deleted file mode 100644 index 423cbb0c34..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockActionResponse.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import java.util.Map; -import javax.portlet.ActionResponse; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletModeException; -import javax.portlet.WindowState; -import javax.portlet.WindowStateException; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.ActionResponse} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockActionResponse extends MockStateAwareResponse implements ActionResponse { - - private boolean redirectAllowed = true; - - private String redirectedUrl; - - - /** - * Create a new MockActionResponse with a default {@link MockPortalContext}. - * @see MockPortalContext - */ - public MockActionResponse() { - super(); - } - - /** - * Create a new MockActionResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockActionResponse(PortalContext portalContext) { - super(portalContext); - } - - - @Override - public void setWindowState(WindowState windowState) throws WindowStateException { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set WindowState after sendRedirect has been called"); - } - super.setWindowState(windowState); - this.redirectAllowed = false; - } - - @Override - public void setPortletMode(PortletMode portletMode) throws PortletModeException { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set PortletMode after sendRedirect has been called"); - } - super.setPortletMode(portletMode); - this.redirectAllowed = false; - } - - @Override - public void setRenderParameters(Map parameters) { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called"); - } - super.setRenderParameters(parameters); - this.redirectAllowed = false; - } - - @Override - public void setRenderParameter(String key, String value) { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called"); - } - super.setRenderParameter(key, value); - this.redirectAllowed = false; - } - - @Override - public void setRenderParameter(String key, String[] values) { - if (this.redirectedUrl != null) { - throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called"); - } - super.setRenderParameter(key, values); - this.redirectAllowed = false; - } - - @Override - public void sendRedirect(String location) throws IOException { - if (!this.redirectAllowed) { - throw new IllegalStateException( - "Cannot call sendRedirect after windowState, portletMode, or renderParameters have been set"); - } - Assert.notNull(location, "Redirect URL must not be null"); - this.redirectedUrl = location; - } - - @Override - public void sendRedirect(String location, String renderUrlParamName) throws IOException { - sendRedirect(location); - if (renderUrlParamName != null) { - setRenderParameter(renderUrlParamName, location); - } - } - - public String getRedirectedUrl() { - return this.redirectedUrl; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockBaseURL.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockBaseURL.java deleted file mode 100644 index 28662358c0..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockBaseURL.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import javax.portlet.BaseURL; -import javax.portlet.PortletSecurityException; - -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * Mock implementation of the {@link javax.portlet.BaseURL} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public abstract class MockBaseURL implements BaseURL { - - public static final String URL_TYPE_RENDER = "render"; - - public static final String URL_TYPE_ACTION = "action"; - - private static final String ENCODING = "UTF-8"; - - - protected final Map parameters = new LinkedHashMap(); - - private boolean secure = false; - - private final Map properties = new LinkedHashMap(); - - - //--------------------------------------------------------------------- - // BaseURL methods - //--------------------------------------------------------------------- - - @Override - public void setParameter(String key, String value) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(value, "Parameter value must not be null"); - this.parameters.put(key, new String[] {value}); - } - - @Override - public void setParameter(String key, String[] values) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(values, "Parameter values must not be null"); - this.parameters.put(key, values); - } - - @Override - public void setParameters(Map parameters) { - Assert.notNull(parameters, "Parameters Map must not be null"); - this.parameters.clear(); - this.parameters.putAll(parameters); - } - - public Set getParameterNames() { - return this.parameters.keySet(); - } - - public String getParameter(String name) { - String[] arr = this.parameters.get(name); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public String[] getParameterValues(String name) { - return this.parameters.get(name); - } - - @Override - public Map getParameterMap() { - return Collections.unmodifiableMap(this.parameters); - } - - @Override - public void setSecure(boolean secure) throws PortletSecurityException { - this.secure = secure; - } - - public boolean isSecure() { - return this.secure; - } - - @Override - public void write(Writer out) throws IOException { - out.write(toString()); - } - - @Override - public void write(Writer out, boolean escapeXML) throws IOException { - out.write(toString()); - } - - @Override - public void addProperty(String key, String value) { - String[] values = this.properties.get(key); - if (values != null) { - this.properties.put(key, StringUtils.addStringToArray(values, value)); - } - else { - this.properties.put(key, new String[] {value}); - } - } - - @Override - public void setProperty(String key, String value) { - this.properties.put(key, new String[] {value}); - } - - public Map getProperties() { - return Collections.unmodifiableMap(this.properties); - } - - - protected String encodeParameter(String name, String value) { - try { - return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING); - } - catch (UnsupportedEncodingException ex) { - return null; - } - } - - protected String encodeParameter(String name, String[] values) { - try { - StringBuilder sb = new StringBuilder(); - for (int i = 0, n = values.length; i < n; i++) { - sb.append(i > 0 ? ";" : "").append(URLEncoder.encode(name, ENCODING)).append("=") - .append(URLEncoder.encode(values[i], ENCODING)); - } - return sb.toString(); - } - catch (UnsupportedEncodingException ex) { - return null; - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockCacheControl.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockCacheControl.java deleted file mode 100644 index 109133a2b6..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockCacheControl.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.CacheControl; - -/** - * Mock implementation of the {@link javax.portlet.CacheControl} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockCacheControl implements CacheControl { - - private int expirationTime = 0; - - private boolean publicScope = false; - - private String etag; - - private boolean useCachedContent = false; - - - @Override - public int getExpirationTime() { - return this.expirationTime; - } - - @Override - public void setExpirationTime(int time) { - this.expirationTime = time; - } - - @Override - public boolean isPublicScope() { - return this.publicScope; - } - - @Override - public void setPublicScope(boolean publicScope) { - this.publicScope = publicScope; - } - - @Override - public String getETag() { - return this.etag; - } - - @Override - public void setETag(String token) { - this.etag = token; - } - - @Override - public boolean useCachedContent() { - return this.useCachedContent; - } - - @Override - public void setUseCachedContent(boolean useCachedContent) { - this.useCachedContent = useCachedContent; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockClientDataRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockClientDataRequest.java deleted file mode 100644 index beccbcf59a..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockClientDataRequest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.UnsupportedEncodingException; -import javax.portlet.ClientDataRequest; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; - -/** - * Mock implementation of the {@link javax.portlet.ClientDataRequest} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockClientDataRequest extends MockPortletRequest implements ClientDataRequest { - - private String characterEncoding; - - private byte[] content; - - private String contentType; - - private String method; - - - /** - * Create a new MockClientDataRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - * @see org.springframework.mock.web.portlet.MockPortletContext - */ - public MockClientDataRequest() { - super(); - } - - /** - * Create a new MockClientDataRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockClientDataRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockClientDataRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockClientDataRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - public void setContent(byte[] content) { - this.content = content; - } - - @Override - public InputStream getPortletInputStream() throws IOException { - if (this.content != null) { - return new ByteArrayInputStream(this.content); - } - else { - return null; - } - } - - @Override - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - } - - @Override - public BufferedReader getReader() throws UnsupportedEncodingException { - if (this.content != null) { - InputStream sourceStream = new ByteArrayInputStream(this.content); - Reader sourceReader = (this.characterEncoding != null) ? - new InputStreamReader(sourceStream, this.characterEncoding) : new InputStreamReader(sourceStream); - return new BufferedReader(sourceReader); - } - else { - return null; - } - } - - @Override - public String getCharacterEncoding() { - return this.characterEncoding; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @Override - public String getContentType() { - return this.contentType; - } - - @Override - public int getContentLength() { - return (this.content != null ? content.length : -1); - } - - public void setMethod(String method) { - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEvent.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEvent.java deleted file mode 100644 index daa15e5156..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEvent.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.Serializable; -import javax.portlet.Event; -import javax.xml.namespace.QName; - -/** - * Mock implementation of the {@link javax.portlet.Event} interface. - * - * @author Juergen Hoeller - * @since 3.0 - * @see MockEventRequest - */ -public class MockEvent implements Event { - - private final QName name; - - private final Serializable value; - - - /** - * Create a new MockEvent with the given name. - * @param name the name of the event - */ - public MockEvent(QName name) { - this.name = name; - this.value = null; - } - - /** - * Create a new MockEvent with the given name and value. - * @param name the name of the event - * @param value the associated payload of the event - */ - public MockEvent(QName name, Serializable value) { - this.name = name; - this.value = value; - } - - /** - * Create a new MockEvent with the given name. - * @param name the name of the event - */ - public MockEvent(String name) { - this.name = new QName(name); - this.value = null; - } - - /** - * Create a new MockEvent with the given name and value. - * @param name the name of the event - * @param value the associated payload of the event - */ - public MockEvent(String name, Serializable value) { - this.name = new QName(name); - this.value = value; - } - - - @Override - public QName getQName() { - return this.name; - } - - @Override - public String getName() { - return this.name.getLocalPart(); - } - - @Override - public Serializable getValue() { - return this.value; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventRequest.java deleted file mode 100644 index d29d7865c4..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventRequest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.Event; -import javax.portlet.EventRequest; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; - -/** - * Mock implementation of the {@link javax.portlet.EventRequest} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockEventRequest extends MockPortletRequest implements EventRequest { - - private final Event event; - - private String method; - - - /** - * Create a new MockEventRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param event the event that this request wraps - * @see MockEvent - */ - public MockEventRequest(Event event) { - super(); - this.event = event; - } - - /** - * Create a new MockEventRequest with a default {@link MockPortalContext}. - * @param event the event that this request wraps - * @param portletContext the PortletContext that the request runs in - * @see MockEvent - */ - public MockEventRequest(Event event, PortletContext portletContext) { - super(portletContext); - this.event = event; - } - - /** - * Create a new MockEventRequest. - * @param event the event that this request wraps - * @param portalContext the PortletContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockEventRequest(Event event, PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - this.event = event; - } - - - @Override - protected String getLifecyclePhase() { - return EVENT_PHASE; - } - - @Override - public Event getEvent() { - return this.event; - } - - public void setMethod(String method) { - this.method = method; - } - - @Override - public String getMethod() { - return this.method; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventResponse.java deleted file mode 100644 index 1114d0081b..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockEventResponse.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.EventRequest; -import javax.portlet.EventResponse; - -/** - * Mock implementation of the {@link javax.portlet.EventResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockEventResponse extends MockStateAwareResponse implements EventResponse { - - @Override - public void setRenderParameters(EventRequest request) { - setRenderParameters(request.getParameterMap()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMimeResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMimeResponse.java deleted file mode 100644 index 0a48975f69..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMimeResponse.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Locale; -import javax.portlet.CacheControl; -import javax.portlet.MimeResponse; -import javax.portlet.PortalContext; -import javax.portlet.PortletRequest; -import javax.portlet.PortletURL; -import javax.portlet.ResourceURL; - -import org.springframework.util.CollectionUtils; -import org.springframework.web.util.WebUtils; - -/** - * Mock implementation of the {@link javax.portlet.MimeResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockMimeResponse extends MockPortletResponse implements MimeResponse { - - private PortletRequest request; - - private String contentType; - - private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; - - private PrintWriter writer; - - private Locale locale = Locale.getDefault(); - - private int bufferSize = 4096; - - private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - - private final CacheControl cacheControl = new MockCacheControl(); - - private boolean committed; - - private String includedUrl; - - private String forwardedUrl; - - - /** - * Create a new MockMimeResponse with a default {@link MockPortalContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - */ - public MockMimeResponse() { - super(); - } - - /** - * Create a new MockMimeResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockMimeResponse(PortalContext portalContext) { - super(portalContext); - } - - /** - * Create a new MockMimeResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - * @param request the corresponding render/resource request that this response - * is being generated for - */ - public MockMimeResponse(PortalContext portalContext, PortletRequest request) { - super(portalContext); - this.request = request; - } - - - //--------------------------------------------------------------------- - // RenderResponse methods - //--------------------------------------------------------------------- - - @Override - public void setContentType(String contentType) { - if (this.request != null) { - Enumeration supportedTypes = this.request.getResponseContentTypes(); - if (!CollectionUtils.contains(supportedTypes, contentType)) { - throw new IllegalArgumentException("Content type [" + contentType + "] not in supported list: " + - Collections.list(supportedTypes)); - } - } - this.contentType = contentType; - } - - @Override - public String getContentType() { - return this.contentType; - } - - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - } - - @Override - public String getCharacterEncoding() { - return this.characterEncoding; - } - - @Override - public PrintWriter getWriter() throws UnsupportedEncodingException { - if (this.writer == null) { - Writer targetWriter = (this.characterEncoding != null - ? new OutputStreamWriter(this.outputStream, this.characterEncoding) - : new OutputStreamWriter(this.outputStream)); - this.writer = new PrintWriter(targetWriter); - } - return this.writer; - } - - public byte[] getContentAsByteArray() { - flushBuffer(); - return this.outputStream.toByteArray(); - } - - public String getContentAsString() throws UnsupportedEncodingException { - flushBuffer(); - return (this.characterEncoding != null) - ? this.outputStream.toString(this.characterEncoding) - : this.outputStream.toString(); - } - - public void setLocale(Locale locale) { - this.locale = locale; - } - - @Override - public Locale getLocale() { - return this.locale; - } - - @Override - public void setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - } - - @Override - public int getBufferSize() { - return this.bufferSize; - } - - @Override - public void flushBuffer() { - if (this.writer != null) { - this.writer.flush(); - } - if (this.outputStream != null) { - try { - this.outputStream.flush(); - } - catch (IOException ex) { - throw new IllegalStateException("Could not flush OutputStream: " + ex.getMessage()); - } - } - this.committed = true; - } - - @Override - public void resetBuffer() { - if (this.committed) { - throw new IllegalStateException("Cannot reset buffer - response is already committed"); - } - this.outputStream.reset(); - } - - public void setCommitted(boolean committed) { - this.committed = committed; - } - - @Override - public boolean isCommitted() { - return this.committed; - } - - @Override - public void reset() { - resetBuffer(); - this.characterEncoding = null; - this.contentType = null; - this.locale = null; - } - - @Override - public OutputStream getPortletOutputStream() throws IOException { - return this.outputStream; - } - - @Override - public PortletURL createRenderURL() { - return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_RENDER); - } - - @Override - public PortletURL createActionURL() { - return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_ACTION); - } - - @Override - public ResourceURL createResourceURL() { - return new MockResourceURL(); - } - - @Override - public CacheControl getCacheControl() { - return this.cacheControl; - } - - - //--------------------------------------------------------------------- - // Methods for MockPortletRequestDispatcher - //--------------------------------------------------------------------- - - public void setIncludedUrl(String includedUrl) { - this.includedUrl = includedUrl; - } - - public String getIncludedUrl() { - return this.includedUrl; - } - - public void setForwardedUrl(String forwardedUrl) { - this.forwardedUrl = forwardedUrl; - } - - public String getForwardedUrl() { - return this.forwardedUrl; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java deleted file mode 100644 index e269a621e1..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockMultipartActionRequest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.springframework.util.Assert; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.portlet.multipart.MultipartActionRequest; - -/** - * Mock implementation of the - * {@link org.springframework.web.portlet.multipart.MultipartActionRequest} interface. - * - *

        Useful for testing application controllers that access multipart uploads. - * The {@link org.springframework.mock.web.MockMultipartFile} can be used to - * populate these mock requests with files. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @since 2.0 - * @see org.springframework.mock.web.MockMultipartFile - */ -public class MockMultipartActionRequest extends MockActionRequest implements MultipartActionRequest { - - private final MultiValueMap multipartFiles = - new LinkedMultiValueMap(); - - - /** - * Add a file to this request. The parameter name from the multipart - * form is taken from the {@link org.springframework.web.multipart.MultipartFile#getName()}. - * @param file multipart file to be added - */ - public void addFile(MultipartFile file) { - Assert.notNull(file, "MultipartFile must not be null"); - this.multipartFiles.add(file.getName(), file); - } - - @Override - public Iterator getFileNames() { - return this.multipartFiles.keySet().iterator(); - } - - @Override - public MultipartFile getFile(String name) { - return this.multipartFiles.getFirst(name); - } - - @Override - public List getFiles(String name) { - List multipartFiles = this.multipartFiles.get(name); - if (multipartFiles != null) { - return multipartFiles; - } - else { - return Collections.emptyList(); - } - } - - @Override - public Map getFileMap() { - return this.multipartFiles.toSingleValueMap(); - } - - @Override - public MultiValueMap getMultiFileMap() { - return new LinkedMultiValueMap(this.multipartFiles); - } - - @Override - public String getMultipartContentType(String paramOrFileName) { - MultipartFile file = getFile(paramOrFileName); - if (file != null) { - return file.getContentType(); - } - else { - return null; - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortalContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortalContext.java deleted file mode 100644 index 824df6f70d..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortalContext.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.WindowState; - -/** - * Mock implementation of the {@link javax.portlet.PortalContext} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortalContext implements PortalContext { - - private final Map properties = new HashMap(); - - private final List portletModes; - - private final List windowStates; - - - /** - * Create a new MockPortalContext - * with default PortletModes (VIEW, EDIT, HELP) - * and default WindowStates (NORMAL, MAXIMIZED, MINIMIZED). - * @see javax.portlet.PortletMode - * @see javax.portlet.WindowState - */ - public MockPortalContext() { - this.portletModes = new ArrayList(3); - this.portletModes.add(PortletMode.VIEW); - this.portletModes.add(PortletMode.EDIT); - this.portletModes.add(PortletMode.HELP); - - this.windowStates = new ArrayList(3); - this.windowStates.add(WindowState.NORMAL); - this.windowStates.add(WindowState.MAXIMIZED); - this.windowStates.add(WindowState.MINIMIZED); - } - - /** - * Create a new MockPortalContext with the given PortletModes and WindowStates. - * @param supportedPortletModes the List of supported PortletMode instances - * @param supportedWindowStates the List of supported WindowState instances - * @see javax.portlet.PortletMode - * @see javax.portlet.WindowState - */ - public MockPortalContext(List supportedPortletModes, List supportedWindowStates) { - this.portletModes = new ArrayList(supportedPortletModes); - this.windowStates = new ArrayList(supportedWindowStates); - } - - - @Override - public String getPortalInfo() { - return "MockPortal/1.0"; - } - - public void setProperty(String name, String value) { - this.properties.put(name, value); - } - - @Override - public String getProperty(String name) { - return this.properties.get(name); - } - - @Override - public Enumeration getPropertyNames() { - return Collections.enumeration(this.properties.keySet()); - } - - @Override - public Enumeration getSupportedPortletModes() { - return Collections.enumeration(this.portletModes); - } - - @Override - public Enumeration getSupportedWindowStates() { - return Collections.enumeration(this.windowStates); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletConfig.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletConfig.java deleted file mode 100644 index cf7f48bb17..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletConfig.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.Set; -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletConfig} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletConfig implements PortletConfig { - - private final PortletContext portletContext; - - private final String portletName; - - private final Map resourceBundles = new HashMap(); - - private final Map initParameters = new LinkedHashMap(); - - private final Set publicRenderParameterNames = new LinkedHashSet(); - - private String defaultNamespace = XMLConstants.NULL_NS_URI; - - private final Set publishingEventQNames = new LinkedHashSet(); - - private final Set processingEventQNames = new LinkedHashSet(); - - private final Set supportedLocales = new LinkedHashSet(); - - private final Map containerRuntimeOptions = new LinkedHashMap(); - - - /** - * Create a new MockPortletConfig with a default {@link MockPortletContext}. - */ - public MockPortletConfig() { - this(null, ""); - } - - /** - * Create a new MockPortletConfig with a default {@link MockPortletContext}. - * @param portletName the name of the portlet - */ - public MockPortletConfig(String portletName) { - this(null, portletName); - } - - /** - * Create a new MockPortletConfig. - * @param portletContext the PortletContext that the portlet runs in - */ - public MockPortletConfig(PortletContext portletContext) { - this(portletContext, ""); - } - - /** - * Create a new MockPortletConfig. - * @param portletContext the PortletContext that the portlet runs in - * @param portletName the name of the portlet - */ - public MockPortletConfig(PortletContext portletContext, String portletName) { - this.portletContext = (portletContext != null ? portletContext : new MockPortletContext()); - this.portletName = portletName; - } - - - @Override - public String getPortletName() { - return this.portletName; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - public void setResourceBundle(Locale locale, ResourceBundle resourceBundle) { - Assert.notNull(locale, "Locale must not be null"); - this.resourceBundles.put(locale, resourceBundle); - } - - @Override - public ResourceBundle getResourceBundle(Locale locale) { - Assert.notNull(locale, "Locale must not be null"); - return this.resourceBundles.get(locale); - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - - public void addPublicRenderParameterName(String name) { - this.publicRenderParameterNames.add(name); - } - - @Override - public Enumeration getPublicRenderParameterNames() { - return Collections.enumeration(this.publicRenderParameterNames); - } - - public void setDefaultNamespace(String defaultNamespace) { - this.defaultNamespace = defaultNamespace; - } - - @Override - public String getDefaultNamespace() { - return this.defaultNamespace; - } - - public void addPublishingEventQName(QName name) { - this.publishingEventQNames.add(name); - } - - @Override - public Enumeration getPublishingEventQNames() { - return Collections.enumeration(this.publishingEventQNames); - } - - public void addProcessingEventQName(QName name) { - this.processingEventQNames.add(name); - } - - @Override - public Enumeration getProcessingEventQNames() { - return Collections.enumeration(this.processingEventQNames); - } - - public void addSupportedLocale(Locale locale) { - this.supportedLocales.add(locale); - } - - @Override - public Enumeration getSupportedLocales() { - return Collections.enumeration(this.supportedLocales); - } - - public void addContainerRuntimeOption(String key, String value) { - this.containerRuntimeOptions.put(key, new String[] {value}); - } - - public void addContainerRuntimeOption(String key, String[] values) { - this.containerRuntimeOptions.put(key, values); - } - - @Override - public Map getContainerRuntimeOptions() { - return Collections.unmodifiableMap(this.containerRuntimeOptions); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletContext.java deleted file mode 100644 index 902991ab98..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletContext.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequestDispatcher; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.util.Assert; -import org.springframework.web.util.WebUtils; - -/** - * Mock implementation of the {@link javax.portlet.PortletContext} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletContext implements PortletContext { - - private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir"; - - - private final Log logger = LogFactory.getLog(getClass()); - - private final String resourceBasePath; - - private final ResourceLoader resourceLoader; - - private final Map attributes = new LinkedHashMap(); - - private final Map initParameters = new LinkedHashMap(); - - private String portletContextName = "MockPortletContext"; - - private Set containerRuntimeOptions = new LinkedHashSet(); - - - /** - * Create a new MockPortletContext with no base path and a - * DefaultResourceLoader (i.e. the classpath root as WAR root). - * @see org.springframework.core.io.DefaultResourceLoader - */ - public MockPortletContext() { - this("", null); - } - - /** - * Create a new MockPortletContext using a DefaultResourceLoader. - * @param resourceBasePath the WAR root directory (should not end with a slash) - * @see org.springframework.core.io.DefaultResourceLoader - */ - public MockPortletContext(String resourceBasePath) { - this(resourceBasePath, null); - } - - /** - * Create a new MockPortletContext, using the specified ResourceLoader - * and no base path. - * @param resourceLoader the ResourceLoader to use (or null for the default) - */ - public MockPortletContext(ResourceLoader resourceLoader) { - this("", resourceLoader); - } - - /** - * Create a new MockPortletContext. - * @param resourceBasePath the WAR root directory (should not end with a slash) - * @param resourceLoader the ResourceLoader to use (or null for the default) - */ - public MockPortletContext(String resourceBasePath, ResourceLoader resourceLoader) { - this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : ""); - this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); - - // Use JVM temp dir as PortletContext temp dir. - String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY); - if (tempDir != null) { - this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir)); - } - } - - /** - * Build a full resource location for the given path, - * prepending the resource base path of this MockPortletContext. - * @param path the path as specified - * @return the full resource path - */ - protected String getResourceLocation(String path) { - if (!path.startsWith("/")) { - path = "/" + path; - } - return this.resourceBasePath + path; - } - - - @Override - public String getServerInfo() { - return "MockPortal/1.0"; - } - - @Override - public PortletRequestDispatcher getRequestDispatcher(String path) { - if (!path.startsWith("/")) { - throw new IllegalArgumentException( - "PortletRequestDispatcher path at PortletContext level must start with '/'"); - } - return new MockPortletRequestDispatcher(path); - } - - @Override - public PortletRequestDispatcher getNamedDispatcher(String path) { - return null; - } - - @Override - public InputStream getResourceAsStream(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getInputStream(); - } - catch (IOException ex) { - logger.info("Couldn't open InputStream for " + resource, ex); - return null; - } - } - - @Override - public int getMajorVersion() { - return 2; - } - - @Override - public int getMinorVersion() { - return 0; - } - - @Override - public String getMimeType(String filePath) { - return null; - } - - @Override - public String getRealPath(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getFile().getAbsolutePath(); - } - catch (IOException ex) { - logger.info("Couldn't determine real path of resource " + resource, ex); - return null; - } - } - - @Override - public Set getResourcePaths(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - File file = resource.getFile(); - String[] fileList = file.list(); - String prefix = (path.endsWith("/") ? path : path + "/"); - Set resourcePaths = new HashSet(fileList.length); - for (String fileEntry : fileList) { - resourcePaths.add(prefix + fileEntry); - } - return resourcePaths; - } - catch (IOException ex) { - logger.info("Couldn't get resource paths for " + resource, ex); - return null; - } - } - - @Override - public URL getResource(String path) throws MalformedURLException { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getURL(); - } - catch (IOException ex) { - logger.info("Couldn't get URL for " + resource, ex); - return null; - } - } - - @Override - public Object getAttribute(String name) { - return this.attributes.get(name); - } - - @Override - public Enumeration getAttributeNames() { - return Collections.enumeration(this.attributes.keySet()); - } - - @Override - public void setAttribute(String name, Object value) { - if (value != null) { - this.attributes.put(name, value); - } - else { - this.attributes.remove(name); - } - } - - @Override - public void removeAttribute(String name) { - this.attributes.remove(name); - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - - @Override - public void log(String message) { - logger.info(message); - } - - @Override - public void log(String message, Throwable t) { - logger.info(message, t); - } - - public void setPortletContextName(String portletContextName) { - this.portletContextName = portletContextName; - } - - @Override - public String getPortletContextName() { - return this.portletContextName; - } - - public void addContainerRuntimeOption(String key) { - this.containerRuntimeOptions.add(key); - } - - @Override - public Enumeration getContainerRuntimeOptions() { - return Collections.enumeration(this.containerRuntimeOptions); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletPreferences.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletPreferences.java deleted file mode 100644 index fc281fc16b..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletPreferences.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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.mock.web.portlet; - -import java.io.IOException; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortletPreferences; -import javax.portlet.PreferencesValidator; -import javax.portlet.ReadOnlyException; -import javax.portlet.ValidatorException; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletPreferences} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletPreferences implements PortletPreferences { - - private PreferencesValidator preferencesValidator; - - private final Map preferences = new LinkedHashMap(); - - private final Set readOnly = new HashSet(); - - - public void setReadOnly(String key, boolean readOnly) { - Assert.notNull(key, "Key must not be null"); - if (readOnly) { - this.readOnly.add(key); - } - else { - this.readOnly.remove(key); - } - } - - @Override - public boolean isReadOnly(String key) { - Assert.notNull(key, "Key must not be null"); - return this.readOnly.contains(key); - } - - @Override - public String getValue(String key, String def) { - Assert.notNull(key, "Key must not be null"); - String[] values = this.preferences.get(key); - return (values != null && values.length > 0 ? values[0] : def); - } - - @Override - public String[] getValues(String key, String[] def) { - Assert.notNull(key, "Key must not be null"); - String[] values = this.preferences.get(key); - return (values != null && values.length > 0 ? values : def); - } - - @Override - public void setValue(String key, String value) throws ReadOnlyException { - setValues(key, new String[] {value}); - } - - @Override - public void setValues(String key, String[] values) throws ReadOnlyException { - Assert.notNull(key, "Key must not be null"); - if (isReadOnly(key)) { - throw new ReadOnlyException("Preference '" + key + "' is read-only"); - } - this.preferences.put(key, values); - } - - @Override - public Enumeration getNames() { - return Collections.enumeration(this.preferences.keySet()); - } - - @Override - public Map getMap() { - return Collections.unmodifiableMap(this.preferences); - } - - @Override - public void reset(String key) throws ReadOnlyException { - Assert.notNull(key, "Key must not be null"); - if (isReadOnly(key)) { - throw new ReadOnlyException("Preference '" + key + "' is read-only"); - } - this.preferences.remove(key); - } - - public void setPreferencesValidator(PreferencesValidator preferencesValidator) { - this.preferencesValidator = preferencesValidator; - } - - @Override - public void store() throws IOException, ValidatorException { - if (this.preferencesValidator != null) { - this.preferencesValidator.validate(this); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java deleted file mode 100644 index 08278d07d5..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequest.java +++ /dev/null @@ -1,565 +0,0 @@ -/* - * Copyright 2002-2014 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.mock.web.portlet; - -import java.security.Principal; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletPreferences; -import javax.portlet.PortletRequest; -import javax.portlet.PortletSession; -import javax.portlet.WindowState; -import javax.servlet.http.Cookie; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Mock implementation of the {@link javax.portlet.PortletRequest} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletRequest implements PortletRequest { - - private boolean active = true; - - private final PortalContext portalContext; - - private final PortletContext portletContext; - - private PortletSession session; - - private WindowState windowState = WindowState.NORMAL; - - private PortletMode portletMode = PortletMode.VIEW; - - private PortletPreferences portletPreferences = new MockPortletPreferences(); - - private final Map> properties = new LinkedHashMap>(); - - private final Map attributes = new LinkedHashMap(); - - private final Map parameters = new LinkedHashMap(); - - private String authType = null; - - private String contextPath = ""; - - private String remoteUser = null; - - private Principal userPrincipal = null; - - private final Set userRoles = new HashSet(); - - private boolean secure = false; - - private boolean requestedSessionIdValid = true; - - private final List responseContentTypes = new LinkedList(); - - private final List locales = new LinkedList(); - - private String scheme = "http"; - - private String serverName = "localhost"; - - private int serverPort = 80; - - private String windowID; - - private Cookie[] cookies; - - private final Set publicParameterNames = new HashSet(); - - - /** - * Create a new MockPortletRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see MockPortalContext - * @see MockPortletContext - */ - public MockPortletRequest() { - this(null, null); - } - - /** - * Create a new MockPortletRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - * @see MockPortalContext - */ - public MockPortletRequest(PortletContext portletContext) { - this(null, portletContext); - } - - /** - * Create a new MockPortletRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockPortletRequest(PortalContext portalContext, PortletContext portletContext) { - this.portalContext = (portalContext != null ? portalContext : new MockPortalContext()); - this.portletContext = (portletContext != null ? portletContext : new MockPortletContext()); - this.responseContentTypes.add("text/html"); - this.locales.add(Locale.ENGLISH); - this.attributes.put(LIFECYCLE_PHASE, getLifecyclePhase()); - } - - - //--------------------------------------------------------------------- - // Lifecycle methods - //--------------------------------------------------------------------- - - /** - * Return the Portlet 2.0 lifecycle id for the current phase. - */ - protected String getLifecyclePhase() { - return null; - } - - /** - * Return whether this request is still active (that is, not completed yet). - */ - public boolean isActive() { - return this.active; - } - - /** - * Mark this request as completed. - */ - public void close() { - this.active = false; - } - - /** - * Check whether this request is still active (that is, not completed yet), - * throwing an IllegalStateException if not active anymore. - */ - protected void checkActive() throws IllegalStateException { - if (!this.active) { - throw new IllegalStateException("Request is not active anymore"); - } - } - - - //--------------------------------------------------------------------- - // PortletRequest methods - //--------------------------------------------------------------------- - - @Override - public boolean isWindowStateAllowed(WindowState windowState) { - return CollectionUtils.contains(this.portalContext.getSupportedWindowStates(), windowState); - } - - @Override - public boolean isPortletModeAllowed(PortletMode portletMode) { - return CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode); - } - - public void setPortletMode(PortletMode portletMode) { - Assert.notNull(portletMode, "PortletMode must not be null"); - this.portletMode = portletMode; - } - - @Override - public PortletMode getPortletMode() { - return this.portletMode; - } - - public void setWindowState(WindowState windowState) { - Assert.notNull(windowState, "WindowState must not be null"); - this.windowState = windowState; - } - - @Override - public WindowState getWindowState() { - return this.windowState; - } - - public void setPreferences(PortletPreferences preferences) { - Assert.notNull(preferences, "PortletPreferences must not be null"); - this.portletPreferences = preferences; - } - - @Override - public PortletPreferences getPreferences() { - return this.portletPreferences; - } - - public void setSession(PortletSession session) { - this.session = session; - if (session instanceof MockPortletSession) { - MockPortletSession mockSession = ((MockPortletSession) session); - mockSession.access(); - } - } - - @Override - public PortletSession getPortletSession() { - return getPortletSession(true); - } - - @Override - public PortletSession getPortletSession(boolean create) { - checkActive(); - // Reset session if invalidated. - if (this.session instanceof MockPortletSession && ((MockPortletSession) this.session).isInvalid()) { - this.session = null; - } - // Create new session if necessary. - if (this.session == null && create) { - this.session = new MockPortletSession(this.portletContext); - } - return this.session; - } - - /** - * Set a single value for the specified property. - *

        If there are already one or more values registered for the given - * property key, they will be replaced. - */ - public void setProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - List list = new LinkedList(); - list.add(value); - this.properties.put(key, list); - } - - /** - * Add a single value for the specified property. - *

        If there are already one or more values registered for the given - * property key, the given value will be added to the end of the list. - */ - public void addProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - List oldList = this.properties.get(key); - if (oldList != null) { - oldList.add(value); - } - else { - List list = new LinkedList(); - list.add(value); - this.properties.put(key, list); - } - } - - @Override - public String getProperty(String key) { - Assert.notNull(key, "Property key must not be null"); - List list = this.properties.get(key); - return (list != null && list.size() > 0 ? list.get(0) : null); - } - - @Override - public Enumeration getProperties(String key) { - Assert.notNull(key, "property key must not be null"); - return Collections.enumeration(this.properties.get(key)); - } - - @Override - public Enumeration getPropertyNames() { - return Collections.enumeration(this.properties.keySet()); - } - - @Override - public PortalContext getPortalContext() { - return this.portalContext; - } - - public void setAuthType(String authType) { - this.authType = authType; - } - - @Override - public String getAuthType() { - return this.authType; - } - - public void setContextPath(String contextPath) { - this.contextPath = contextPath; - } - - @Override - public String getContextPath() { - return this.contextPath; - } - - public void setRemoteUser(String remoteUser) { - this.remoteUser = remoteUser; - } - - @Override - public String getRemoteUser() { - return this.remoteUser; - } - - public void setUserPrincipal(Principal userPrincipal) { - this.userPrincipal = userPrincipal; - } - - @Override - public Principal getUserPrincipal() { - return this.userPrincipal; - } - - public void addUserRole(String role) { - this.userRoles.add(role); - } - - @Override - public boolean isUserInRole(String role) { - return this.userRoles.contains(role); - } - - @Override - public Object getAttribute(String name) { - checkActive(); - return this.attributes.get(name); - } - - @Override - public Enumeration getAttributeNames() { - checkActive(); - return Collections.enumeration(this.attributes.keySet()); - } - - public void setParameters(Map parameters) { - Assert.notNull(parameters, "Parameters Map must not be null"); - this.parameters.clear(); - this.parameters.putAll(parameters); - } - - public void setParameter(String key, String value) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(value, "Parameter value must not be null"); - this.parameters.put(key, new String[] {value}); - } - - public void setParameter(String key, String[] values) { - Assert.notNull(key, "Parameter key must be null"); - Assert.notNull(values, "Parameter values must not be null"); - this.parameters.put(key, values); - } - - public void addParameter(String name, String value) { - addParameter(name, new String[] {value}); - } - - public void addParameter(String name, String[] values) { - String[] oldArr = this.parameters.get(name); - if (oldArr != null) { - String[] newArr = new String[oldArr.length + values.length]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - System.arraycopy(values, 0, newArr, oldArr.length, values.length); - this.parameters.put(name, newArr); - } - else { - this.parameters.put(name, values); - } - } - - @Override - public String getParameter(String name) { - String[] arr = this.parameters.get(name); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - @Override - public Enumeration getParameterNames() { - return Collections.enumeration(this.parameters.keySet()); - } - - @Override - public String[] getParameterValues(String name) { - return this.parameters.get(name); - } - - @Override - public Map getParameterMap() { - return Collections.unmodifiableMap(this.parameters); - } - - public void setSecure(boolean secure) { - this.secure = secure; - } - - @Override - public boolean isSecure() { - return this.secure; - } - - @Override - public void setAttribute(String name, Object value) { - checkActive(); - if (value != null) { - this.attributes.put(name, value); - } - else { - this.attributes.remove(name); - } - } - - @Override - public void removeAttribute(String name) { - checkActive(); - this.attributes.remove(name); - } - - @Override - public String getRequestedSessionId() { - PortletSession session = this.getPortletSession(); - return (session != null ? session.getId() : null); - } - - public void setRequestedSessionIdValid(boolean requestedSessionIdValid) { - this.requestedSessionIdValid = requestedSessionIdValid; - } - - @Override - public boolean isRequestedSessionIdValid() { - return this.requestedSessionIdValid; - } - - public void addResponseContentType(String responseContentType) { - this.responseContentTypes.add(responseContentType); - } - - public void addPreferredResponseContentType(String responseContentType) { - this.responseContentTypes.add(0, responseContentType); - } - - @Override - public String getResponseContentType() { - return this.responseContentTypes.get(0); - } - - @Override - public Enumeration getResponseContentTypes() { - return Collections.enumeration(this.responseContentTypes); - } - - public void addLocale(Locale locale) { - this.locales.add(locale); - } - - public void addPreferredLocale(Locale locale) { - this.locales.add(0, locale); - } - - @Override - public Locale getLocale() { - return this.locales.get(0); - } - - @Override - public Enumeration getLocales() { - return Collections.enumeration(this.locales); - } - - public void setScheme(String scheme) { - this.scheme = scheme; - } - - @Override - public String getScheme() { - return this.scheme; - } - - public void setServerName(String serverName) { - this.serverName = serverName; - } - - @Override - public String getServerName() { - return this.serverName; - } - - public void setServerPort(int serverPort) { - this.serverPort = serverPort; - } - - @Override - public int getServerPort() { - return this.serverPort; - } - - public void setWindowID(String windowID) { - this.windowID = windowID; - } - - @Override - public String getWindowID() { - return this.windowID; - } - - public void setCookies(Cookie... cookies) { - this.cookies = cookies; - } - - @Override - public Cookie[] getCookies() { - return this.cookies; - } - - @Override - public Map getPrivateParameterMap() { - if (!this.publicParameterNames.isEmpty()) { - Map filtered = new LinkedHashMap(); - for (String key : this.parameters.keySet()) { - if (!this.publicParameterNames.contains(key)) { - filtered.put(key, this.parameters.get(key)); - } - } - return filtered; - } - else { - return Collections.unmodifiableMap(this.parameters); - } - } - - @Override - public Map getPublicParameterMap() { - if (!this.publicParameterNames.isEmpty()) { - Map filtered = new LinkedHashMap(); - for (String key : this.parameters.keySet()) { - if (this.publicParameterNames.contains(key)) { - filtered.put(key, this.parameters.get(key)); - } - } - return filtered; - } - else { - return Collections.emptyMap(); - } - } - - public void registerPublicParameter(String name) { - this.publicParameterNames.add(name); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java deleted file mode 100644 index f4e0dc98fd..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletRequestDispatcher.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.IOException; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.PortletResponse; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletRequestDispatcher} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletRequestDispatcher implements PortletRequestDispatcher { - - private final Log logger = LogFactory.getLog(getClass()); - - private final String url; - - - /** - * Create a new MockPortletRequestDispatcher for the given URL. - * @param url the URL to dispatch to. - */ - public MockPortletRequestDispatcher(String url) { - Assert.notNull(url, "URL must not be null"); - this.url = url; - } - - - @Override - public void include(RenderRequest request, RenderResponse response) throws PortletException, IOException { - include((PortletRequest) request, (PortletResponse) response); - } - - @Override - public void include(PortletRequest request, PortletResponse response) throws PortletException, IOException { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - if (!(response instanceof MockMimeResponse)) { - throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse"); - } - ((MockMimeResponse) response).setIncludedUrl(this.url); - if (logger.isDebugEnabled()) { - logger.debug("MockPortletRequestDispatcher: including URL [" + this.url + "]"); - } - } - - @Override - public void forward(PortletRequest request, PortletResponse response) throws PortletException, IOException { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - if (!(response instanceof MockMimeResponse)) { - throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse"); - } - ((MockMimeResponse) response).setForwardedUrl(this.url); - if (logger.isDebugEnabled()) { - logger.debug("MockPortletRequestDispatcher: forwarding to URL [" + this.url + "]"); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletResponse.java deleted file mode 100644 index 513a6c8c9c..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletResponse.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import javax.portlet.PortalContext; -import javax.portlet.PortletResponse; -import javax.servlet.http.Cookie; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletResponse} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletResponse implements PortletResponse { - - private final PortalContext portalContext; - - private final Map properties = new LinkedHashMap(); - - private String namespace = ""; - - private final Set cookies = new LinkedHashSet(); - - private final Map xmlProperties = new LinkedHashMap(); - - private Document xmlDocument; - - - /** - * Create a new MockPortletResponse with a default {@link MockPortalContext}. - * @see MockPortalContext - */ - public MockPortletResponse() { - this(null); - } - - /** - * Create a new MockPortletResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockPortletResponse(PortalContext portalContext) { - this.portalContext = (portalContext != null ? portalContext : new MockPortalContext()); - } - - /** - * Return the PortalContext that this MockPortletResponse runs in, - * defining the supported PortletModes and WindowStates. - */ - public PortalContext getPortalContext() { - return this.portalContext; - } - - - //--------------------------------------------------------------------- - // PortletResponse methods - //--------------------------------------------------------------------- - - @Override - public void addProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - String[] oldArr = this.properties.get(key); - if (oldArr != null) { - String[] newArr = new String[oldArr.length + 1]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - newArr[oldArr.length] = value; - this.properties.put(key, newArr); - } - else { - this.properties.put(key, new String[] {value}); - } - } - - @Override - public void setProperty(String key, String value) { - Assert.notNull(key, "Property key must not be null"); - this.properties.put(key, new String[] {value}); - } - - public Set getPropertyNames() { - return Collections.unmodifiableSet(this.properties.keySet()); - } - - public String getProperty(String key) { - Assert.notNull(key, "Property key must not be null"); - String[] arr = this.properties.get(key); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public String[] getProperties(String key) { - Assert.notNull(key, "Property key must not be null"); - return this.properties.get(key); - } - - @Override - public String encodeURL(String path) { - return path; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - @Override - public String getNamespace() { - return this.namespace; - } - - @Override - public void addProperty(Cookie cookie) { - Assert.notNull(cookie, "Cookie must not be null"); - this.cookies.add(cookie); - } - - public Cookie[] getCookies() { - return this.cookies.toArray(new Cookie[this.cookies.size()]); - } - - public Cookie getCookie(String name) { - Assert.notNull(name, "Cookie name must not be null"); - for (Cookie cookie : this.cookies) { - if (name.equals(cookie.getName())) { - return cookie; - } - } - return null; - } - - @Override - public void addProperty(String key, Element value) { - Assert.notNull(key, "Property key must not be null"); - Element[] oldArr = this.xmlProperties.get(key); - if (oldArr != null) { - Element[] newArr = new Element[oldArr.length + 1]; - System.arraycopy(oldArr, 0, newArr, 0, oldArr.length); - newArr[oldArr.length] = value; - this.xmlProperties.put(key, newArr); - } - else { - this.xmlProperties.put(key, new Element[] {value}); - } - } - - - public Set getXmlPropertyNames() { - return Collections.unmodifiableSet(this.xmlProperties.keySet()); - } - - public Element getXmlProperty(String key) { - Assert.notNull(key, "Property key must not be null"); - Element[] arr = this.xmlProperties.get(key); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public Element[] getXmlProperties(String key) { - Assert.notNull(key, "Property key must not be null"); - return this.xmlProperties.get(key); - } - - @Override - public Element createElement(String tagName) throws DOMException { - if (this.xmlDocument == null) { - try { - this.xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); - } - catch (ParserConfigurationException ex) { - throw new DOMException(DOMException.INVALID_STATE_ERR, ex.toString()); - } - } - return this.xmlDocument.createElement(tagName); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java deleted file mode 100644 index 0f3593ff30..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright 2002-2013 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.mock.web.portlet; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import javax.portlet.PortletContext; -import javax.portlet.PortletSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; - -import org.springframework.mock.web.test.MockHttpSession; - -/** - * Mock implementation of the {@link javax.portlet.PortletSession} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletSession implements PortletSession { - - private static int nextId = 1; - - - private final String id = Integer.toString(nextId++); - - private final long creationTime = System.currentTimeMillis(); - - private int maxInactiveInterval; - - private long lastAccessedTime = System.currentTimeMillis(); - - private final PortletContext portletContext; - - private final Map portletAttributes = new HashMap(); - - private final Map applicationAttributes = new HashMap(); - - private boolean invalid = false; - - private boolean isNew = true; - - - /** - * Create a new MockPortletSession with a default {@link MockPortletContext}. - * @see MockPortletContext - */ - public MockPortletSession() { - this(null); - } - - /** - * Create a new MockPortletSession. - * @param portletContext the PortletContext that the session runs in - */ - public MockPortletSession(PortletContext portletContext) { - this.portletContext = (portletContext != null ? portletContext : new MockPortletContext()); - } - - - @Override - public Object getAttribute(String name) { - return this.portletAttributes.get(name); - } - - @Override - public Object getAttribute(String name, int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - return this.portletAttributes.get(name); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - return this.applicationAttributes.get(name); - } - return null; - } - - @Override - public Enumeration getAttributeNames() { - return Collections.enumeration(this.portletAttributes.keySet()); - } - - @Override - public Enumeration getAttributeNames(int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - return Collections.enumeration(this.portletAttributes.keySet()); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - return Collections.enumeration(this.applicationAttributes.keySet()); - } - return null; - } - - @Override - public long getCreationTime() { - return this.creationTime; - } - - @Override - public String getId() { - return this.id; - } - - public void access() { - this.lastAccessedTime = System.currentTimeMillis(); - setNew(false); - } - - @Override - public long getLastAccessedTime() { - return this.lastAccessedTime; - } - - @Override - public int getMaxInactiveInterval() { - return this.maxInactiveInterval; - } - - /** - * Clear all of this session's attributes. - */ - public void clearAttributes() { - doClearAttributes(this.portletAttributes); - doClearAttributes(this.applicationAttributes); - } - - protected void doClearAttributes(Map attributes) { - for (Iterator> it = attributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - String name = entry.getKey(); - Object value = entry.getValue(); - it.remove(); - if (value instanceof HttpSessionBindingListener) { - ((HttpSessionBindingListener) value).valueUnbound( - new HttpSessionBindingEvent(new MockHttpSession(), name, value)); - } - } - } - - @Override - public void invalidate() { - this.invalid = true; - clearAttributes(); - } - - public boolean isInvalid() { - return this.invalid; - } - - public void setNew(boolean value) { - this.isNew = value; - } - - @Override - public boolean isNew() { - return this.isNew; - } - - @Override - public void removeAttribute(String name) { - this.portletAttributes.remove(name); - } - - @Override - public void removeAttribute(String name, int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - this.portletAttributes.remove(name); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - this.applicationAttributes.remove(name); - } - } - - @Override - public void setAttribute(String name, Object value) { - if (value != null) { - this.portletAttributes.put(name, value); - } - else { - this.portletAttributes.remove(name); - } - } - - @Override - public void setAttribute(String name, Object value, int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - if (value != null) { - this.portletAttributes.put(name, value); - } - else { - this.portletAttributes.remove(name); - } - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - if (value != null) { - this.applicationAttributes.put(name, value); - } - else { - this.applicationAttributes.remove(name); - } - } - } - - @Override - public void setMaxInactiveInterval(int interval) { - this.maxInactiveInterval = interval; - } - - @Override - public PortletContext getPortletContext() { - return this.portletContext; - } - - @Override - public Map getAttributeMap() { - return Collections.unmodifiableMap(this.portletAttributes); - } - - @Override - public Map getAttributeMap(int scope) { - if (scope == PortletSession.PORTLET_SCOPE) { - return Collections.unmodifiableMap(this.portletAttributes); - } - else if (scope == PortletSession.APPLICATION_SCOPE) { - return Collections.unmodifiableMap(this.applicationAttributes); - } - else { - return Collections.emptyMap(); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletURL.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletURL.java deleted file mode 100644 index c7eff5a528..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletURL.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletModeException; -import javax.portlet.PortletURL; -import javax.portlet.WindowState; -import javax.portlet.WindowStateException; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Mock implementation of the {@link javax.portlet.PortletURL} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockPortletURL extends MockBaseURL implements PortletURL { - - public static final String URL_TYPE_RENDER = "render"; - - public static final String URL_TYPE_ACTION = "action"; - - - private final PortalContext portalContext; - - private final String urlType; - - private WindowState windowState; - - private PortletMode portletMode; - - - /** - * Create a new MockPortletURL for the given URL type. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - * @param urlType the URL type, for example "render" or "action" - * @see #URL_TYPE_RENDER - * @see #URL_TYPE_ACTION - */ - public MockPortletURL(PortalContext portalContext, String urlType) { - Assert.notNull(portalContext, "PortalContext is required"); - this.portalContext = portalContext; - this.urlType = urlType; - } - - - //--------------------------------------------------------------------- - // PortletURL methods - //--------------------------------------------------------------------- - - @Override - public void setWindowState(WindowState windowState) throws WindowStateException { - if (!CollectionUtils.contains(this.portalContext.getSupportedWindowStates(), windowState)) { - throw new WindowStateException("WindowState not supported", windowState); - } - this.windowState = windowState; - } - - @Override - public WindowState getWindowState() { - return this.windowState; - } - - @Override - public void setPortletMode(PortletMode portletMode) throws PortletModeException { - if (!CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode)) { - throw new PortletModeException("PortletMode not supported", portletMode); - } - this.portletMode = portletMode; - } - - @Override - public PortletMode getPortletMode() { - return this.portletMode; - } - - @Override - public void removePublicRenderParameter(String name) { - this.parameters.remove(name); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(encodeParameter("urlType", this.urlType)); - if (this.windowState != null) { - sb.append(";").append(encodeParameter("windowState", this.windowState.toString())); - } - if (this.portletMode != null) { - sb.append(";").append(encodeParameter("portletMode", this.portletMode.toString())); - } - for (Map.Entry entry : this.parameters.entrySet()) { - sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue())); - } - return (isSecure() ? "https:" : "http:") + - "//localhost/mockportlet?" + sb.toString(); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderRequest.java deleted file mode 100644 index 8b9ed2e41a..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderRequest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; -import javax.portlet.RenderRequest; -import javax.portlet.WindowState; - -/** - * Mock implementation of the {@link javax.portlet.RenderRequest} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockRenderRequest extends MockPortletRequest implements RenderRequest { - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see MockPortalContext - * @see MockPortletContext - */ - public MockRenderRequest() { - super(); - } - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param portletMode the mode that the portlet runs in - */ - public MockRenderRequest(PortletMode portletMode) { - super(); - setPortletMode(portletMode); - } - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param portletMode the mode that the portlet runs in - * @param windowState the window state to run the portlet in - */ - public MockRenderRequest(PortletMode portletMode, WindowState windowState) { - super(); - setPortletMode(portletMode); - setWindowState(windowState); - } - - /** - * Create a new MockRenderRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockRenderRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockRenderRequest. - * @param portalContext the PortletContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockRenderRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - @Override - protected String getLifecyclePhase() { - return RENDER_PHASE; - } - - @Override - public String getETag() { - return getProperty(RenderRequest.ETAG); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderResponse.java deleted file mode 100644 index e359b0b52c..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockRenderResponse.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collection; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -/** - * Mock implementation of the {@link javax.portlet.RenderResponse} interface. - * - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -public class MockRenderResponse extends MockMimeResponse implements RenderResponse { - - private String title; - - private Collection nextPossiblePortletModes; - - - /** - * Create a new MockRenderResponse with a default {@link MockPortalContext}. - * @see MockPortalContext - */ - public MockRenderResponse() { - super(); - } - - /** - * Create a new MockRenderResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockRenderResponse(PortalContext portalContext) { - super(portalContext); - } - - /** - * Create a new MockRenderResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - * @param request the corresponding render request that this response - * is generated for - */ - public MockRenderResponse(PortalContext portalContext, RenderRequest request) { - super(portalContext, request); - } - - - //--------------------------------------------------------------------- - // RenderResponse methods - //--------------------------------------------------------------------- - - @Override - public void setTitle(String title) { - this.title = title; - } - - public String getTitle() { - return this.title; - } - - @Override - public void setNextPossiblePortletModes(Collection portletModes) { - this.nextPossiblePortletModes = portletModes; - } - - public Collection getNextPossiblePortletModes() { - return this.nextPossiblePortletModes; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceRequest.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceRequest.java deleted file mode 100644 index 5878e7b96e..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceRequest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletContext; -import javax.portlet.RenderRequest; -import javax.portlet.ResourceRequest; - -/** - * Mock implementation of the {@link javax.portlet.ResourceRequest} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockResourceRequest extends MockClientDataRequest implements ResourceRequest { - - private String resourceID; - - private String cacheability; - - private final Map privateRenderParameterMap = new LinkedHashMap(); - - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - * @see org.springframework.mock.web.portlet.MockPortletContext - */ - public MockResourceRequest() { - super(); - } - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param resourceID the resource id for this request - */ - public MockResourceRequest(String resourceID) { - super(); - this.resourceID = resourceID; - } - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext} - * and a default {@link MockPortletContext}. - * @param url the resource URL for this request - */ - public MockResourceRequest(MockResourceURL url) { - super(); - this.resourceID = url.getResourceID(); - this.cacheability = url.getCacheability(); - } - - /** - * Create a new MockResourceRequest with a default {@link MockPortalContext}. - * @param portletContext the PortletContext that the request runs in - */ - public MockResourceRequest(PortletContext portletContext) { - super(portletContext); - } - - /** - * Create a new MockResourceRequest. - * @param portalContext the PortalContext that the request runs in - * @param portletContext the PortletContext that the request runs in - */ - public MockResourceRequest(PortalContext portalContext, PortletContext portletContext) { - super(portalContext, portletContext); - } - - - @Override - protected String getLifecyclePhase() { - return RESOURCE_PHASE; - } - - public void setResourceID(String resourceID) { - this.resourceID = resourceID; - } - - @Override - public String getResourceID() { - return this.resourceID; - } - - public void setCacheability(String cacheLevel) { - this.cacheability = cacheLevel; - } - - @Override - public String getCacheability() { - return this.cacheability; - } - - @Override - public String getETag() { - return getProperty(RenderRequest.ETAG); - } - - public void addPrivateRenderParameter(String key, String value) { - this.privateRenderParameterMap.put(key, new String[] {value}); - } - - public void addPrivateRenderParameter(String key, String[] values) { - this.privateRenderParameterMap.put(key, values); - } - - @Override - public Map getPrivateRenderParameterMap() { - return Collections.unmodifiableMap(this.privateRenderParameterMap); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceResponse.java deleted file mode 100644 index 4c7f45279b..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceResponse.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import javax.portlet.ResourceResponse; - -/** - * Mock implementation of the {@link javax.portlet.ResourceResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockResourceResponse extends MockMimeResponse implements ResourceResponse { - - private int contentLength = 0; - - - @Override - public void setContentLength(int len) { - this.contentLength = len; - } - - public int getContentLength() { - return this.contentLength; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceURL.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceURL.java deleted file mode 100644 index b7aab871df..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockResourceURL.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.util.Map; -import javax.portlet.ResourceURL; - -/** - * Mock implementation of the {@link javax.portlet.ResourceURL} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockResourceURL extends MockBaseURL implements ResourceURL { - - private String resourceID; - - private String cacheability; - - - //--------------------------------------------------------------------- - // ResourceURL methods - //--------------------------------------------------------------------- - - @Override - public void setResourceID(String resourceID) { - this.resourceID = resourceID; - } - - public String getResourceID() { - return this.resourceID; - } - - @Override - public void setCacheability(String cacheLevel) { - this.cacheability = cacheLevel; - } - - @Override - public String getCacheability() { - return this.cacheability; - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(encodeParameter("resourceID", this.resourceID)); - if (this.cacheability != null) { - sb.append(";").append(encodeParameter("cacheability", this.cacheability)); - } - for (Map.Entry entry : this.parameters.entrySet()) { - sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue())); - } - return (isSecure() ? "https:" : "http:") + - "//localhost/mockportlet?" + sb.toString(); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java deleted file mode 100644 index 93ddad81d0..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2002-2012 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.mock.web.portlet; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.portlet.PortalContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletModeException; -import javax.portlet.StateAwareResponse; -import javax.portlet.WindowState; -import javax.portlet.WindowStateException; -import javax.xml.namespace.QName; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Mock implementation of the {@link javax.portlet.StateAwareResponse} interface. - * - * @author Juergen Hoeller - * @since 3.0 - */ -public class MockStateAwareResponse extends MockPortletResponse implements StateAwareResponse { - - private WindowState windowState; - - private PortletMode portletMode; - - private final Map renderParameters = new LinkedHashMap(); - - private final Map events = new HashMap(); - - - /** - * Create a new MockActionResponse with a default {@link MockPortalContext}. - * @see org.springframework.mock.web.portlet.MockPortalContext - */ - public MockStateAwareResponse() { - super(); - } - - /** - * Create a new MockActionResponse. - * @param portalContext the PortalContext defining the supported - * PortletModes and WindowStates - */ - public MockStateAwareResponse(PortalContext portalContext) { - super(portalContext); - } - - - @Override - public void setWindowState(WindowState windowState) throws WindowStateException { - if (!CollectionUtils.contains(getPortalContext().getSupportedWindowStates(), windowState)) { - throw new WindowStateException("WindowState not supported", windowState); - } - this.windowState = windowState; - } - - @Override - public WindowState getWindowState() { - return this.windowState; - } - - @Override - public void setPortletMode(PortletMode portletMode) throws PortletModeException { - if (!CollectionUtils.contains(getPortalContext().getSupportedPortletModes(), portletMode)) { - throw new PortletModeException("PortletMode not supported", portletMode); - } - this.portletMode = portletMode; - } - - @Override - public PortletMode getPortletMode() { - return this.portletMode; - } - - @Override - public void setRenderParameters(Map parameters) { - Assert.notNull(parameters, "Parameters Map must not be null"); - this.renderParameters.clear(); - this.renderParameters.putAll(parameters); - } - - @Override - public void setRenderParameter(String key, String value) { - Assert.notNull(key, "Parameter key must not be null"); - Assert.notNull(value, "Parameter value must not be null"); - this.renderParameters.put(key, new String[] {value}); - } - - @Override - public void setRenderParameter(String key, String[] values) { - Assert.notNull(key, "Parameter key must not be null"); - Assert.notNull(values, "Parameter values must not be null"); - this.renderParameters.put(key, values); - } - - public String getRenderParameter(String key) { - Assert.notNull(key, "Parameter key must not be null"); - String[] arr = this.renderParameters.get(key); - return (arr != null && arr.length > 0 ? arr[0] : null); - } - - public String[] getRenderParameterValues(String key) { - Assert.notNull(key, "Parameter key must not be null"); - return this.renderParameters.get(key); - } - - public Iterator getRenderParameterNames() { - return this.renderParameters.keySet().iterator(); - } - - @Override - public Map getRenderParameterMap() { - return Collections.unmodifiableMap(this.renderParameters); - } - - @Override - public void removePublicRenderParameter(String name) { - this.renderParameters.remove(name); - } - - @Override - public void setEvent(QName name, Serializable value) { - this.events.put(name, value); - } - - @Override - public void setEvent(String name, Serializable value) { - this.events.put(new QName(name), value); - } - - public Iterator getEventNames() { - return this.events.keySet().iterator(); - } - - public Serializable getEvent(QName name) { - return this.events.get(name); - } - - public Serializable getEvent(String name) { - return this.events.get(new QName(name)); - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java deleted file mode 100644 index 716f71b0ef..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/ServletWrappingPortletContext.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2002-2016 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.mock.web.portlet; - -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Set; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequestDispatcher; -import javax.servlet.ServletContext; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.portlet.PortletContext} interface, - * wrapping an underlying {@link javax.servlet.ServletContext}. - * - * @author Juergen Hoeller - * @since 3.0 - * @see MockPortletContext - */ -public class ServletWrappingPortletContext implements PortletContext { - - private final ServletContext servletContext; - - - /** - * Create a new PortletContext wrapping the given ServletContext. - * @param servletContext the ServletContext to wrap - */ - public ServletWrappingPortletContext(ServletContext servletContext) { - Assert.notNull(servletContext, "ServletContext must not be null"); - this.servletContext = servletContext; - } - - /** - * Return the underlying ServletContext that this PortletContext wraps. - */ - public final ServletContext getServletContext() { - return this.servletContext; - } - - - @Override - public String getServerInfo() { - return this.servletContext.getServerInfo(); - } - - @Override - public PortletRequestDispatcher getRequestDispatcher(String path) { - return null; - } - - @Override - public PortletRequestDispatcher getNamedDispatcher(String name) { - return null; - } - - @Override - public InputStream getResourceAsStream(String path) { - return this.servletContext.getResourceAsStream(path); - } - - @Override - public int getMajorVersion() { - return 2; - } - - @Override - public int getMinorVersion() { - return 0; - } - - @Override - public String getMimeType(String file) { - return this.servletContext.getMimeType(file); - } - - @Override - public String getRealPath(String path) { - return this.servletContext.getRealPath(path); - } - - @Override - public Set getResourcePaths(String path) { - return this.servletContext.getResourcePaths(path); - } - - @Override - public URL getResource(String path) throws MalformedURLException { - return this.servletContext.getResource(path); - } - - @Override - public Object getAttribute(String name) { - return this.servletContext.getAttribute(name); - } - - @Override - public Enumeration getAttributeNames() { - return this.servletContext.getAttributeNames(); - } - - @Override - public String getInitParameter(String name) { - return this.servletContext.getInitParameter(name); - } - - @Override - public Enumeration getInitParameterNames() { - return this.servletContext.getInitParameterNames(); - } - - @Override - public void log(String msg) { - this.servletContext.log(msg); - } - - @Override - public void log(String message, Throwable throwable) { - this.servletContext.log(message, throwable); - } - - @Override - public void removeAttribute(String name) { - this.servletContext.removeAttribute(name); - } - - @Override - public void setAttribute(String name, Object object) { - this.servletContext.setAttribute(name, object); - } - - @Override - public String getPortletContextName() { - return this.servletContext.getServletContextName(); - } - - @Override - public Enumeration getContainerRuntimeOptions() { - return Collections.enumeration(Collections.emptySet()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/package-info.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/package-info.java deleted file mode 100644 index 1b260618f1..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/package-info.java +++ /dev/null @@ -1,11 +0,0 @@ -/** - * A comprehensive set of Portlet API mock objects, - * targeted at usage with Spring's web MVC framework. - * Useful for testing web contexts and controllers. - * - *

        More convenient to use than dynamic mock objects - * (EasyMock) or - * existing Portlet API mock objects. - */ - -package org.springframework.mock.web.portlet; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java deleted file mode 100644 index e6bf78f3c8..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java +++ /dev/null @@ -1,548 +0,0 @@ -/* - * Copyright 2002-2014 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; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.EventRequest; -import javax.portlet.EventResponse; -import javax.portlet.Portlet; -import javax.portlet.PortletConfig; -import javax.portlet.PortletException; -import javax.portlet.PortletRequest; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.ResourceRequest; -import javax.portlet.ResourceResponse; - -import org.springframework.beans.BeansException; -import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.factory.config.BeanReference; -import org.springframework.beans.factory.config.ConstructorArgumentValues; -import org.springframework.beans.factory.config.RuntimeBeanReference; -import org.springframework.beans.factory.support.ManagedList; -import org.springframework.beans.factory.support.ManagedMap; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.i18n.LocaleContextHolder; -import org.springframework.core.Ordered; -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.test.MockMultipartFile; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; -import org.springframework.web.multipart.MaxUploadSizeExceededException; -import org.springframework.web.multipart.MultipartException; -import org.springframework.web.multipart.MultipartFile; -import org.springframework.web.portlet.bind.PortletRequestBindingException; -import org.springframework.web.portlet.context.PortletRequestHandledEvent; -import org.springframework.web.portlet.context.StaticPortletApplicationContext; -import org.springframework.web.portlet.handler.HandlerInterceptorAdapter; -import org.springframework.web.portlet.handler.ParameterHandlerMapping; -import org.springframework.web.portlet.handler.ParameterMappingInterceptor; -import org.springframework.web.portlet.handler.PortletModeHandlerMapping; -import org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping; -import org.springframework.web.portlet.handler.SimpleMappingExceptionResolver; -import org.springframework.web.portlet.handler.SimplePortletHandlerAdapter; -import org.springframework.web.portlet.handler.SimplePortletPostProcessor; -import org.springframework.web.portlet.handler.UserRoleAuthorizationInterceptor; -import org.springframework.web.portlet.multipart.DefaultMultipartActionRequest; -import org.springframework.web.portlet.multipart.MultipartActionRequest; -import org.springframework.web.portlet.multipart.PortletMultipartResolver; -import org.springframework.web.portlet.mvc.Controller; -import org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter; - -/** - * @author Juergen Hoeller - * @author Mark Fisher - * @author Arjen Poutsma - */ -public class ComplexPortletApplicationContext extends StaticPortletApplicationContext { - - @Override - public void refresh() throws BeansException { - registerSingleton("standardHandlerAdapter", SimpleControllerHandlerAdapter.class); - registerSingleton("portletHandlerAdapter", SimplePortletHandlerAdapter.class); - registerSingleton("myHandlerAdapter", MyHandlerAdapter.class); - - registerSingleton("viewController", ViewController.class); - registerSingleton("editController", EditController.class); - registerSingleton("helpController1", HelpController1.class); - registerSingleton("helpController2", HelpController2.class); - registerSingleton("testController1", TestController1.class); - registerSingleton("testController2", TestController2.class); - registerSingleton("requestLocaleCheckingController", RequestLocaleCheckingController.class); - registerSingleton("localeContextCheckingController", LocaleContextCheckingController.class); - - registerSingleton("exceptionThrowingHandler1", ExceptionThrowingHandler.class); - registerSingleton("exceptionThrowingHandler2", ExceptionThrowingHandler.class); - registerSingleton("unknownHandler", Object.class); - - registerSingleton("myPortlet", MyPortlet.class); - registerSingleton("portletMultipartResolver", MockMultipartResolver.class); - registerSingleton("portletPostProcessor", SimplePortletPostProcessor.class); - registerSingleton("testListener", TestApplicationListener.class); - - ConstructorArgumentValues cvs = new ConstructorArgumentValues(); - cvs.addIndexedArgumentValue(0, new MockPortletContext()); - cvs.addIndexedArgumentValue(1, "complex"); - registerBeanDefinition("portletConfig", new RootBeanDefinition(MockPortletConfig.class, cvs, null)); - - UserRoleAuthorizationInterceptor userRoleInterceptor = new UserRoleAuthorizationInterceptor(); - userRoleInterceptor.setAuthorizedRoles(new String[] {"role1", "role2"}); - - ParameterHandlerMapping interceptingHandlerMapping = new ParameterHandlerMapping(); - interceptingHandlerMapping.setParameterName("interceptingParam"); - ParameterMappingInterceptor parameterMappingInterceptor = new ParameterMappingInterceptor(); - parameterMappingInterceptor.setParameterName("interceptingParam"); - - List interceptors = new ArrayList(4); - interceptors.add(parameterMappingInterceptor); - interceptors.add(userRoleInterceptor); - interceptors.add(new MyHandlerInterceptor1()); - interceptors.add(new MyHandlerInterceptor2()); - - MutablePropertyValues pvs = new MutablePropertyValues(); - Map portletModeMap = new ManagedMap(); - portletModeMap.put("view", new RuntimeBeanReference("viewController")); - portletModeMap.put("edit", new RuntimeBeanReference("editController")); - pvs.add("portletModeMap", portletModeMap); - pvs.add("interceptors", interceptors); - registerSingleton("handlerMapping3", PortletModeHandlerMapping.class, pvs); - - pvs = new MutablePropertyValues(); - Map parameterMap = new ManagedMap(); - parameterMap.put("test1", new RuntimeBeanReference("testController1")); - parameterMap.put("test2", new RuntimeBeanReference("testController2")); - parameterMap.put("requestLocaleChecker", new RuntimeBeanReference("requestLocaleCheckingController")); - parameterMap.put("contextLocaleChecker", new RuntimeBeanReference("localeContextCheckingController")); - parameterMap.put("exception1", new RuntimeBeanReference("exceptionThrowingHandler1")); - parameterMap.put("exception2", new RuntimeBeanReference("exceptionThrowingHandler2")); - parameterMap.put("myPortlet", new RuntimeBeanReference("myPortlet")); - parameterMap.put("unknown", new RuntimeBeanReference("unknownHandler")); - pvs.add("parameterMap", parameterMap); - pvs.add("parameterName", "myParam"); - pvs.add("order", "2"); - registerSingleton("handlerMapping2", ParameterHandlerMapping.class, pvs); - - pvs = new MutablePropertyValues(); - Map innerMap = new ManagedMap(); - innerMap.put("help1", new RuntimeBeanReference("helpController1")); - innerMap.put("help2", new RuntimeBeanReference("helpController2")); - Map outerMap = new ManagedMap(); - outerMap.put("help", innerMap); - pvs.add("portletModeParameterMap", outerMap); - pvs.add("order", "1"); - registerSingleton("handlerMapping1", PortletModeParameterHandlerMapping.class, pvs); - - pvs = new MutablePropertyValues(); - pvs.add("order", "1"); - pvs.add("exceptionMappings", - "java.lang.IllegalAccessException=failed-illegalaccess\n" + - "PortletRequestBindingException=failed-binding\n" + - "NoHandlerFoundException=failed-unavailable"); - pvs.add("defaultErrorView", "failed-default-1"); - registerSingleton("exceptionResolver", SimpleMappingExceptionResolver.class, pvs); - - pvs = new MutablePropertyValues(); - pvs.add("order", "0"); - pvs.add("exceptionMappings", - "java.lang.Exception=failed-exception\n" + - "java.lang.RuntimeException=failed-runtime"); - List mappedHandlers = new ManagedList(); - mappedHandlers.add(new RuntimeBeanReference("exceptionThrowingHandler1")); - pvs.add("mappedHandlers", mappedHandlers); - pvs.add("defaultErrorView", "failed-default-0"); - registerSingleton("handlerExceptionResolver", SimpleMappingExceptionResolver.class, pvs); - - addMessage("test", Locale.ENGLISH, "test message"); - addMessage("test", Locale.CANADA, "Canadian & test message"); - addMessage("test.args", Locale.ENGLISH, "test {0} and {1}"); - - super.refresh(); - } - - - public static class TestController1 implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) { - response.setRenderParameter("result", "test1-action"); - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - return null; - } - } - - - public static class TestController2 implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) {} - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - response.setProperty("result", "test2-view"); - return null; - } - } - - - public static class ViewController implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) {} - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - return new ModelAndView("someViewName", "result", "view was here"); - } - } - - - public static class EditController implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) { - response.setRenderParameter("param", "edit was here"); - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - return new ModelAndView(request.getParameter("param")); - } - } - - - public static class HelpController1 implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) { - response.setRenderParameter("param", "help1 was here"); - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - return new ModelAndView("help1-view"); - } - } - - - public static class HelpController2 implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) { - response.setRenderParameter("param", "help2 was here"); - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception { - return new ModelAndView("help2-view"); - } - } - - public static class RequestLocaleCheckingController implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) throws PortletException { - if (!Locale.CANADA.equals(request.getLocale())) { - throw new PortletException("Incorrect Locale in ActionRequest"); - } - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) - throws PortletException, IOException { - if (!Locale.CANADA.equals(request.getLocale())) { - throw new PortletException("Incorrect Locale in RenderRequest"); - } - response.getWriter().write("locale-ok"); - return null; - } - } - - - public static class LocaleContextCheckingController implements Controller { - - @Override - public void handleActionRequest(ActionRequest request, ActionResponse response) throws PortletException { - if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) { - throw new PortletException("Incorrect Locale in LocaleContextHolder"); - } - } - - @Override - public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) - throws PortletException, IOException { - if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) { - throw new PortletException("Incorrect Locale in LocaleContextHolder"); - } - response.getWriter().write("locale-ok"); - return null; - } - } - - - public static class MyPortlet implements Portlet { - - private PortletConfig portletConfig; - - @Override - public void init(PortletConfig portletConfig) throws PortletException { - this.portletConfig = portletConfig; - } - - @Override - public void processAction(ActionRequest request, ActionResponse response) throws PortletException { - response.setRenderParameter("result", "myPortlet action called"); - } - - @Override - public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException { - response.getWriter().write("myPortlet was here"); - } - - public PortletConfig getPortletConfig() { - return this.portletConfig; - } - - @Override - public void destroy() { - this.portletConfig = null; - } - } - - - public static interface MyHandler { - - public void doSomething(PortletRequest request) throws Exception; - } - - - public static class ExceptionThrowingHandler implements MyHandler { - - @Override - public void doSomething(PortletRequest request) throws Exception { - if (request.getParameter("fail") != null) { - throw new ModelAndViewDefiningException(new ModelAndView("failed-modelandview")); - } - if (request.getParameter("access") != null) { - throw new IllegalAccessException("portlet-illegalaccess"); - } - if (request.getParameter("binding") != null) { - throw new PortletRequestBindingException("portlet-binding"); - } - if (request.getParameter("generic") != null) { - throw new Exception("portlet-generic"); - } - if (request.getParameter("runtime") != null) { - throw new RuntimeException("portlet-runtime"); - } - throw new IllegalArgumentException("illegal argument"); - } - } - - - public static class MyHandlerAdapter implements HandlerAdapter, Ordered { - - @Override - public int getOrder() { - return 99; - } - - @Override - public boolean supports(Object handler) { - return handler != null && MyHandler.class.isAssignableFrom(handler.getClass()); - } - - @Override - public void handleAction(ActionRequest request, ActionResponse response, Object delegate) throws Exception { - ((MyHandler) delegate).doSomething(request); - } - - @Override - public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object delegate) throws Exception { - ((MyHandler) delegate).doSomething(request); - return null; - } - - @Override - public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler) - throws Exception { - return null; - } - - @Override - public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception { - } - } - - - public static class MyHandlerInterceptor1 extends HandlerInterceptorAdapter { - - @Override - public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) - throws PortletException { - if (request.getAttribute("test2-remove-never") != null) { - throw new PortletException("Wrong interceptor order"); - } - request.setAttribute("test1-remove-never", "test1-remove-never"); - request.setAttribute("test1-remove-post", "test1-remove-post"); - request.setAttribute("test1-remove-after", "test1-remove-after"); - return true; - } - - @Override - public void postHandleRender( - RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView) - throws PortletException { - if (request.getAttribute("test2-remove-post") != null) { - throw new PortletException("Wrong interceptor order"); - } - if (!"test1-remove-post".equals(request.getAttribute("test1-remove-post"))) { - throw new PortletException("Incorrect request attribute"); - } - request.removeAttribute("test1-remove-post"); - } - - @Override - public void afterRenderCompletion( - RenderRequest request, RenderResponse response, Object handler, Exception ex) - throws PortletException { - if (request.getAttribute("test2-remove-after") != null) { - throw new PortletException("Wrong interceptor order"); - } - request.removeAttribute("test1-remove-after"); - } - } - - - public static class MyHandlerInterceptor2 extends HandlerInterceptorAdapter { - - @Override - public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler) - throws PortletException { - if (request.getAttribute("test1-remove-post") == null) { - throw new PortletException("Wrong interceptor order"); - } - if ("true".equals(request.getParameter("abort"))) { - return false; - } - request.setAttribute("test2-remove-never", "test2-remove-never"); - request.setAttribute("test2-remove-post", "test2-remove-post"); - request.setAttribute("test2-remove-after", "test2-remove-after"); - return true; - } - - @Override - public void postHandleRender( - RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView) - throws PortletException { - if ("true".equals(request.getParameter("noView"))) { - modelAndView.clear(); - } - if (request.getAttribute("test1-remove-post") == null) { - throw new PortletException("Wrong interceptor order"); - } - if (!"test2-remove-post".equals(request.getAttribute("test2-remove-post"))) { - throw new PortletException("Incorrect request attribute"); - } - request.removeAttribute("test2-remove-post"); - } - - @Override - public void afterRenderCompletion( - RenderRequest request, RenderResponse response, Object handler, Exception ex) - throws Exception { - if (request.getAttribute("test1-remove-after") == null) { - throw new PortletException("Wrong interceptor order"); - } - request.removeAttribute("test2-remove-after"); - } - } - - - public static class MultipartCheckingHandler implements MyHandler { - - @Override - public void doSomething(PortletRequest request) throws PortletException, IllegalAccessException { - if (!(request instanceof MultipartActionRequest)) { - throw new PortletException("Not in a MultipartActionRequest"); - } - } - } - - - public static class MockMultipartResolver implements PortletMultipartResolver { - - @Override - public boolean isMultipart(ActionRequest request) { - return true; - } - - @Override - public MultipartActionRequest resolveMultipart(ActionRequest request) throws MultipartException { - if (request.getAttribute("fail") != null) { - throw new MaxUploadSizeExceededException(1000); - } - if (request instanceof MultipartActionRequest) { - throw new IllegalStateException("Already a multipart request"); - } - if (request.getAttribute("resolved") != null) { - throw new IllegalStateException("Already resolved"); - } - request.setAttribute("resolved", Boolean.TRUE); - MultiValueMap files = new LinkedMultiValueMap(); - files.set("someFile", new MockMultipartFile("someFile", "someContent".getBytes())); - Map params = new HashMap(); - params.put("someParam", new String[] {"someParam"}); - return new DefaultMultipartActionRequest(request, files, params, Collections.emptyMap()); - } - - @Override - public void cleanupMultipart(MultipartActionRequest request) { - if (request.getAttribute("cleanedUp") != null) { - throw new IllegalStateException("Already cleaned up"); - } - request.setAttribute("cleanedUp", Boolean.TRUE); - } - } - - - public static class TestApplicationListener implements ApplicationListener { - - public int counter = 0; - - @Override - public void onApplicationEvent(ApplicationEvent event) { - if (event instanceof PortletRequestHandledEvent) { - this.counter++; - } - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java deleted file mode 100644 index 0aa92526e2..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java +++ /dev/null @@ -1,758 +0,0 @@ -/* - * Copyright 2002-2015 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; - -import java.util.Locale; -import java.util.Map; -import javax.portlet.PortletContext; -import javax.portlet.PortletException; -import javax.portlet.PortletMode; -import javax.portlet.PortletSecurityException; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.StaticWebApplicationContext; -import org.springframework.web.multipart.MaxUploadSizeExceededException; -import org.springframework.web.portlet.context.PortletApplicationContextUtils; -import org.springframework.web.portlet.context.PortletConfigAwareBean; -import org.springframework.web.portlet.context.PortletContextAwareBean; -import org.springframework.web.portlet.multipart.MultipartActionRequest; -import org.springframework.web.portlet.multipart.PortletMultipartResolver; -import org.springframework.web.servlet.ViewRendererServlet; -import org.springframework.web.servlet.view.InternalResourceView; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Juergen Hoeller - * @author Dan McCallum - */ -public class DispatcherPortletTests { - - private final MockPortletConfig complexPortletConfig = new MockPortletConfig(new MockPortletContext(), "complex"); - - private final DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet(); - - - @Before - public void setUp() throws PortletException { - complexPortletConfig.addInitParameter("publishContext", "false"); - - complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class); - complexDispatcherPortlet.setNamespace("test"); - complexDispatcherPortlet.addRequiredProperty("publishContext"); - complexDispatcherPortlet.init(complexPortletConfig); - } - - private PortletContext getPortletContext() { - return complexPortletConfig.getPortletContext(); - } - - - @Test - public void dispatcherPortletGetPortletNameDoesNotFailWithoutConfig() { - DispatcherPortlet dp = new DispatcherPortlet(); - assertEquals(null, dp.getPortletConfig()); - assertEquals(null, dp.getPortletName()); - assertEquals(null, dp.getPortletContext()); - } - - @Test - public void dispatcherPortlets() { - assertTrue("Correct namespace", "test".equals(complexDispatcherPortlet.getNamespace())); - assertTrue("Correct attribute", - (FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "complex").equals(complexDispatcherPortlet.getPortletContextAttributeName())); - assertTrue("Context not published", - getPortletContext().getAttribute(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "complex") == null); - } - - @Test - public void portletModeParameterMappingHelp1() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.HELP); - request.setParameter("action", "help1"); - complexDispatcherPortlet.processAction(request, response); - String param = response.getRenderParameter("param"); - assertEquals("help1 was here", param); - } - - @Test - public void portletModeParameterMappingHelp2() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.HELP); - request.setParameter("action", "help2"); - complexDispatcherPortlet.processAction(request, response); - String param = response.getRenderParameter("param"); - assertEquals("help2 was here", param); - } - - @Test - public void portletModeParameterMappingInvalidHelpActionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.HELP); - request.setParameter("action", "help3"); - complexDispatcherPortlet.processAction(request, response); - String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); - assertNotNull(exceptionParam); - assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName())); - } - - @Test - public void portletModeParameterMappingInvalidHelpRenderRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.HELP); - request.setParameter("action", "help3"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - assertTrue(model.get("exception").getClass().equals(NoHandlerFoundException.class)); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-unavailable", view.getBeanName()); - } - - @Test - public void portletModeMappingValidEditActionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.EDIT); - request.addUserRole("role1"); - request.setParameter("action", "not mapped"); - request.setParameter("myParam", "not mapped"); - complexDispatcherPortlet.processAction(request, response); - assertEquals("edit was here", response.getRenderParameter("param")); - } - - @Test - public void portletModeMappingEditActionRequestWithUnauthorizedUserRole() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.EDIT); - request.addUserRole("role3"); - request.setParameter("action", "not mapped"); - request.setParameter("myParam", "not mapped"); - complexDispatcherPortlet.processAction(request, response); - String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); - assertNotNull(exception); - String name = PortletSecurityException.class.getName(); - assertTrue(exception.startsWith(name)); - } - - @Test - public void portletModeMappingValidViewRenderRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role2"); - request.setParameter("action", "not mapped"); - request.setParameter("myParam", "not mapped"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - assertEquals("view was here", model.get("result")); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("someViewName", view.getBeanName()); - } - - @Test - public void portletModeMappingViewRenderRequestWithUnauthorizedUserRole() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role3"); - request.setParameter("action", "not mapped"); - request.setParameter("myParam", "not mapped"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - Exception exception = (Exception) model.get("exception"); - assertNotNull(exception); - assertTrue(exception.getClass().equals(PortletSecurityException.class)); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void parameterMappingValidActionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.EDIT); - request.setParameter("action", "not mapped"); - request.setParameter("myParam", "test1"); - complexDispatcherPortlet.processAction(request, response); - assertEquals("test1-action", response.getRenderParameter("result")); - } - - @Test - public void parameterMappingValidRenderRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.setParameter("action", "not mapped"); - request.setParameter("myParam", "test2"); - complexDispatcherPortlet.doDispatch(request, response); - assertEquals("test2-view", response.getProperty("result")); - } - - @Test - public void unknownHandlerActionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setParameter("myParam", "unknown"); - complexDispatcherPortlet.processAction(request, response); - String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); - assertNotNull(exceptionParam); - assertTrue(exceptionParam.startsWith(PortletException.class.getName())); - assertTrue(exceptionParam.indexOf("No adapter for handler") != -1); - } - - @Test - public void unknownHandlerRenderRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "unknown"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - Exception exception = (Exception)model.get("exception"); - assertTrue(exception.getClass().equals(PortletException.class)); - assertTrue(exception.getMessage().indexOf("No adapter for handler") != -1); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void noDetectAllHandlerMappingsWithPortletModeActionRequest() throws Exception { - DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet(); - complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class); - complexDispatcherPortlet.setNamespace("test"); - complexDispatcherPortlet.setDetectAllHandlerMappings(false); - complexDispatcherPortlet.init(new MockPortletConfig(getPortletContext(), "complex")); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.EDIT); - complexDispatcherPortlet.processAction(request, response); - String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); - assertNotNull(exceptionParam); - assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName())); - } - - @Test - public void noDetectAllHandlerMappingsWithParameterRenderRequest() throws Exception { - DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet(); - complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class); - complexDispatcherPortlet.setNamespace("test"); - complexDispatcherPortlet.setDetectAllHandlerMappings(false); - complexDispatcherPortlet.init(new MockPortletConfig(getPortletContext(), "complex")); - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "test1"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - Exception exception = (Exception) model.get("exception"); - assertTrue(exception.getClass().equals(NoHandlerFoundException.class)); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-unavailable", view.getBeanName()); - } - - @Test - public void existingMultipartRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.EDIT); - ComplexPortletApplicationContext.MockMultipartResolver multipartResolver = - (ComplexPortletApplicationContext.MockMultipartResolver) - complexDispatcherPortlet.getPortletApplicationContext().getBean("portletMultipartResolver"); - MultipartActionRequest multipartRequest = multipartResolver.resolveMultipart(request); - complexDispatcherPortlet.processAction(multipartRequest, response); - multipartResolver.cleanupMultipart(multipartRequest); - assertNotNull(request.getAttribute("cleanedUp")); - } - - @Test - public void multipartResolutionFailed() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.EDIT); - request.addUserRole("role1"); - request.setAttribute("fail", Boolean.TRUE); - complexDispatcherPortlet.processAction(request, response); - String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER); - assertTrue(exception.startsWith(MaxUploadSizeExceededException.class.getName())); - } - - @Test - public void actionRequestHandledEvent() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - complexDispatcherPortlet.processAction(request, response); - ComplexPortletApplicationContext.TestApplicationListener listener = - (ComplexPortletApplicationContext.TestApplicationListener) - complexDispatcherPortlet.getPortletApplicationContext().getBean("testListener"); - assertEquals(1, listener.counter); - } - - @Test - public void renderRequestHandledEvent() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - ComplexPortletApplicationContext.TestApplicationListener listener = - (ComplexPortletApplicationContext.TestApplicationListener) - complexDispatcherPortlet.getPortletApplicationContext().getBean("testListener"); - assertEquals(1, listener.counter); - } - - @Test - public void publishEventsOff() throws Exception { - complexDispatcherPortlet.setPublishEvents(false); - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setParameter("action", "checker"); - complexDispatcherPortlet.processAction(request, response); - ComplexPortletApplicationContext.TestApplicationListener listener = - (ComplexPortletApplicationContext.TestApplicationListener) - complexDispatcherPortlet.getPortletApplicationContext().getBean("testListener"); - assertEquals(0, listener.counter); - } - - @Test - public void correctLocaleInRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "requestLocaleChecker"); - request.addPreferredLocale(Locale.CANADA); - complexDispatcherPortlet.doDispatch(request, response); - assertEquals("locale-ok", response.getContentAsString()); - } - - @Test - public void incorrectLocaleInRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "requestLocaleChecker"); - request.addPreferredLocale(Locale.ENGLISH); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - Exception exception = (Exception) model.get("exception"); - assertTrue(exception.getClass().equals(PortletException.class)); - assertEquals("Incorrect Locale in RenderRequest", exception.getMessage()); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void correctLocaleInLocaleContextHolder() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "contextLocaleChecker"); - request.addPreferredLocale(Locale.CANADA); - complexDispatcherPortlet.doDispatch(request, response); - assertEquals("locale-ok", response.getContentAsString()); - } - - @Test - public void incorrectLocaleInLocalContextHolder() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "contextLocaleChecker"); - request.addPreferredLocale(Locale.ENGLISH); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - Exception exception = (Exception) model.get("exception"); - assertTrue(exception.getClass().equals(PortletException.class)); - assertEquals("Incorrect Locale in LocaleContextHolder", exception.getMessage()); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void handlerInterceptorNoAbort() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role1"); - request.addParameter("abort", "false"); - complexDispatcherPortlet.doDispatch(request, response); - assertTrue(request.getAttribute("test1-remove-never") != null); - assertTrue(request.getAttribute("test1-remove-post") == null); - assertTrue(request.getAttribute("test1-remove-after") == null); - assertTrue(request.getAttribute("test2-remove-never") != null); - assertTrue(request.getAttribute("test2-remove-post") == null); - assertTrue(request.getAttribute("test2-remove-after") == null); - } - - @Test - public void handlerInterceptorAbort() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role1"); - request.addParameter("abort", "true"); - complexDispatcherPortlet.doDispatch(request, response); - assertTrue(request.getAttribute("test1-remove-never") != null); - assertTrue(request.getAttribute("test1-remove-post") != null); - assertTrue(request.getAttribute("test1-remove-after") == null); - assertTrue(request.getAttribute("test2-remove-never") == null); - assertTrue(request.getAttribute("test2-remove-post") == null); - assertTrue(request.getAttribute("test2-remove-after") == null); - } - - @Test - public void handlerInterceptorNotClearingModelAndView() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role1"); - request.addParameter("noView", "false"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - assertEquals("view was here", model.get("result")); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("someViewName", view.getBeanName()); - } - - @Test - public void handlerInterceptorClearingModelAndView() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role1"); - request.addParameter("noView", "true"); - complexDispatcherPortlet.doDispatch(request, response); - Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE); - assertNull(model); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertNull(view); - } - - @Test - public void parameterMappingInterceptorWithCorrectParam() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role1"); - request.addParameter("interceptingParam", "test1"); - complexDispatcherPortlet.processAction(request, response); - assertEquals("test1", response.getRenderParameter("interceptingParam")); - } - - @Test - public void parameterMappingInterceptorWithIncorrectParam() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setPortletMode(PortletMode.VIEW); - request.addUserRole("role1"); - request.addParameter("incorrect", "test1"); - complexDispatcherPortlet.processAction(request, response); - assertNull(response.getRenderParameter("incorrect")); - assertNull(response.getRenderParameter("interceptingParam")); - } - - @Test - public void portletHandlerAdapterActionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setParameter("myParam", "myPortlet"); - complexDispatcherPortlet.processAction(request, response); - assertEquals("myPortlet action called", response.getRenderParameter("result")); - ComplexPortletApplicationContext.MyPortlet myPortlet = - (ComplexPortletApplicationContext.MyPortlet) complexDispatcherPortlet.getPortletApplicationContext().getBean("myPortlet"); - assertEquals("complex", myPortlet.getPortletConfig().getPortletName()); - assertEquals(getPortletContext(), myPortlet.getPortletConfig().getPortletContext()); - assertEquals(complexDispatcherPortlet.getPortletContext(), myPortlet.getPortletConfig().getPortletContext()); - complexDispatcherPortlet.destroy(); - assertNull(myPortlet.getPortletConfig()); - } - - @Test - public void portletHandlerAdapterRenderRequest() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - request.setParameter("myParam", "myPortlet"); - complexDispatcherPortlet.doDispatch(request, response); - assertEquals("myPortlet was here", response.getContentAsString()); - ComplexPortletApplicationContext.MyPortlet myPortlet = - (ComplexPortletApplicationContext.MyPortlet) - complexDispatcherPortlet.getPortletApplicationContext().getBean("myPortlet"); - assertEquals("complex", myPortlet.getPortletConfig().getPortletName()); - assertEquals(getPortletContext(), myPortlet.getPortletConfig().getPortletContext()); - assertEquals(complexDispatcherPortlet.getPortletContext(), - myPortlet.getPortletConfig().getPortletContext()); - complexDispatcherPortlet.destroy(); - assertNull(myPortlet.getPortletConfig()); - } - - @Test - public void modelAndViewDefiningExceptionInMappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception1"); - request.addParameter("fail", "yes"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-modelandview", view.getBeanName()); - } - - @Test - public void modelAndViewDefiningExceptionInUnmappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception2"); - request.addParameter("fail", "yes"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-modelandview", view.getBeanName()); - } - - @Test - public void illegalAccessExceptionInMappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception1"); - request.addParameter("access", "illegal"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-exception", view.getBeanName()); - } - - @Test - public void illegalAccessExceptionInUnmappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception2"); - request.addParameter("access", "illegal"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-illegalaccess", view.getBeanName()); - } - - @Test - public void portletRequestBindingExceptionInMappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception1"); - request.addParameter("binding", "should fail"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-exception", view.getBeanName()); - } - - @Test - public void portletRequestBindingExceptionInUnmappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception2"); - request.addParameter("binding", "should fail"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-binding", view.getBeanName()); - } - - @Test - public void illegalArgumentExceptionInMappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception1"); - request.addParameter("unknown", ""); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-runtime", view.getBeanName()); - } - - @Test - public void illegalArgumentExceptionInUnmappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception2"); - request.addParameter("unknown", ""); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void exceptionInMappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception1"); - request.addParameter("generic", "123"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-exception", view.getBeanName()); - } - - @Test - public void exceptionInUnmappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception2"); - request.addParameter("generic", "123"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void runtimeExceptionInMappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception1"); - request.addParameter("runtime", "true"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-runtime", view.getBeanName()); - } - - @Test - public void runtimeExceptionInUnmappedHandler() throws Exception { - MockRenderRequest request = new MockRenderRequest(); - request.setPortletMode(PortletMode.HELP); - request.addParameter("myParam", "exception2"); - request.addParameter("runtime", "true"); - MockRenderResponse response = new MockRenderResponse(); - complexDispatcherPortlet.doDispatch(request, response); - InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE); - assertEquals("failed-default-1", view.getBeanName()); - } - - @Test - public void getMessage() { - String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test", null, Locale.ENGLISH); - assertEquals("test message", message); - } - - @Test - public void getMessageOtherLocale() { - String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test", null, Locale.CANADA); - assertEquals("Canadian & test message", message); - } - - @Test - public void getMessageWithArgs() { - Object[] args = new String[] {"this", "that"}; - String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test.args", args, Locale.ENGLISH); - assertEquals("test this and that", message); - } - - @Test - public void portletApplicationContextLookup() { - MockPortletContext portletContext = new MockPortletContext(); - ApplicationContext ac = PortletApplicationContextUtils.getWebApplicationContext(portletContext); - assertNull(ac); - try { - ac = PortletApplicationContextUtils.getRequiredWebApplicationContext(portletContext); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { -// expected - } - portletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, - new StaticWebApplicationContext()); - try { - ac = PortletApplicationContextUtils.getRequiredWebApplicationContext(portletContext); - assertNotNull(ac); - } - catch (IllegalStateException ex) { - fail("Should not have thrown IllegalStateException: " + ex.getMessage()); - } - } - - @Test - public void dispatcherPortletRefresh() throws PortletException { - MockPortletContext portletContext = new MockPortletContext("org/springframework/web/portlet/context"); - DispatcherPortlet portlet = new DispatcherPortlet(); - - portlet.init(new MockPortletConfig(portletContext, "empty")); - PortletContextAwareBean contextBean = (PortletContextAwareBean) - portlet.getPortletApplicationContext().getBean("portletContextAwareBean"); - PortletConfigAwareBean configBean = (PortletConfigAwareBean) - portlet.getPortletApplicationContext().getBean("portletConfigAwareBean"); - assertSame(portletContext, contextBean.getPortletContext()); - assertSame(portlet.getPortletConfig(), configBean.getPortletConfig()); - PortletMultipartResolver multipartResolver = portlet.getMultipartResolver(); - assertNotNull(multipartResolver); - - portlet.refresh(); - - PortletContextAwareBean contextBean2 = (PortletContextAwareBean) - portlet.getPortletApplicationContext().getBean("portletContextAwareBean"); - PortletConfigAwareBean configBean2 = (PortletConfigAwareBean) - portlet.getPortletApplicationContext().getBean("portletConfigAwareBean"); - assertSame(portletContext, contextBean.getPortletContext()); - assertSame(portlet.getPortletConfig(), configBean.getPortletConfig()); - assertTrue(contextBean != contextBean2); - assertTrue(configBean != configBean2); - PortletMultipartResolver multipartResolver2 = portlet.getMultipartResolver(); - assertTrue(multipartResolver != multipartResolver2); - - portlet.destroy(); - } - - @Test - public void dispatcherPortletContextRefresh() throws PortletException { - MockPortletContext portletContext = new MockPortletContext("org/springframework/web/portlet/context"); - DispatcherPortlet portlet = new DispatcherPortlet(); - - portlet.init(new MockPortletConfig(portletContext, "empty")); - PortletContextAwareBean contextBean = (PortletContextAwareBean) - portlet.getPortletApplicationContext().getBean("portletContextAwareBean"); - PortletConfigAwareBean configBean = (PortletConfigAwareBean) - portlet.getPortletApplicationContext().getBean("portletConfigAwareBean"); - assertSame(portletContext, contextBean.getPortletContext()); - assertSame(portlet.getPortletConfig(), configBean.getPortletConfig()); - PortletMultipartResolver multipartResolver = portlet.getMultipartResolver(); - assertNotNull(multipartResolver); - - ((ConfigurableApplicationContext) portlet.getPortletApplicationContext()).refresh(); - - PortletContextAwareBean contextBean2 = (PortletContextAwareBean) - portlet.getPortletApplicationContext().getBean("portletContextAwareBean"); - PortletConfigAwareBean configBean2 = (PortletConfigAwareBean) - portlet.getPortletApplicationContext().getBean("portletConfigAwareBean"); - assertSame(portletContext, contextBean.getPortletContext()); - assertSame(portlet.getPortletConfig(), configBean.getPortletConfig()); - assertTrue(contextBean != contextBean2); - assertTrue(configBean != configBean2); - PortletMultipartResolver multipartResolver2 = portlet.getMultipartResolver(); - assertTrue(multipartResolver != multipartResolver2); - - portlet.destroy(); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java deleted file mode 100644 index 19766ef882..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/GenericPortletBeanTests.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2002-2015 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; - -import javax.portlet.PortletContext; -import javax.portlet.PortletException; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - */ -public class GenericPortletBeanTests { - - private final PortletContext portletContext = new MockPortletContext(); - - private final MockPortletConfig portletConfig = new MockPortletConfig(portletContext); - - @Test - public void initParameterSet() throws Exception { - String testValue = "testValue"; - portletConfig.addInitParameter("testParam", testValue); - TestPortletBean portletBean = new TestPortletBean(); - assertNull(portletBean.getTestParam()); - portletBean.init(portletConfig); - assertNotNull(portletBean.getTestParam()); - assertEquals(testValue, portletBean.getTestParam()); - } - - @Test - public void initParameterNotSet() throws Exception { - TestPortletBean portletBean = new TestPortletBean(); - assertNull(portletBean.getTestParam()); - portletBean.init(portletConfig); - assertNull(portletBean.getTestParam()); - } - - @Test - public void multipleInitParametersSet() throws Exception { - String testValue = "testValue"; - String anotherValue = "anotherValue"; - portletConfig.addInitParameter("testParam", testValue); - portletConfig.addInitParameter("anotherParam", anotherValue); - portletConfig.addInitParameter("unknownParam", "unknownValue"); - TestPortletBean portletBean = new TestPortletBean(); - assertNull(portletBean.getTestParam()); - assertNull(portletBean.getAnotherParam()); - portletBean.init(portletConfig); - assertNotNull(portletBean.getTestParam()); - assertNotNull(portletBean.getAnotherParam()); - assertEquals(testValue, portletBean.getTestParam()); - assertEquals(anotherValue, portletBean.getAnotherParam()); - } - - @Test - public void multipleInitParametersOnlyOneSet() throws Exception { - String testValue = "testValue"; - portletConfig.addInitParameter("testParam", testValue); - portletConfig.addInitParameter("unknownParam", "unknownValue"); - TestPortletBean portletBean = new TestPortletBean(); - assertNull(portletBean.getTestParam()); - assertNull(portletBean.getAnotherParam()); - portletBean.init(portletConfig); - assertNotNull(portletBean.getTestParam()); - assertEquals(testValue, portletBean.getTestParam()); - assertNull(portletBean.getAnotherParam()); - } - - @Test - public void requiredInitParameterSet() throws Exception { - String testParam = "testParam"; - String testValue = "testValue"; - portletConfig.addInitParameter(testParam, testValue); - TestPortletBean portletBean = new TestPortletBean(); - portletBean.addRequiredProperty(testParam); - assertNull(portletBean.getTestParam()); - portletBean.init(portletConfig); - assertNotNull(portletBean.getTestParam()); - assertEquals(testValue, portletBean.getTestParam()); - } - - @Test - public void requiredInitParameterNotSet() throws Exception { - String testParam = "testParam"; - TestPortletBean portletBean = new TestPortletBean(); - portletBean.addRequiredProperty(testParam); - assertNull(portletBean.getTestParam()); - try { - portletBean.init(portletConfig); - fail("should have thrown PortletException"); - } - catch (PortletException ex) { - // expected - } - } - - @Test - public void requiredInitParameterNotSetOtherParameterNotSet() throws Exception { - String testParam = "testParam"; - String testValue = "testValue"; - portletConfig.addInitParameter(testParam, testValue); - TestPortletBean portletBean = new TestPortletBean(); - portletBean.addRequiredProperty("anotherParam"); - assertNull(portletBean.getTestParam()); - try { - portletBean.init(portletConfig); - fail("should have thrown PortletException"); - } - catch (PortletException ex) { - // expected - } - assertNull(portletBean.getTestParam()); - } - - @Test - public void unknownRequiredInitParameter() throws Exception { - String testParam = "testParam"; - String testValue = "testValue"; - portletConfig.addInitParameter(testParam, testValue); - TestPortletBean portletBean = new TestPortletBean(); - portletBean.addRequiredProperty("unknownParam"); - assertNull(portletBean.getTestParam()); - try { - portletBean.init(portletConfig); - fail("should have thrown PortletException"); - } - catch (PortletException ex) { - // expected - } - assertNull(portletBean.getTestParam()); - } - - - @SuppressWarnings("unused") - private static class TestPortletBean extends GenericPortletBean { - - private String testParam; - private String anotherParam; - - public void setTestParam(String value) { - this.testParam = value; - } - - public String getTestParam() { - return this.testParam; - } - - public void setAnotherParam(String value) { - this.anotherParam = value; - } - - public String getAnotherParam() { - return this.anotherParam; - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java deleted file mode 100644 index 29725a79e5..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2002-2015 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; - -import java.beans.PropertyEditorSupport; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.Set; - -import org.junit.Test; - -import org.springframework.beans.propertyeditors.CustomDateEditor; -import org.springframework.beans.propertyeditors.StringArrayPropertyEditor; -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.validation.BindingResult; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - */ -public class PortletRequestDataBinderTests { - - private final MockPortletRequest request = new MockPortletRequest(); - - private final TestBean bean = new TestBean(); - - @Test - public void simpleBind() { - - request.addParameter("age", "35"); - request.addParameter("name", "test"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - assertEquals(35, bean.getAge()); - assertEquals("test", bean.getName()); - } - - @Test - public void nestedBind() { - bean.setSpouse(new TestBean()); - - request.addParameter("spouse.name", "test"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - assertNotNull(bean.getSpouse()); - assertEquals("test", bean.getSpouse().getName()); - } - - @Test - public void nestedBindWithPropertyEditor() { - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() { - @Override - public void setAsText(String text) throws IllegalArgumentException { - setValue(new TestBean(text)); - } - }); - - request.addParameter("spouse", "test"); - request.addParameter("spouse.age", "32"); - binder.bind(request); - - assertNotNull(bean.getSpouse()); - assertEquals("test", bean.getSpouse().getName()); - assertEquals(32, bean.getSpouse().getAge()); - } - - @Test - public void bindingMismatch() { - bean.setAge(30); - - request.addParameter("age", "zzz"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - BindingResult error = binder.getBindingResult(); - assertNotNull(error.getFieldError("age")); - assertEquals("typeMismatch", error.getFieldError("age").getCode()); - assertEquals(30, bean.getAge()); - } - - @Test - public void bindingStringWithCommaSeparatedValue() throws Exception { - request.addParameter("stringArray", "test1,test2"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - assertNotNull(bean.getStringArray()); - assertEquals(1, bean.getStringArray().length); - assertEquals("test1,test2", bean.getStringArray()[0]); - } - - @Test - public void bindingStringArrayWithSplitting() { - request.addParameter("stringArray", "test1,test2"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.registerCustomEditor(String[].class, new StringArrayPropertyEditor()); - binder.bind(request); - - assertNotNull(bean.getStringArray()); - assertEquals(2, bean.getStringArray().length); - assertEquals("test1", bean.getStringArray()[0]); - assertEquals("test2", bean.getStringArray()[1]); - } - - @Test - public void bindingList() { - request.addParameter("someList[0]", "test1"); - request.addParameter("someList[1]", "test2"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - assertNotNull(bean.getSomeList()); - assertEquals(2, bean.getSomeList().size()); - assertEquals("test1", bean.getSomeList().get(0)); - assertEquals("test2", bean.getSomeList().get(1)); - } - - @Test - public void bindingMap() { - request.addParameter("someMap['key1']", "val1"); - request.addParameter("someMap['key2']", "val2"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - assertNotNull(bean.getSomeMap()); - assertEquals(2, bean.getSomeMap().size()); - assertEquals("val1", bean.getSomeMap().get("key1")); - assertEquals("val2", bean.getSomeMap().get("key2")); - } - - @Test - public void bindingSet() { - Set set = new LinkedHashSet(2); - set.add(new TestBean("test1")); - set.add(new TestBean("test2")); - bean.setSomeSet(set); - - request.addParameter("someSet[0].age", "35"); - request.addParameter("someSet[1].age", "36"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.bind(request); - - assertNotNull(bean.getSomeSet()); - assertEquals(2, bean.getSomeSet().size()); - - Iterator iter = bean.getSomeSet().iterator(); - - TestBean bean1 = (TestBean) iter.next(); - assertEquals("test1", bean1.getName()); - assertEquals(35, bean1.getAge()); - - TestBean bean2 = (TestBean) iter.next(); - assertEquals("test2", bean2.getName()); - assertEquals(36, bean2.getAge()); - } - - @Test - public void bindingDate() throws Exception { - SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); - Date expected = dateFormat.parse("06-03-2006"); - - request.addParameter("date", "06-03-2006"); - - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - binder.bind(request); - - assertEquals(expected, bean.getDate()); - } - - @Test - public void bindingFailsWhenMissingRequiredParam() { - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.setRequiredFields(new String[] {"age", "name"}); - - request.addParameter("age", "35"); - binder.bind(request); - - BindingResult error = binder.getBindingResult(); - assertNotNull(error.getFieldError("name")); - assertEquals("required", error.getFieldError("name").getCode()); - } - - @Test - public void bindingExcludesDisallowedParam() { - PortletRequestDataBinder binder = new PortletRequestDataBinder(bean); - binder.setAllowedFields(new String[] {"age"}); - - request.addParameter("age", "35"); - request.addParameter("name", "test"); - binder.bind(request); - - assertEquals(35, bean.getAge()); - assertNull(bean.getName()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java deleted file mode 100644 index 405f12060e..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestParameterPropertyValuesTests.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2002-2015 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; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletRequest; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - */ -public class PortletRequestParameterPropertyValuesTests { - - private final MockPortletRequest request = new MockPortletRequest(); - - @Test - public void withNoParams() { - PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request); - assertTrue("Should not have any property values", pvs.getPropertyValues().length == 0); - } - - @Test - public void withNoPrefix() { - request.addParameter("param", "value"); - PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request); - assertEquals("value", pvs.getPropertyValue("param").getValue()); - } - - @Test - public void withPrefix() { - request.addParameter("test_param", "value"); - PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test"); - assertTrue(pvs.contains("param")); - assertFalse(pvs.contains("test_param")); - assertEquals("value", pvs.getPropertyValue("param").getValue()); - } - - @Test - public void withPrefixAndOverridingSeparator() { - request.addParameter("test.param", "value"); - request.addParameter("test_another", "anotherValue"); - request.addParameter("some.other", "someValue"); - PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test", "."); - assertFalse(pvs.contains("test.param")); - assertFalse(pvs.contains("test_another")); - assertFalse(pvs.contains("some.other")); - assertFalse(pvs.contains("another")); - assertFalse(pvs.contains("other")); - assertTrue(pvs.contains("param")); - assertEquals("value", pvs.getPropertyValue("param").getValue()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java deleted file mode 100644 index 228eadd899..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java +++ /dev/null @@ -1,458 +0,0 @@ -/* - * Copyright 2002-2013 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; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.tests.Assume; -import org.springframework.tests.TestGroup; -import org.springframework.util.StopWatch; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * @author Juergen Hoeller - * @author Mark Fisher - */ -public class PortletRequestUtilsTests { - - @Test - public void testIntParameter() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param1", "5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertEquals(PortletRequestUtils.getIntParameter(request, "param1"), new Integer(5)); - assertEquals(PortletRequestUtils.getIntParameter(request, "param1", 6), 5); - assertEquals(PortletRequestUtils.getRequiredIntParameter(request, "param1"), 5); - - assertEquals(PortletRequestUtils.getIntParameter(request, "param2", 6), 6); - try { - PortletRequestUtils.getRequiredIntParameter(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - assertEquals(PortletRequestUtils.getIntParameter(request, "param3"), null); - assertEquals(PortletRequestUtils.getIntParameter(request, "param3", 6), 6); - try { - PortletRequestUtils.getRequiredIntParameter(request, "param3"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - try { - PortletRequestUtils.getRequiredIntParameter(request, "paramEmpty"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testIntParameters() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param", new String[] {"1", "2", "3"}); - - request.addParameter("param2", "1"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - int[] array = new int[] { 1, 2, 3 }; - int[] values = PortletRequestUtils.getRequiredIntParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - - try { - PortletRequestUtils.getRequiredIntParameters(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testLongParameter() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param1", "5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertEquals(PortletRequestUtils.getLongParameter(request, "param1"), new Long(5L)); - assertEquals(PortletRequestUtils.getLongParameter(request, "param1", 6L), 5L); - assertEquals(PortletRequestUtils.getRequiredIntParameter(request, "param1"), 5L); - assertEquals(PortletRequestUtils.getLongParameter(request, "param2", 6L), 6L); - - try { - PortletRequestUtils.getRequiredLongParameter(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - assertEquals(PortletRequestUtils.getLongParameter(request, "param3"), null); - assertEquals(PortletRequestUtils.getLongParameter(request, "param3", 6L), 6L); - try { - PortletRequestUtils.getRequiredLongParameter(request, "param3"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - try { - PortletRequestUtils.getRequiredLongParameter(request, "paramEmpty"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testLongParameters() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.setParameter("param", new String[] {"1", "2", "3"}); - - request.setParameter("param2", "0"); - request.setParameter("param2", "1"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - long[] array = new long[] { 1L, 2L, 3L }; - long[] values = PortletRequestUtils.getRequiredLongParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - - try { - PortletRequestUtils.getRequiredLongParameters(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - request.setParameter("param2", new String[] {"1", "2"}); - values = PortletRequestUtils.getRequiredLongParameters(request, "param2"); - assertEquals(2, values.length); - assertEquals(1, values[0]); - assertEquals(2, values[1]); - } - - @Test - public void testFloatParameter() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param1", "5.5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertTrue(PortletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f))); - assertTrue(PortletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f); - assertTrue(PortletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f); - - assertTrue(PortletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f); - try { - PortletRequestUtils.getRequiredFloatParameter(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - assertTrue(PortletRequestUtils.getFloatParameter(request, "param3") == null); - assertTrue(PortletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f); - try { - PortletRequestUtils.getRequiredFloatParameter(request, "param3"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - try { - PortletRequestUtils.getRequiredFloatParameter(request, "paramEmpty"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testFloatParameters() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param", new String[] {"1.5", "2.5", "3"}); - - request.addParameter("param2", "1.5"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - float[] array = new float[] { 1.5F, 2.5F, 3 }; - float[] values = PortletRequestUtils.getRequiredFloatParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i], 0); - } - - try { - PortletRequestUtils.getRequiredFloatParameters(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testDoubleParameter() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param1", "5.5"); - request.addParameter("param2", "e"); - request.addParameter("paramEmpty", ""); - - assertTrue(PortletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5))); - assertTrue(PortletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5); - assertTrue(PortletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5); - - assertTrue(PortletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5); - try { - PortletRequestUtils.getRequiredDoubleParameter(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - assertTrue(PortletRequestUtils.getDoubleParameter(request, "param3") == null); - assertTrue(PortletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5); - try { - PortletRequestUtils.getRequiredDoubleParameter(request, "param3"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - try { - PortletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testDoubleParameters() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param", new String[] {"1.5", "2.5", "3"}); - - request.addParameter("param2", "1.5"); - request.addParameter("param2", "2"); - request.addParameter("param2", "bogus"); - - double[] array = new double[] { 1.5, 2.5, 3 }; - double[] values = PortletRequestUtils.getRequiredDoubleParameters(request, "param"); - assertEquals(3, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i], 0); - } - - try { - PortletRequestUtils.getRequiredDoubleParameters(request, "param2"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - } - - @Test - public void testBooleanParameter() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param1", "true"); - request.addParameter("param2", "e"); - request.addParameter("param4", "yes"); - request.addParameter("param5", "1"); - request.addParameter("paramEmpty", ""); - - assertTrue(PortletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE)); - assertTrue(PortletRequestUtils.getBooleanParameter(request, "param1", false)); - assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param1")); - - assertFalse(PortletRequestUtils.getBooleanParameter(request, "param2", true)); - assertFalse(PortletRequestUtils.getRequiredBooleanParameter(request, "param2")); - - assertTrue(PortletRequestUtils.getBooleanParameter(request, "param3") == null); - assertTrue(PortletRequestUtils.getBooleanParameter(request, "param3", true)); - try { - PortletRequestUtils.getRequiredBooleanParameter(request, "param3"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - assertTrue(PortletRequestUtils.getBooleanParameter(request, "param4", false)); - assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param4")); - - assertTrue(PortletRequestUtils.getBooleanParameter(request, "param5", false)); - assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param5")); - assertFalse(PortletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty")); - } - - @Test - public void testBooleanParameters() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param", new String[] {"true", "yes", "off", "1", "bogus"}); - - request.addParameter("param2", "false"); - request.addParameter("param2", "true"); - request.addParameter("param2", ""); - - boolean[] array = new boolean[] { true, true, false, true, false }; - boolean[] values = PortletRequestUtils.getRequiredBooleanParameters(request, "param"); - assertEquals(5, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - - array = new boolean[] { false, true, false }; - values = PortletRequestUtils.getRequiredBooleanParameters(request, "param2"); - assertEquals(array.length, values.length); - for (int i = 0; i < array.length; i++) { - assertEquals(array[i], values[i]); - } - } - - @Test - public void testStringParameter() throws PortletRequestBindingException { - MockPortletRequest request = new MockPortletRequest(); - request.addParameter("param1", "str"); - request.addParameter("paramEmpty", ""); - - assertEquals("str", PortletRequestUtils.getStringParameter(request, "param1")); - assertEquals("str", PortletRequestUtils.getStringParameter(request, "param1", "string")); - assertEquals("str", PortletRequestUtils.getRequiredStringParameter(request, "param1")); - - assertEquals(null, PortletRequestUtils.getStringParameter(request, "param3")); - assertEquals("string", PortletRequestUtils.getStringParameter(request, "param3", "string")); - try { - PortletRequestUtils.getRequiredStringParameter(request, "param3"); - fail("Should have thrown PortletRequestBindingException"); - } - catch (PortletRequestBindingException ex) { - // expected - } - - assertEquals("", PortletRequestUtils.getStringParameter(request, "paramEmpty")); - assertEquals("", PortletRequestUtils.getRequiredStringParameter(request, "paramEmpty")); - } - - @Test - public void testGetIntParameterWithDefaultValueHandlingIsFastEnough() { - Assume.group(TestGroup.PERFORMANCE); - MockPortletRequest request = new MockPortletRequest(); - StopWatch sw = new StopWatch(); - sw.start(); - for (int i = 0; i < 1000000; i++) { - PortletRequestUtils.getIntParameter(request, "nonExistingParam", 0); - } - sw.stop(); - assertThat(sw.getTotalTimeMillis(), lessThan(250L)); - } - - @Test - public void testGetLongParameterWithDefaultValueHandlingIsFastEnough() { - Assume.group(TestGroup.PERFORMANCE); - MockPortletRequest request = new MockPortletRequest(); - StopWatch sw = new StopWatch(); - sw.start(); - for (int i = 0; i < 1000000; i++) { - PortletRequestUtils.getLongParameter(request, "nonExistingParam", 0); - } - sw.stop(); - assertThat(sw.getTotalTimeMillis(), lessThan(250L)); - } - - @Test - public void testGetFloatParameterWithDefaultValueHandlingIsFastEnough() { - Assume.group(TestGroup.PERFORMANCE); - MockPortletRequest request = new MockPortletRequest(); - StopWatch sw = new StopWatch(); - sw.start(); - for (int i = 0; i < 1000000; i++) { - PortletRequestUtils.getFloatParameter(request, "nonExistingParam", 0f); - } - sw.stop(); - assertThat(sw.getTotalTimeMillis(), lessThan(350L)); - } - - @Test - public void testGetDoubleParameterWithDefaultValueHandlingIsFastEnough() { - Assume.group(TestGroup.PERFORMANCE); - MockPortletRequest request = new MockPortletRequest(); - StopWatch sw = new StopWatch(); - sw.start(); - for (int i = 0; i < 1000000; i++) { - PortletRequestUtils.getDoubleParameter(request, "nonExistingParam", 0d); - } - sw.stop(); - assertThat(sw.getTotalTimeMillis(), lessThan(250L)); - } - - @Test - public void testGetBooleanParameterWithDefaultValueHandlingIsFastEnough() { - Assume.group(TestGroup.PERFORMANCE); - MockPortletRequest request = new MockPortletRequest(); - StopWatch sw = new StopWatch(); - sw.start(); - for (int i = 0; i < 1000000; i++) { - PortletRequestUtils.getBooleanParameter(request, "nonExistingParam", false); - } - sw.stop(); - assertThat(sw.getTotalTimeMillis(), lessThan(250L)); - } - - @Test - public void testGetStringParameterWithDefaultValueHandlingIsFastEnough() { - Assume.group(TestGroup.PERFORMANCE); - MockPortletRequest request = new MockPortletRequest(); - StopWatch sw = new StopWatch(); - sw.start(); - for (int i = 0; i < 1000000; i++) { - PortletRequestUtils.getStringParameter(request, "nonExistingParam", "defaultValue"); - } - sw.stop(); - assertThat(sw.getTotalTimeMillis(), lessThan(250L)); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java deleted file mode 100644 index 9a9158fcff..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2002-2015 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.context; - -import javax.servlet.ServletException; - -import org.junit.Test; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.AbstractApplicationContextTests; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.TestListener; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.web.context.ConfigurableWebApplicationContext; - -import static org.junit.Assert.*; - -/** - * Should ideally be eliminated. Copied when splitting .testsuite up into individual bundles. - * - * @see org.springframework.web.context.XmlWebApplicationContextTests - * - * @author Rod Johnson - * @author Juergen Hoeller - * @author Chris Beams - */ -public abstract class AbstractXmlWebApplicationContextTests extends AbstractApplicationContextTests { - - private ConfigurableWebApplicationContext root; - - - /** - * Overridden as we can't trust superclass method - * @see org.springframework.context.AbstractApplicationContextTests#testEvents() - */ - @Override - protected void doTestEvents(TestListener listener, TestListener parentListener, - MyEvent event) { - TestListener listenerBean = (TestListener) this.applicationContext.getBean("testListener"); - TestListener parentListenerBean = (TestListener) this.applicationContext.getParent().getBean("parentListener"); - super.doTestEvents(listenerBean, parentListenerBean, event); - - }; - - @Test - @Override - public void count() { - assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(), - this.applicationContext.getBeanDefinitionCount() == 14); - } - - @Test - public void contextNesting() { - TestBean father = (TestBean) this.applicationContext.getBean("father"); - assertTrue("Bean from root context", father != null); - assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend")); - - TestBean rod = (TestBean) this.applicationContext.getBean("rod"); - assertTrue("Bean from child context", "Rod".equals(rod.getName())); - assertTrue("Bean has external reference", rod.getSpouse() == father); - assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend")); - - rod = (TestBean) this.root.getBean("rod"); - assertTrue("Bean from root context", "Roderick".equals(rod.getName())); - assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend")); - } - - @Test - public void initializingBeanAndInitMethod() throws Exception { - assertFalse(InitAndIB.constructed); - InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib"); - assertTrue(InitAndIB.constructed); - assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked); - assertTrue(!iib.destroyed && !iib.customDestroyed); - this.applicationContext.close(); - assertTrue(!iib.destroyed && !iib.customDestroyed); - ConfigurableApplicationContext parent = (ConfigurableApplicationContext) this.applicationContext.getParent(); - parent.close(); - assertTrue(iib.destroyed && iib.customDestroyed); - parent.close(); - assertTrue(iib.destroyed && iib.customDestroyed); - } - - - public static class InitAndIB implements InitializingBean, DisposableBean { - - public static boolean constructed; - - public boolean afterPropertiesSetInvoked, initMethodInvoked, destroyed, customDestroyed; - - public InitAndIB() { - constructed = true; - } - - @Override - public void afterPropertiesSet() { - if (this.initMethodInvoked) - fail(); - this.afterPropertiesSetInvoked = true; - } - - /** Init method */ - public void customInit() throws ServletException { - if (!this.afterPropertiesSetInvoked) - fail(); - this.initMethodInvoked = true; - } - - @Override - public void destroy() { - if (this.customDestroyed) - fail(); - if (this.destroyed) { - throw new IllegalStateException("Already destroyed"); - } - this.destroyed = true; - } - - public void customDestroy() { - if (!this.destroyed) - fail(); - if (this.customDestroyed) { - throw new IllegalStateException("Already customDestroyed"); - } - this.customDestroyed = true; - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java deleted file mode 100644 index 999ba33f80..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2002-2013 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.context; - -import javax.portlet.PortletContext; -import javax.portlet.PortletSession; -import javax.servlet.ServletContextEvent; - -import org.junit.Test; - -import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.ServletWrappingPortletContext; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.tests.sample.beans.DerivedTestBean; -import org.springframework.web.context.ContextCleanupListener; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.support.GenericWebApplicationContext; - -import static org.junit.Assert.*; - -/** - * @author Juergen Hoeller - */ -public class PortletApplicationContextScopeTests { - - private static final String NAME = "scoped"; - - - private ConfigurablePortletApplicationContext initApplicationContext(String scope) { - MockServletContext sc = new MockServletContext(); - GenericWebApplicationContext rac = new GenericWebApplicationContext(sc); - rac.refresh(); - PortletContext pc = new ServletWrappingPortletContext(sc); - StaticPortletApplicationContext ac = new StaticPortletApplicationContext(); - ac.setParent(rac); - ac.setPortletContext(pc); - GenericBeanDefinition bd = new GenericBeanDefinition(); - bd.setBeanClass(DerivedTestBean.class); - bd.setScope(scope); - ac.registerBeanDefinition(NAME, bd); - ac.refresh(); - return ac; - } - - @Test - public void testRequestScope() { - WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_REQUEST); - MockRenderRequest request = new MockRenderRequest(); - PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request); - RequestContextHolder.setRequestAttributes(requestAttributes); - try { - assertNull(request.getAttribute(NAME)); - DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, request.getAttribute(NAME)); - assertSame(bean, ac.getBean(NAME)); - requestAttributes.requestCompleted(); - assertTrue(bean.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } - } - - @Test - public void testSessionScope() { - WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_SESSION); - MockRenderRequest request = new MockRenderRequest(); - PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request); - RequestContextHolder.setRequestAttributes(requestAttributes); - try { - assertNull(request.getPortletSession().getAttribute(NAME)); - DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, request.getPortletSession().getAttribute(NAME)); - assertSame(bean, ac.getBean(NAME)); - request.getPortletSession().invalidate(); - assertTrue(bean.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } - } - - @Test - public void testGlobalSessionScope() { - WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_GLOBAL_SESSION); - MockRenderRequest request = new MockRenderRequest(); - PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request); - RequestContextHolder.setRequestAttributes(requestAttributes); - try { - assertNull(request.getPortletSession().getAttribute(NAME, PortletSession.APPLICATION_SCOPE)); - DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, request.getPortletSession().getAttribute(NAME, PortletSession.APPLICATION_SCOPE)); - assertSame(bean, ac.getBean(NAME)); - request.getPortletSession().invalidate(); - assertTrue(bean.wasDestroyed()); - } - finally { - RequestContextHolder.setRequestAttributes(null); - } - } - - @Test - public void testApplicationScope() { - ConfigurablePortletApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION); - assertNull(ac.getPortletContext().getAttribute(NAME)); - DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class); - assertSame(bean, ac.getPortletContext().getAttribute(NAME)); - assertSame(bean, ac.getBean(NAME)); - new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext())); - assertTrue(bean.wasDestroyed()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletConfigAwareBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletConfigAwareBean.java deleted file mode 100644 index a5186f3b65..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletConfigAwareBean.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import javax.portlet.PortletConfig; - -/** - * @author Mark Fisher - */ -public class PortletConfigAwareBean implements PortletConfigAware { - - private PortletConfig portletConfig; - - @Override - public void setPortletConfig(PortletConfig portletConfig) { - this.portletConfig = portletConfig; - } - - public PortletConfig getPortletConfig() { - return portletConfig; - } -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareBean.java deleted file mode 100644 index 0773459f5e..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareBean.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 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.context; - -import javax.portlet.PortletContext; - -/** - * @author Mark Fisher - */ -public class PortletContextAwareBean implements PortletContextAware { - - private PortletContext portletContext; - - @Override - public void setPortletContext(PortletContext portletContext) { - this.portletContext = portletContext; - } - - public PortletContext getPortletContext() { - return portletContext; - } -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java deleted file mode 100644 index 0b371b306f..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletContextAwareProcessorTests.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2002-2015 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.context; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class PortletContextAwareProcessorTests { - - private final PortletContext portletContext = new MockPortletContext(); - - private final PortletConfig portletConfig = new MockPortletConfig(portletContext); - - private final PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext); - - private final PortletContextAwareBean bean = new PortletContextAwareBean(); - - - @Test - public void portletContextAwareWithPortletContext() { - assertNull(bean.getPortletContext()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletContext should have been set", bean.getPortletContext()); - assertEquals(portletContext, bean.getPortletContext()); - } - - @Test - public void portletContextAwareWithPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig); - assertNull(bean.getPortletContext()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletContext should have been set", bean.getPortletContext()); - assertEquals(portletContext, bean.getPortletContext()); - } - - @Test - public void portletContextAwareWithPortletContextAndPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig); - assertNull(bean.getPortletContext()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletContext should have been set", bean.getPortletContext()); - assertEquals(portletContext, bean.getPortletContext()); - } - - @Test - public void portletContextAwareWithNullPortletContextAndNonNullPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig); - assertNull(bean.getPortletContext()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletContext should have been set", bean.getPortletContext()); - assertEquals(portletContext, bean.getPortletContext()); - } - - @Test - public void portletContextAwareWithNonNullPortletContextAndNullPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null); - assertNull(bean.getPortletContext()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletContext should have been set", bean.getPortletContext()); - assertEquals(portletContext, bean.getPortletContext()); - } - - @Test - public void portletContextAwareWithNullPortletContext() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor((PortletContext) null); - assertNull(bean.getPortletContext()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getPortletContext()); - } - - @Test - public void portletConfigAwareWithPortletContextOnly() { - PortletConfigAwareBean bean = new PortletConfigAwareBean(); - assertNull(bean.getPortletConfig()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getPortletConfig()); - } - - @Test - public void portletConfigAwareWithPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig); - PortletConfigAwareBean bean = new PortletConfigAwareBean(); - assertNull(bean.getPortletConfig()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletConfig should have been set", bean.getPortletConfig()); - assertEquals(portletConfig, bean.getPortletConfig()); - } - - @Test - public void portletConfigAwareWithPortletContextAndPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig); - PortletConfigAwareBean bean = new PortletConfigAwareBean(); - assertNull(bean.getPortletConfig()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletConfig should have been set", bean.getPortletConfig()); - assertEquals(portletConfig, bean.getPortletConfig()); - } - - @Test - public void portletConfigAwareWithNullPortletContextAndNonNullPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig); - PortletConfigAwareBean bean = new PortletConfigAwareBean(); - assertNull(bean.getPortletConfig()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNotNull("PortletConfig should have been set", bean.getPortletConfig()); - assertEquals(portletConfig, bean.getPortletConfig()); - } - - @Test - public void portletConfigAwareWithNonNullPortletContextAndNullPortletConfig() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null); - PortletConfigAwareBean bean = new PortletConfigAwareBean(); - assertNull(bean.getPortletConfig()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getPortletConfig()); - } - - @Test - public void portletConfigAwareWithNullPortletContext() { - PortletContextAwareProcessor processor = new PortletContextAwareProcessor((PortletContext) null); - PortletConfigAwareBean bean = new PortletConfigAwareBean(); - assertNull(bean.getPortletConfig()); - processor.postProcessBeforeInitialization(bean, "testBean"); - assertNull(bean.getPortletConfig()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java deleted file mode 100644 index 40237e8182..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletRequestAttributesTests.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2002-2016 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.context; - -import java.io.Serializable; -import javax.portlet.PortletRequest; -import javax.portlet.PortletSession; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.mock.web.portlet.MockPortletSession; -import org.springframework.web.context.request.RequestAttributes; - -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.*; - -/** - * @author Rick Evans - * @author Juergen Hoeller - * @author Chris Beams - */ -public class PortletRequestAttributesTests { - - private static final String KEY = "ThatThingThatThing"; - - @SuppressWarnings("serial") - private static final Serializable VALUE = new Serializable() { - }; - - - @Test(expected = IllegalArgumentException.class) - public void testCtorRejectsNullArg() throws Exception { - new PortletRequestAttributes(null); - } - - @Test - public void testUpdateAccessedAttributes() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute(KEY, VALUE); - MockPortletRequest request = new MockPortletRequest(); - request.setSession(session); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION); - assertSame(VALUE, value); - attrs.requestCompleted(); - } - - @Test - public void testSetRequestScopedAttribute() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST); - Object value = request.getAttribute(KEY); - assertSame(VALUE, value); - } - - @Test - public void testSetRequestScopedAttributeAfterCompletion() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - request.close(); - try { - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST); - fail("Should have thrown IllegalStateException"); - } - catch (IllegalStateException ex) { - // expected - } - } - - @Test - public void testSetSessionScopedAttribute() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute(KEY, VALUE, PortletSession.PORTLET_SCOPE); - MockPortletRequest request = new MockPortletRequest(); - request.setSession(session); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION); - assertSame(VALUE, session.getAttribute(KEY, PortletSession.PORTLET_SCOPE)); - } - - @Test - public void testSetSessionScopedAttributeAfterCompletion() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute(KEY, VALUE, PortletSession.PORTLET_SCOPE); - MockPortletRequest request = new MockPortletRequest(); - request.setSession(session); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION)); - attrs.requestCompleted(); - request.close(); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION); - assertSame(VALUE, session.getAttribute(KEY, PortletSession.PORTLET_SCOPE)); - } - - @Test - public void testSetGlobalSessionScopedAttribute() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute(KEY, VALUE, PortletSession.APPLICATION_SCOPE); - MockPortletRequest request = new MockPortletRequest(); - request.setSession(session); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION); - assertSame(VALUE, session.getAttribute(KEY, PortletSession.APPLICATION_SCOPE)); - } - - @Test - public void testSetGlobalSessionScopedAttributeAfterCompletion() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute(KEY, VALUE, PortletSession.APPLICATION_SCOPE); - MockPortletRequest request = new MockPortletRequest(); - request.setSession(session); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - assertSame(VALUE, attrs.getAttribute(KEY, RequestAttributes.SCOPE_GLOBAL_SESSION)); - attrs.requestCompleted(); - request.close(); - attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION); - assertSame(VALUE, session.getAttribute(KEY, PortletSession.APPLICATION_SCOPE)); - } - - @Test - public void testGetSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { - PortletRequest request = mock(PortletRequest.class); - - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION); - assertNull(value); - - verify(request).getPortletSession(false); - } - - @Test - public void testRemoveSessionScopedAttribute() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute(KEY, VALUE); - MockPortletRequest request = new MockPortletRequest(); - request.setSession(session); - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION); - Object value = session.getAttribute(KEY); - assertNull(value); - } - - @Test - public void testRemoveSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception { - PortletRequest request = mock(PortletRequest.class); - - PortletRequestAttributes attrs = new PortletRequestAttributes(request); - attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION); - - verify(request).getPortletSession(false); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java deleted file mode 100644 index a0cb9280b2..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletWebRequestTests.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2002-2014 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.context; - -import java.util.Locale; -import java.util.Map; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.filter.PortletRequestWrapper; -import javax.portlet.filter.PortletResponseWrapper; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.web.multipart.MultipartRequest; - -import static org.junit.Assert.*; - -/** - * @author Juergen Hoeller - * @since 26.07.2006 - */ -public class PortletWebRequestTests { - - @Test - public void testParameters() { - MockPortletRequest portletRequest = new MockPortletRequest(); - portletRequest.addParameter("param1", "value1"); - portletRequest.addParameter("param2", "value2"); - portletRequest.addParameter("param2", "value2a"); - - PortletWebRequest request = new PortletWebRequest(portletRequest); - assertEquals("value1", request.getParameter("param1")); - assertEquals(1, request.getParameterValues("param1").length); - assertEquals("value1", request.getParameterValues("param1")[0]); - assertEquals("value2", request.getParameter("param2")); - assertEquals(2, request.getParameterValues("param2").length); - assertEquals("value2", request.getParameterValues("param2")[0]); - assertEquals("value2a", request.getParameterValues("param2")[1]); - - Map paramMap = request.getParameterMap(); - assertEquals(2, paramMap.size()); - assertEquals(1, paramMap.get("param1").length); - assertEquals("value1", paramMap.get("param1")[0]); - assertEquals(2, paramMap.get("param2").length); - assertEquals("value2", paramMap.get("param2")[0]); - assertEquals("value2a", paramMap.get("param2")[1]); - } - - @Test - public void testLocale() { - MockPortletRequest portletRequest = new MockPortletRequest(); - portletRequest.addPreferredLocale(Locale.UK); - - PortletWebRequest request = new PortletWebRequest(portletRequest); - assertEquals(Locale.UK, request.getLocale()); - } - - @Test - public void testNativeRequest() { - MockRenderRequest portletRequest = new MockRenderRequest(); - MockRenderResponse portletResponse = new MockRenderResponse(); - PortletWebRequest request = new PortletWebRequest(portletRequest, portletResponse); - assertSame(portletRequest, request.getNativeRequest()); - assertSame(portletRequest, request.getNativeRequest(PortletRequest.class)); - assertSame(portletRequest, request.getNativeRequest(RenderRequest.class)); - assertSame(portletRequest, request.getNativeRequest(MockRenderRequest.class)); - assertNull(request.getNativeRequest(MultipartRequest.class)); - assertSame(portletResponse, request.getNativeResponse()); - assertSame(portletResponse, request.getNativeResponse(PortletResponse.class)); - assertSame(portletResponse, request.getNativeResponse(RenderResponse.class)); - assertSame(portletResponse, request.getNativeResponse(MockRenderResponse.class)); - assertNull(request.getNativeResponse(MultipartRequest.class)); - } - - @Test - public void testDecoratedNativeRequest() { - MockRenderRequest portletRequest = new MockRenderRequest(); - MockRenderResponse portletResponse = new MockRenderResponse(); - PortletRequest decoratedRequest = new PortletRequestWrapper(portletRequest); - PortletResponse decoratedResponse = new PortletResponseWrapper(portletResponse); - PortletWebRequest request = new PortletWebRequest(decoratedRequest, decoratedResponse); - assertSame(decoratedRequest, request.getNativeRequest()); - assertSame(decoratedRequest, request.getNativeRequest(PortletRequest.class)); - assertSame(portletRequest, request.getNativeRequest(RenderRequest.class)); - assertSame(portletRequest, request.getNativeRequest(MockRenderRequest.class)); - assertNull(request.getNativeRequest(MultipartRequest.class)); - assertSame(decoratedResponse, request.getNativeResponse()); - assertSame(decoratedResponse, request.getNativeResponse(PortletResponse.class)); - assertSame(portletResponse, request.getNativeResponse(RenderResponse.class)); - assertSame(portletResponse, request.getNativeResponse(MockRenderResponse.class)); - assertNull(request.getNativeResponse(MultipartRequest.class)); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java deleted file mode 100644 index b4f3e8e93b..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright 2002-2015 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.context; - -import java.util.Locale; - -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; - -import org.junit.Test; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.NoSuchMessageException; -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.tests.sample.beans.TestBean; - -import static org.junit.Assert.*; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - * @author Mark Fisher - * @author Chris Beams - */ -public class XmlPortletApplicationContextTests extends AbstractXmlWebApplicationContextTests { - - private ConfigurablePortletApplicationContext root; - - @Override - protected ConfigurableApplicationContext createContext() throws Exception { - root = new XmlPortletApplicationContext(); - PortletContext portletContext = new MockPortletContext(); - PortletConfig portletConfig = new MockPortletConfig(portletContext); - root.setPortletConfig(portletConfig); - root.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml"}); - root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() { - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - beanFactory.addBeanPostProcessor(new BeanPostProcessor() { - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { - if (bean instanceof TestBean) { - ((TestBean) bean).getFriends().add("myFriend"); - } - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - return bean; - } - }); - } - }); - root.refresh(); - XmlPortletApplicationContext pac = new XmlPortletApplicationContext(); - pac.setParent(root); - pac.setPortletConfig(portletConfig); - pac.setNamespace("test-portlet"); - pac.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml"}); - pac.refresh(); - return pac; - } - - /** - * Overridden in order to use MockPortletConfig - * @see org.springframework.web.context.XmlWebApplicationContextTests#testWithoutMessageSource() - */ - @Test - @SuppressWarnings("resource") - public void withoutMessageSource() throws Exception { - MockPortletContext portletContext = new MockPortletContext(""); - MockPortletConfig portletConfig = new MockPortletConfig(portletContext); - XmlPortletApplicationContext pac = new XmlPortletApplicationContext(); - pac.setParent(root); - pac.setPortletConfig(portletConfig); - pac.setNamespace("testNamespace"); - pac.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml"}); - pac.refresh(); - try { - pac.getMessage("someMessage", null, Locale.getDefault()); - fail("Should have thrown NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // expected; - } - String msg = pac.getMessage("someMessage", null, "default", Locale.getDefault()); - assertEquals("Default message returned", "default", msg); - } - - /** - * Overridden in order to access the root ApplicationContext. - * - * @see org.springframework.web.context.XmlWebApplicationContextTests#contextNesting() - */ - @Test - @Override - public void contextNesting() { - TestBean father = (TestBean) this.applicationContext.getBean("father"); - assertTrue("Bean from root context", father != null); - assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend")); - - TestBean rod = (TestBean) this.applicationContext.getBean("rod"); - assertTrue("Bean from child context", "Rod".equals(rod.getName())); - assertTrue("Bean has external reference", rod.getSpouse() == father); - assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend")); - - rod = (TestBean) this.root.getBean("rod"); - assertTrue("Bean from root context", "Roderick".equals(rod.getName())); - assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend")); - } - - @Test - @Override - public void count() { - assertTrue("should have 16 beans, not "+ this.applicationContext.getBeanDefinitionCount(), - this.applicationContext.getBeanDefinitionCount() == 16); - } - - @Test - public void portletContextAwareBean() { - PortletContextAwareBean bean = (PortletContextAwareBean)this.applicationContext.getBean("portletContextAwareBean"); - assertNotNull(bean.getPortletContext()); - } - - @Test - public void portletConfigAwareBean() { - PortletConfigAwareBean bean = (PortletConfigAwareBean)this.applicationContext.getBean("portletConfigAwareBean"); - assertNotNull(bean.getPortletConfig()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java deleted file mode 100644 index 061fc9b698..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterHandlerMappingTests.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2002-2015 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 org.junit.Before; -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; -import org.springframework.web.portlet.context.XmlPortletApplicationContext; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class ParameterHandlerMappingTests { - - public static final String CONF = "/org/springframework/web/portlet/handler/parameterMapping.xml"; - - private final ConfigurablePortletApplicationContext pac = new XmlPortletApplicationContext(); - - private final MockPortletContext portletContext = new MockPortletContext(); - - private final MockPortletRequest request = new MockPortletRequest(); - - private ParameterHandlerMapping hm; - - @Before - public void setUp() throws Exception { - pac.setPortletContext(portletContext); - pac.setConfigLocations(new String[] {CONF}); - pac.refresh(); - - hm = pac.getBean(ParameterHandlerMapping.class); - } - - @Test - public void parameterMapping() throws Exception { - MockPortletRequest addRequest = request; - addRequest.addParameter("action", "add"); - Object addHandler = hm.getHandler(addRequest).getHandler(); - assertEquals(pac.getBean("addItemHandler"), addHandler); - - MockPortletRequest removeRequest = new MockPortletRequest(); - removeRequest.addParameter("action", "remove"); - Object removeHandler = hm.getHandler(removeRequest).getHandler(); - assertEquals(pac.getBean("removeItemHandler"), removeHandler); - } - - @Test - public void unregisteredHandlerWithNoDefault() throws Exception { - request.addParameter("action", "modify"); - - assertNull(hm.getHandler(request)); - } - - @Test - public void unregisteredHandlerWithDefault() throws Exception { - Object defaultHandler = new Object(); - hm.setDefaultHandler(defaultHandler); - request.addParameter("action", "modify"); - - assertNotNull(hm.getHandler(request)); - assertEquals(defaultHandler, hm.getHandler(request).getHandler()); - } - - @Test - public void configuredParameterName() throws Exception { - hm.setParameterName("someParam"); - request.addParameter("someParam", "add"); - - Object handler = hm.getHandler(request).getHandler(); - assertEquals(pac.getBean("addItemHandler"), handler); - } - - @Test(expected = IllegalStateException.class) - public void duplicateMappingAttempt() { - hm.registerHandler("add", new Object()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java deleted file mode 100644 index 60bff0cfc6..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/ParameterMappingInterceptorTests.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2002-2015 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 org.junit.Test; - -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class ParameterMappingInterceptorTests { - - private final ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor(); - - private final Object handler = new Object(); - - private final MockActionRequest request = new MockActionRequest(); - - private final MockActionResponse response = new MockActionResponse(); - - - @Test - public void defaultParameterMapped() throws Exception { - String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME; - String value = "someValue"; - request.setParameter(param, value); - assertNull(response.getRenderParameter(param)); - boolean shouldProceed = interceptor.preHandleAction(request, response, handler); - assertTrue(shouldProceed); - assertNotNull(response.getRenderParameter(param)); - assertEquals(value, response.getRenderParameter(param)); - } - - @Test - public void nonDefaultParameterNotMapped() throws Exception { - String param = "myParam"; - String value = "someValue"; - request.setParameter(param, value); - assertNull(response.getRenderParameter(param)); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - assertNull(response.getRenderParameter(param)); - assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME)); - } - - @Test - public void nonDefaultParameterMappedWhenHandlerMappingProvided() throws Exception { - String param = "myParam"; - String value = "someValue"; - ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping(); - handlerMapping.setParameterName(param); - interceptor.setParameterName(param); - request.setParameter(param, value); - assertNull(response.getRenderParameter(param)); - boolean shouldProceed = interceptor.preHandleAction(request, response, handler); - assertTrue(shouldProceed); - assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME)); - assertNotNull(response.getRenderParameter(param)); - assertEquals(value, response.getRenderParameter(param)); - } - - @Test - public void noEffectForRenderRequest() throws Exception { - String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME; - String value = "someValue"; - request.setParameter(param, value); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - } - - @Test - public void noParameterValueSetWithDefaultParameterName() throws Exception { - String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME; - assertNull(response.getRenderParameter(param)); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - assertNull(response.getRenderParameter(param)); - } - - @Test - public void noParameterValueSetWithNonDefaultParameterName() throws Exception { - String param = "myParam"; - assertNull(response.getRenderParameter(param)); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - assertNull(response.getRenderParameter(param)); - } - - @Test - public void noParameterValueSetWithNonDefaultParameterNameWhenHandlerMappingProvided() throws Exception { - String param = "myParam"; - ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping(); - handlerMapping.setParameterName(param); - interceptor.setParameterName(param); - assertNull(response.getRenderParameter(param)); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - assertNull(response.getRenderParameter(param)); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java deleted file mode 100644 index 2acd2ed686..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeHandlerMappingTests.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2002-2015 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.PortletMode; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; -import org.springframework.web.portlet.context.XmlPortletApplicationContext; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class PortletModeHandlerMappingTests { - - public static final String CONF = "/org/springframework/web/portlet/handler/portletModeMapping.xml"; - - private final ConfigurablePortletApplicationContext pac = new XmlPortletApplicationContext(); - - private final MockPortletContext portletContext = new MockPortletContext(); - - private final MockPortletRequest request = new MockPortletRequest(); - - private PortletModeHandlerMapping hm; - - - @Before - public void setUp() throws Exception { - pac.setPortletContext(portletContext); - pac.setConfigLocations(new String[] {CONF}); - pac.refresh(); - - hm = pac.getBean(PortletModeHandlerMapping.class); - } - - @Test - public void portletModeView() throws Exception { - request.setPortletMode(PortletMode.VIEW); - - Object handler = hm.getHandler(request).getHandler(); - assertEquals(pac.getBean("viewHandler"), handler); - } - - @Test - public void portletModeEdit() throws Exception { - request.setPortletMode(PortletMode.EDIT); - - Object handler = hm.getHandler(request).getHandler(); - assertEquals(pac.getBean("editHandler"), handler); - } - - @Test - public void portletModeHelp() throws Exception { - request.setPortletMode(PortletMode.HELP); - - Object handler = hm.getHandler(request).getHandler(); - assertEquals(pac.getBean("helpHandler"), handler); - } - - @Test(expected = IllegalStateException.class) - public void duplicateMappingAttempt() { - hm.registerHandler(PortletMode.VIEW, new Object()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java deleted file mode 100644 index f634e51255..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/PortletModeParameterHandlerMappingTests.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2002-2015 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.PortletMode; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; -import org.springframework.web.portlet.context.XmlPortletApplicationContext; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class PortletModeParameterHandlerMappingTests { - - public static final String CONF = "/org/springframework/web/portlet/handler/portletModeParameterMapping.xml"; - - private final ConfigurablePortletApplicationContext pac = new XmlPortletApplicationContext(); - - private final MockPortletContext portletContext = new MockPortletContext(); - - private final MockPortletRequest request = new MockPortletRequest(); - - private PortletModeParameterHandlerMapping hm; - - - @Before - public void setUp() throws Exception { - pac.setPortletContext(portletContext); - pac.setConfigLocations(new String[] {CONF}); - pac.refresh(); - - hm = pac.getBean(PortletModeParameterHandlerMapping.class); - } - - @Test - public void portletModeViewWithParameter() throws Exception { - MockPortletRequest addRequest = request; - addRequest.setPortletMode(PortletMode.VIEW); - addRequest.setParameter("action", "add"); - Object addHandler = hm.getHandler(addRequest).getHandler(); - assertEquals(pac.getBean("addItemHandler"), addHandler); - - MockPortletRequest removeRequest = new MockPortletRequest(); - removeRequest.setPortletMode(PortletMode.VIEW); - removeRequest.setParameter("action", "remove"); - Object removeHandler = hm.getHandler(removeRequest).getHandler(); - assertEquals(pac.getBean("removeItemHandler"), removeHandler); - } - - @Test - public void portletModeEditWithParameter() throws Exception { - request.setPortletMode(PortletMode.EDIT); - request.setParameter("action", "prefs"); - - Object handler = hm.getHandler(request).getHandler(); - assertEquals(pac.getBean("preferencesHandler"), handler); - } - - @Test(expected = IllegalStateException.class) - public void duplicateMappingInSamePortletMode() { - hm.registerHandler(PortletMode.VIEW, "remove", new Object()); - } - - @Test(expected = IllegalStateException.class) - public void duplicateMappingInDifferentPortletMode() { - hm.registerHandler(PortletMode.EDIT, "remove", new Object()); - } - - @Test - public void allowDuplicateMappingInDifferentPortletMode() throws Exception { - hm.setAllowDuplicateParameters(true); - - Object editRemoveHandler = new Object(); - hm.registerHandler(PortletMode.EDIT, "remove", editRemoveHandler); - - request.setPortletMode(PortletMode.EDIT); - request.setParameter("action", "remove"); - - Object handler = hm.getHandler(request).getHandler(); - assertEquals(editRemoveHandler, handler); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java deleted file mode 100644 index fed02db643..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/SimpleMappingExceptionResolverTests.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright 2002-2015 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 java.util.Collections; -import java.util.Properties; -import javax.portlet.WindowState; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.web.portlet.ModelAndView; - -import static org.junit.Assert.*; - -/** - * @author Seth Ladd - * @author Mark Fisher - * @author Juergen Hoeller - * @author Sam Brannen - */ -public class SimpleMappingExceptionResolverTests { - - private static final String DEFAULT_VIEW = "default-view"; - - private final SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver(); - - private final MockRenderRequest request = new MockRenderRequest(); - - private final MockRenderResponse response = new MockRenderResponse(); - - private final Object handler1 = new String(); - - private final Object handler2 = new Object(); - - private final Exception genericException = new Exception(); - - - @Test - public void setOrder() { - exceptionResolver.setOrder(2); - assertEquals(2, exceptionResolver.getOrder()); - } - - @Test - public void defaultErrorView() { - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(DEFAULT_VIEW, mav.getViewName()); - assertEquals(genericException, mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); - } - - @Test - public void defaultErrorViewDifferentHandler() { - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull("Handler not mapped - ModelAndView should be null", mav); - } - - @Test - public void defaultErrorViewDifferentHandlerClass() { - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - exceptionResolver.setMappedHandlerClasses(new Class[] {String.class}); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull("Handler not mapped - ModelAndView should be null", mav); - } - - @Test - public void nullDefaultErrorView() { - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertNull("No default error view set - ModelAndView should be null", mav); - } - - @Test - public void nullExceptionAttribute() { - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - exceptionResolver.setExceptionAttribute(null); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(DEFAULT_VIEW, mav.getViewName()); - assertNull(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE)); - } - - @Test - public void nullExceptionMappings() { - exceptionResolver.setExceptionMappings(null); - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals(DEFAULT_VIEW, mav.getViewName()); - } - - @Test - public void defaultNoRenderWhenMinimized() { - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - request.setWindowState(WindowState.MINIMIZED); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertNull("Should not render when WindowState is MINIMIZED", mav); - } - - @Test - public void doRenderWhenMinimized() { - exceptionResolver.setDefaultErrorView(DEFAULT_VIEW); - exceptionResolver.setRenderWhenMinimized(true); - request.setWindowState(WindowState.MINIMIZED); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertNotNull("ModelAndView should not be null", mav); - assertEquals(DEFAULT_VIEW, mav.getViewName()); - } - - @Test - public void simpleExceptionMapping() { - Properties props = new Properties(); - props.setProperty("Exception", "error"); - exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION"); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); - } - - @Test - public void exactExceptionMappingWithHandlerSpecified() { - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); - } - - @Test - public void exactExceptionMappingWithHandlerClassSpecified() { - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - exceptionResolver.setMappedHandlerClasses(new Class[] {String.class}); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); - } - - @Test - public void exactExceptionMappingWithHandlerInterfaceSpecified() { - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - exceptionResolver.setMappedHandlerClasses(new Class[] {Comparable.class}); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); - } - - @Test - public void simpleExceptionMappingWithHandlerSpecifiedButWrongHandler() { - Properties props = new Properties(); - props.setProperty("Exception", "error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull("Handler not mapped - ModelAndView should be null", mav); - } - - @Test - public void simpleExceptionMappingWithHandlerSpecifiedButWrongHandlerClass() { - Properties props = new Properties(); - props.setProperty("Exception", "error"); - exceptionResolver.setMappedHandlerClasses(new Class[] {String.class}); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException); - assertNull("Handler not mapped - ModelAndView should be null", mav); - } - - @Test - public void missingExceptionInMapping() { - Properties props = new Properties(); - props.setProperty("SomeFooThrowable", "error"); - exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION"); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertNull("Exception not mapped - ModelAndView should be null", mav); - } - - @Test - public void twoMappings() { - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - props.setProperty("AnotherException", "another-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); - } - - @Test - public void twoMappingsOneShortOneLong() { - Properties props = new Properties(); - props.setProperty("Exception", "error"); - props.setProperty("AnotherException", "another-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException); - assertEquals("error", mav.getViewName()); - } - - @Test - public void twoMappingsOneShortOneLongThrowOddException() { - Exception oddException = new SomeOddException(); - Properties props = new Properties(); - props.setProperty("Exception", "error"); - props.setProperty("SomeOddException", "another-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("another-error", mav.getViewName()); - } - - @Test - public void twoMappingsThrowOddExceptionUseLongExceptionMapping() { - Exception oddException = new SomeOddException(); - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - props.setProperty("SomeOddException", "another-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("another-error", mav.getViewName()); - } - - @Test - public void threeMappings() { - Exception oddException = new AnotherOddException(); - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - props.setProperty("SomeOddException", "another-error"); - props.setProperty("AnotherOddException", "another-some-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("another-some-error", mav.getViewName()); - } - - @Test - public void exceptionWithSubstringMatchingParent() { - Exception oddException = new SomeOddExceptionChild(); - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - props.setProperty("SomeOddException", "parent-error"); - props.setProperty("SomeOddExceptionChild", "child-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("child-error", mav.getViewName()); - } - - @Test - public void mostSpecificExceptionInHierarchyWins() { - Exception oddException = new NoSubstringMatchesThisException(); - Properties props = new Properties(); - props.setProperty("java.lang.Exception", "error"); - props.setProperty("SomeOddException", "parent-error"); - exceptionResolver.setMappedHandlers(Collections.singleton(handler1)); - exceptionResolver.setExceptionMappings(props); - ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException); - assertEquals("parent-error", mav.getViewName()); - } - - - @SuppressWarnings("serial") - private static class SomeOddException extends Exception { - - } - - - @SuppressWarnings("serial") - private static class SomeOddExceptionChild extends SomeOddException { - - } - - - @SuppressWarnings("serial") - private static class NoSubstringMatchesThisException extends SomeOddException { - - } - - - @SuppressWarnings("serial") - private static class AnotherOddException extends Exception { - - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java deleted file mode 100644 index 777b8c3f82..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/handler/UserRoleAuthorizationInterceptorTests.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2002-2015 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.PortletSecurityException; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class UserRoleAuthorizationInterceptorTests { - - private final UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor(); - - private final MockRenderRequest request = new MockRenderRequest(); - - private final MockRenderResponse response = new MockRenderResponse(); - - - @Test - public void authorizedUser() throws Exception { - String validRole = "allowed"; - interceptor.setAuthorizedRoles(new String[] {validRole}); - Object handler = new Object(); - request.addUserRole(validRole); - assertTrue(request.isUserInRole(validRole)); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - } - - @Test - public void authorizedUserWithMultipleRoles() throws Exception { - String validRole1 = "allowed1"; - String validRole2 = "allowed2"; - interceptor.setAuthorizedRoles(new String[] {validRole1, validRole2}); - Object handler = new Object(); - request.addUserRole(validRole2); - request.addUserRole("someOtherRole"); - assertFalse(request.isUserInRole(validRole1)); - assertTrue(request.isUserInRole(validRole2)); - boolean shouldProceed = interceptor.preHandle(request, response, handler); - assertTrue(shouldProceed); - } - - @Test(expected = PortletSecurityException.class) - public void unauthorizedUser() throws Exception { - String validRole = "allowed"; - interceptor.setAuthorizedRoles(new String[] {validRole}); - request.addUserRole("someOtherRole"); - assertFalse(request.isUserInRole(validRole)); - - interceptor.preHandle(request, response, new Object()); - } - - @Test(expected = PortletSecurityException.class) - public void requestWithNoUserRoles() throws Exception { - String validRole = "allowed"; - interceptor.setAuthorizedRoles(new String[] {validRole}); - assertFalse(request.isUserInRole(validRole)); - - interceptor.preHandle(request, response, new Object()); - } - - @Test(expected = PortletSecurityException.class) - public void interceptorWithNoAuthorizedRoles() throws Exception { - request.addUserRole("someRole"); - interceptor.preHandle(request, response, new Object()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java deleted file mode 100644 index 4caaa7f6a3..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/ParameterizableViewControllerTests.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2002-2015 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.PortletException; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.context.StaticPortletApplicationContext; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class ParameterizableViewControllerTests { - - private final ParameterizableViewController controller = new ParameterizableViewController(); - - private final RenderRequest request = new MockRenderRequest(); - - private final RenderResponse response = new MockRenderResponse(); - - - @Test - public void renderRequestWithViewNameSet() throws Exception { - String viewName = "testView"; - controller.setViewName(viewName); - ModelAndView mav = controller.handleRenderRequest(request, response); - assertEquals(viewName, mav.getViewName()); - } - - @Test(expected = IllegalArgumentException.class) - public void initApplicationContextWithNoViewNameSet() throws Exception { - controller.setApplicationContext(new StaticPortletApplicationContext()); - } - - @Test(expected = PortletException.class) - public void actionRequestNotHandled() throws Exception { - controller.handleActionRequest(new MockActionRequest(), new MockActionResponse()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java deleted file mode 100644 index ceee4ff5a0..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletModeNameViewControllerTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2015 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.PortletException; -import javax.portlet.PortletMode; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.web.portlet.ModelAndView; - -import static org.junit.Assert.*; - -/** - * @author Mark Fisher - * @author Sam Brannen - */ -public class PortletModeNameViewControllerTests { - - private final PortletModeNameViewController controller = new PortletModeNameViewController(); - - private final MockRenderRequest request = new MockRenderRequest(); - - private final MockRenderResponse response = new MockRenderResponse(); - - - @Test - public void editPortletMode() throws Exception { - request.setPortletMode(PortletMode.EDIT); - ModelAndView mav = controller.handleRenderRequest(request, response); - assertEquals("edit", mav.getViewName()); - } - - @Test - public void helpPortletMode() throws Exception { - request.setPortletMode(PortletMode.HELP); - ModelAndView mav = controller.handleRenderRequest(request, response); - assertEquals("help", mav.getViewName()); - } - - @Test - public void viewPortletMode() throws Exception { - request.setPortletMode(PortletMode.VIEW); - ModelAndView mav = controller.handleRenderRequest(request, response); - assertEquals("view", mav.getViewName()); - } - - @Test(expected = PortletException.class) - public void actionRequest() throws Exception { - controller.handleActionRequest(new MockActionRequest(), new MockActionResponse()); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java deleted file mode 100644 index 62532a769a..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/PortletWrappingControllerTests.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 2002-2015 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 java.io.IOException; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.Portlet; -import javax.portlet.PortletConfig; -import javax.portlet.PortletException; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.beans.BeansException; -import org.springframework.beans.MutablePropertyValues; -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext; -import org.springframework.web.portlet.context.StaticPortletApplicationContext; - -import static org.junit.Assert.*; - -/** - * Unit tests for the {@link PortletWrappingController} class. - * - * @author Mark Fisher - * @author Rick Evans - * @author Chris Beams - * @author Sam Brannen - */ -public final class PortletWrappingControllerTests { - - private static final String RESULT_RENDER_PARAMETER_NAME = "result"; - private static final String PORTLET_WRAPPING_CONTROLLER_BEAN_NAME = "controller"; - private static final String RENDERED_RESPONSE_CONTENT = "myPortlet-view"; - private static final String PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME = "portletName"; - - private PortletWrappingController controller; - - - @Before - @SuppressWarnings("resource") - public void setUp() { - ConfigurablePortletApplicationContext applicationContext = new MyApplicationContext(); - MockPortletConfig config = new MockPortletConfig(new MockPortletContext(), "wrappedPortlet"); - applicationContext.setPortletConfig(config); - applicationContext.refresh(); - controller = (PortletWrappingController) applicationContext.getBean(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME); - } - - - @Test - public void actionRequest() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setParameter("test", "test"); - - controller.handleActionRequest(request, response); - assertEquals("myPortlet-action", response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME)); - } - - @Test - public void renderRequest() throws Exception { - MockRenderResponse response = new MockRenderResponse(); - - controller.handleRenderRequest(new MockRenderRequest(), response); - assertEquals(RENDERED_RESPONSE_CONTENT, response.getContentAsString()); - } - - @Test(expected = IllegalArgumentException.class) - public void actionRequestWithNoParameters() throws Exception { - controller.handleActionRequest(new MockActionRequest(), new MockActionResponse()); - } - - @Test(expected = IllegalArgumentException.class) - public void rejectsPortletClassThatDoesNotImplementPortletInterface() throws Exception { - PortletWrappingController controller = new PortletWrappingController(); - controller.setPortletClass(String.class); - - controller.afterPropertiesSet(); - } - - @Test(expected = IllegalArgumentException.class) - public void rejectsIfPortletClassIsNotSupplied() throws Exception { - PortletWrappingController controller = new PortletWrappingController(); - controller.setPortletClass(null); - - controller.afterPropertiesSet(); - } - - @Test(expected = IllegalStateException.class) - public void destroyingTheControllerPropagatesDestroyToWrappedPortlet() throws Exception { - final PortletWrappingController controller = new PortletWrappingController(); - controller.setPortletClass(MyPortlet.class); - controller.afterPropertiesSet(); - - // test for destroy() call being propagated via exception being thrown - controller.destroy(); - } - - @Test - public void portletName() throws Exception { - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "test"); - controller.handleActionRequest(request, response); - assertEquals("wrappedPortlet", response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME)); - } - - @Test - public void delegationToMockPortletConfigIfSoConfigured() throws Exception { - final String BEAN_NAME = "Sixpence None The Richer"; - - MockActionRequest request = new MockActionRequest(); - MockActionResponse response = new MockActionResponse(); - - PortletWrappingController controller = new PortletWrappingController(); - controller.setPortletClass(MyPortlet.class); - controller.setUseSharedPortletConfig(false); - controller.setBeanName(BEAN_NAME); - controller.afterPropertiesSet(); - - request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "true"); - controller.handleActionRequest(request, response); - - assertEquals(BEAN_NAME, response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME)); - } - - - public static final class MyPortlet implements Portlet { - - private PortletConfig portletConfig; - - - @Override - public void init(PortletConfig portletConfig) { - this.portletConfig = portletConfig; - } - - @Override - public void processAction(ActionRequest request, ActionResponse response) throws PortletException { - if (request.getParameter("test") != null) { - response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, "myPortlet-action"); - } - else if (request.getParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME) != null) { - response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, getPortletConfig().getPortletName()); - } - else { - throw new IllegalArgumentException("no request parameters"); - } - } - - @Override - public void render(RenderRequest request, RenderResponse response) throws IOException { - response.getWriter().write(RENDERED_RESPONSE_CONTENT); - } - - public PortletConfig getPortletConfig() { - return this.portletConfig; - } - - @Override - public void destroy() { - throw new IllegalStateException("Being destroyed..."); - } - - } - - private static final class MyApplicationContext extends StaticPortletApplicationContext { - - @Override - public void refresh() throws BeansException { - MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.add("portletClass", MyPortlet.class); - registerSingleton(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME, PortletWrappingController.class, pvs); - super.refresh(); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java deleted file mode 100644 index 92f2d47036..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2002-2010 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.annotation; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.BindException; -import java.net.SocketException; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.stereotype.Controller; -import org.springframework.util.ClassUtils; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.portlet.ModelAndView; - -import static org.junit.Assert.*; - -/** - * @author Arjen Poutsma - * @author Juergen Hoeller - */ -public class AnnotationMethodHandlerExceptionResolverTests { - - private AnnotationMethodHandlerExceptionResolver exceptionResolver; - - private MockRenderRequest request; - - private MockRenderResponse response; - - - @Before - public void setUp() { - exceptionResolver = new AnnotationMethodHandlerExceptionResolver(); - request = new MockRenderRequest(); - response = new MockRenderResponse(); - } - - @Test - public void simpleWithIOException() { - IOException ex = new IOException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "X:IOException", mav.getViewName()); - } - - @Test - public void simpleWithSocketException() { - SocketException ex = new SocketException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "Y:SocketException", mav.getViewName()); - } - - @Test - public void simpleWithFileNotFoundException() { - FileNotFoundException ex = new FileNotFoundException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "X:FileNotFoundException", mav.getViewName()); - } - - @Test - public void simpleWithBindException() { - BindException ex = new BindException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "Y:BindException", mav.getViewName()); - } - - @Test - public void inherited() { - IOException ex = new IOException(); - InheritedController controller = new InheritedController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "GenericError", mav.getViewName()); - } - - @Test(expected = IllegalStateException.class) - public void ambiguous() { - IllegalArgumentException ex = new IllegalArgumentException(); - AmbiguousController controller = new AmbiguousController(); - exceptionResolver.resolveException(request, response, controller, ex); - } - - // SPR-9209 - - @Test - public void cachingSideEffect() { - IllegalArgumentException ex = new IllegalArgumentException(); - SimpleController controller = new SimpleController(); - - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - - mav = exceptionResolver.resolveException(request, response, controller, new NullPointerException()); - assertNull(mav); - } - - - @Controller - private static class SimpleController { - - @ExceptionHandler(IOException.class) - public String handleIOException(IOException ex, PortletRequest request) { - return "X:" + ClassUtils.getShortName(ex.getClass()); - } - - @ExceptionHandler(SocketException.class) - public String handleSocketException(Exception ex, PortletResponse response) { - return "Y:" + ClassUtils.getShortName(ex.getClass()); - } - - @ExceptionHandler(IllegalArgumentException.class) - public String handleIllegalArgumentException(Exception ex) { - return ClassUtils.getShortName(ex.getClass()); - } - - } - - - @Controller - private static class InheritedController extends SimpleController { - - @Override - public String handleIOException(IOException ex, PortletRequest request) { - return "GenericError"; - } - } - - - @Controller - private static class AmbiguousController { - - @ExceptionHandler({BindException.class, IllegalArgumentException.class}) - public String handle1(Exception ex, PortletRequest request, PortletResponse response) { - return ClassUtils.getShortName(ex.getClass()); - } - - @ExceptionHandler - public String handle2(IllegalArgumentException ex) { - return ClassUtils.getShortName(ex.getClass()); - } - - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java deleted file mode 100644 index 7c2872b995..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java +++ /dev/null @@ -1,1316 +0,0 @@ -/* - * Copyright 2002-2015 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.annotation; - -import java.io.IOException; -import java.io.Writer; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.EventResponse; -import javax.portlet.MimeResponse; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.ResourceResponse; -import javax.portlet.StateAwareResponse; -import javax.portlet.WindowState; -import javax.servlet.http.Cookie; - -import org.junit.Test; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.propertyeditors.CustomDateEditor; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigUtils; -import org.springframework.core.MethodParameter; -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockEvent; -import org.springframework.mock.web.portlet.MockEventRequest; -import org.springframework.mock.web.portlet.MockEventResponse; -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.mock.web.portlet.MockResourceRequest; -import org.springframework.mock.web.portlet.MockResourceResponse; -import org.springframework.stereotype.Controller; -import org.springframework.tests.sample.beans.DerivedTestBean; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.ui.ExtendedModelMap; -import org.springframework.ui.Model; -import org.springframework.ui.ModelMap; -import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.SessionAttributes; -import org.springframework.web.bind.support.SessionStatus; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.bind.support.WebBindingInitializer; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.portlet.DispatcherPortlet; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.NoHandlerFoundException; -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.StaticPortletApplicationContext; -import org.springframework.web.portlet.mvc.AbstractController; - -import static org.junit.Assert.*; - -/** - * @author Juergen Hoeller - * @since 3.0 - */ -public class Portlet20AnnotationControllerTests { - - @Test - public void standardHandleMethod() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class)); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test", response.getContentAsString()); - } - - @Test - public void standardHandleMethodWithResources() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletConfig(getPortletConfig()); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class)); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockResourceRequest resourceRequest = new MockResourceRequest("/resource1"); - MockResourceResponse resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertEquals("/resource1", resourceResponse.getForwardedUrl()); - assertNull(resourceResponse.getProperty(ResourceResponse.HTTP_STATUS_CODE)); - - resourceRequest = new MockResourceRequest("/WEB-INF/resource2"); - resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertNull(resourceResponse.getForwardedUrl()); - assertEquals("404", resourceResponse.getProperty(ResourceResponse.HTTP_STATUS_CODE)); - - resourceRequest = new MockResourceRequest("/META-INF/resource3"); - resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertNull(resourceResponse.getForwardedUrl()); - assertEquals("404", resourceResponse.getProperty(ResourceResponse.HTTP_STATUS_CODE)); - } - - @Test - public void adaptedHandleMethods() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController.class); - } - - @Test - public void adaptedHandleMethods2() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController2.class); - } - - @Test - public void adaptedHandleMethods3() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController3.class); - } - - @Test - public void adaptedHandleMethods4() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController4.class); - } - - private void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass)); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockActionRequest actionRequest = new MockActionRequest(PortletMode.VIEW); - MockActionResponse actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - assertEquals("value", actionResponse.getRenderParameter("test")); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.setSession(actionRequest.getPortletSession()); - request.setParameters(actionResponse.getRenderParameterMap()); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test-name1-typeMismatch", response.getContentAsString()); - assertNull(request.getPortletSession().getAttribute("testBean")); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("param1", "value1"); - request.addParameter("param2", "2"); - request.addProperty("header1", "10"); - request.setCookies(new Cookie("cookie1", "3")); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test-value1-2-10-3", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.HELP); - request.addParameter("name", "name1"); - request.addParameter("age", "2"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test-name1-2", response.getContentAsString()); - } - - @Test - public void formController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); - } - - @Test - public void modelFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyModelFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); - } - - @Test - public void commandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyCommandProvidingFormController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void typedCommandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyTypedCommandProvidingFormController.class)); - wac.registerBeanDefinition("controller2", new RootBeanDefinition(MyOtherTypedCommandProvidingFormController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer()); - adapterDef.getPropertyValues().add("customArgumentResolver", new MySpecialArgumentResolver()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("myParam", "myValue"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("myParam", "myOtherValue"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void binderInitializingCommandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyBinderInitializingCommandProvidingFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void specificBinderInitializingCommandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MySpecificBinderInitializingCommandProvidingFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void parameterDispatchingController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletContext(new MockPortletContext()); - RootBeanDefinition bd = new RootBeanDefinition(MyParameterDispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("view", "other"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("surprise", "!"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void typeLevelParameterDispatchingController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletContext(new MockPortletContext()); - RootBeanDefinition bd = new RootBeanDefinition(MyTypeLevelParameterDispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - RootBeanDefinition bd2 = new RootBeanDefinition(MySpecialParameterDispatchingController.class); - bd2.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller2", bd2); - RootBeanDefinition bd3 = new RootBeanDefinition(MyOtherSpecialParameterDispatchingController.class); - bd3.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller3", bd3); - RootBeanDefinition bd4 = new RootBeanDefinition(MyParameterDispatchingController.class); - bd4.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller4", bd4); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.HELP); - MockRenderResponse response = new MockRenderResponse(); - try { - portlet.render(request, response); - fail("Should have thrown NoHandlerFoundException"); - } - catch (NoHandlerFoundException ex) { - // expected - } - - request = new MockRenderRequest(PortletMode.EDIT); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myDefaultView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "mySpecialValue"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("mySpecialView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myOtherSpecialValue"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherSpecialView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("view", "other"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("surprise", "!"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void portlet20DispatchingController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletContext(new MockPortletContext()); - RootBeanDefinition bd = new RootBeanDefinition(MyPortlet20DispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - wac.registerBeanDefinition("controller2", new RootBeanDefinition(DetailsController.class)); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - MockActionRequest actionRequest = new MockActionRequest("this"); - MockActionResponse actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(actionResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value", response.getContentAsString()); - - actionRequest = new MockActionRequest("that"); - actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(actionResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value2", response.getContentAsString()); - - actionRequest = new MockActionRequest("else"); - actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(actionResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value3", response.getContentAsString()); - - actionRequest = new MockActionRequest("error"); - actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(actionResponse.getRenderParameterMap()); - request.setSession(actionRequest.getPortletSession()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("XXX", response.getContentAsString()); - - MockEventRequest eventRequest = new MockEventRequest(new MockEvent("event1")); - MockEventResponse eventResponse = new MockEventResponse(); - portlet.processEvent(eventRequest, eventResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(eventResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value3", response.getContentAsString()); - - eventRequest = new MockEventRequest(new MockEvent("event2")); - eventResponse = new MockEventResponse(); - portlet.processEvent(eventRequest, eventResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(eventResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value4", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.NORMAL); - request.setParameters(actionResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - MockResourceRequest resourceRequest = new MockResourceRequest("resource1"); - MockResourceResponse resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertEquals("myResource", resourceResponse.getContentAsString()); - - resourceRequest = new MockResourceRequest("resource2"); - resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertEquals("myDefaultResource", resourceResponse.getContentAsString()); - } - - @Test - public void eventDispatchingController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletContext(new MockPortletContext()); - RootBeanDefinition bd = new RootBeanDefinition(MyPortlet20DispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - wac.registerBeanDefinition("controller2", new RootBeanDefinition(DetailsController.class)); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - MockActionRequest actionRequest = new MockActionRequest("this"); - MockActionResponse actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(actionResponse.getRenderParameterMap()); - request.setSession(actionRequest.getPortletSession()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value", response.getContentAsString()); - - actionRequest = new MockActionRequest(); - actionRequest.addParameter("action", "details"); - actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(actionResponse.getRenderParameterMap()); - request.setSession(actionRequest.getPortletSession()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-details", response.getContentAsString()); - - MockEventRequest eventRequest = new MockEventRequest(new MockEvent("event1")); - eventRequest.setParameters(actionRequest.getParameterMap()); - MockEventResponse eventResponse = new MockEventResponse(); - portlet.processEvent(eventRequest, eventResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(eventResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value3", response.getContentAsString()); - - eventRequest = new MockEventRequest(new MockEvent("event3")); - eventRequest.setParameters(actionRequest.getParameterMap()); - eventResponse = new MockEventResponse(); - portlet.processEvent(eventRequest, eventResponse); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.MAXIMIZED); - request.setParameters(eventResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLargeView-value4", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW, WindowState.NORMAL); - request.setParameters(actionResponse.getRenderParameterMap()); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - MockResourceRequest resourceRequest = new MockResourceRequest("resource1"); - MockResourceResponse resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertEquals("myResource", resourceResponse.getContentAsString()); - - resourceRequest = new MockResourceRequest("resource2"); - resourceResponse = new MockResourceResponse(); - portlet.serveResource(resourceRequest, resourceResponse); - assertEquals("myDefaultResource", resourceResponse.getContentAsString()); - } - - @Test - public void testPredicatePriorityComparisonAcrossControllers() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - // The order of handler registration is important to get - // the collection with [Render,Action,Render] predicates - wac.registerSingleton("firstController", FirstController.class); - wac.registerSingleton("secondController", SecondController.class); - wac.registerSingleton("thirdController", ThirdController.class); - wac.registerSingleton("handlerMapping", DefaultAnnotationHandlerMapping.class); - wac.registerSingleton("handlerAdapter", AnnotationMethodHandlerAdapter.class); - wac.setPortletContext(new MockPortletContext()); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - // Make sure all 6 annotated methods can be called - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - - // renderFirst - portlet.render(request, response); - assertArrayEquals(new String[] { "renderFirst" }, response.getProperties("RESPONSE")); - - // renderSecond - request.setWindowState(WindowState.MAXIMIZED); - request.setParameter("report", "second"); - portlet.render(request, response); - assertArrayEquals(new String[] { "renderSecond" }, response.getProperties("RESPONSE")); - - // renderThirds - request.setWindowState(WindowState.MAXIMIZED); - request.setParameter("report", "third"); - portlet.render(request, response); - assertArrayEquals(new String[] { "renderThird" }, response.getProperties("RESPONSE")); - - MockResourceRequest resourceRequest; - MockResourceResponse resourceResponse = new MockResourceResponse(); - - // resourceFirst - resourceRequest = new MockResourceRequest("first"); - portlet.serveResource(resourceRequest, resourceResponse); - assertArrayEquals(new String[] { "resourceFirst" }, resourceResponse.getProperties("RESPONSE")); - - // resourceSecond - resourceRequest = new MockResourceRequest("second"); - portlet.serveResource(resourceRequest, resourceResponse); - assertArrayEquals(new String[] { "resourceSecond" }, resourceResponse.getProperties("RESPONSE")); - - // resourceThirds - resourceRequest = new MockResourceRequest("third"); - portlet.serveResource(resourceRequest, resourceResponse); - assertArrayEquals(new String[] { "resourceThird" }, resourceResponse.getProperties("RESPONSE")); - } - - - /* - * Controllers - */ - - @RequestMapping("VIEW") - private static class MyController extends AbstractController { - - @Override - protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) throws Exception { - response.getWriter().write("test"); - return null; - } - } - - - @Controller - private static class MyAdaptedController { - - @RequestMapping("VIEW") - @ActionMapping - public void myHandle(ActionRequest request, ActionResponse response) throws IOException { - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - @RenderMapping - public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2, - @RequestHeader("header1") long h1, @CookieValue("cookie1") Cookie c1, - RenderResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue()); - } - - @RequestMapping("HELP") - @RenderMapping - public void myHandle(TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("VIEW") - @RenderMapping - public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - private static class MyAdaptedController2 { - - @RequestMapping("VIEW") - @ActionMapping - public void myHandle(ActionRequest request, ActionResponse response) throws IOException { - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - @RenderMapping - public void myHandle(@RequestParam("param1") String p1, int param2, RenderResponse response, - @RequestHeader("header1") String h1, @CookieValue("cookie1") String c1) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2 + "-" + h1 + "-" + c1); - } - - @RequestMapping("HELP") - @RenderMapping - public void myHandle(TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("VIEW") - @RenderMapping - public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - @RequestMapping({"VIEW", "EDIT", "HELP"}) - private static class MyAdaptedController3 { - - @ActionMapping - public void myHandle(ActionRequest request, ActionResponse response) { - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - @RenderMapping - public void myHandle(@RequestParam("param1") String p1, int param2, @RequestHeader Integer header1, - @CookieValue int cookie1, RenderResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1); - } - - @RequestMapping("HELP") - @RenderMapping - public void myHandle(TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RenderMapping - public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - @SessionAttributes("testBean") - private static class MyAdaptedController4 { - - @RequestMapping("VIEW") - @ActionMapping - public void myHandle(Model model, ActionResponse response, SessionStatus status) { - TestBean tb = new TestBean(); - tb.setJedi(true); - model.addAttribute("testBean", tb); - status.setComplete(); - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - @RenderMapping - public void myHandle(@RequestParam("param1") String p1, int param2, RenderResponse response, - @RequestHeader("header1") String h1, @CookieValue("cookie1") String c1) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2 + "-" + h1 + "-" + c1); - } - - @RequestMapping("HELP") - @RenderMapping - public void myHandle(@ModelAttribute("tb") TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("VIEW") - @RenderMapping - public void myHandle(@ModelAttribute("testBean") TestBean tb, Errors errors, RenderResponse response, PortletSession session) throws IOException { - assertTrue(tb.isJedi()); - assertNull(session.getAttribute("testBean")); - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - private static class MyFormController { - - @ModelAttribute("testBeanList") - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @RequestMapping("VIEW") - @RenderMapping - public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, ModelMap model) { - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - } - - - @Controller - private static class MyModelFormController { - - @ModelAttribute - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @RequestMapping("VIEW") - @RenderMapping - public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, Model model) { - if (!model.containsAttribute("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - } - - - @Controller - private static class MyCommandProvidingFormController extends MyFormController { - - @ModelAttribute("myCommand") - private TestBean createTestBean( - @RequestParam T defaultName, Map model, @RequestParam Date date) { - model.put("myKey", "myOriginalValue"); - return new TestBean(defaultName.getClass().getSimpleName() + ":" + defaultName.toString()); - } - - @Override - @RequestMapping("VIEW") - @RenderMapping - public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) { - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - - @RequestMapping("EDIT") - @RenderMapping - public String myOtherHandle(TB tb, BindingResult errors, ExtendedModelMap model, MySpecialArg arg) { - TestBean tbReal = (TestBean) tb; - tbReal.setName("myName"); - assertTrue(model.get("ITestBean") instanceof DerivedTestBean); - assertNotNull(arg); - return super.myHandle(tbReal, errors, model); - } - - @ModelAttribute - @SuppressWarnings("unchecked") - protected TB2 getModelAttr() { - return (TB2) new DerivedTestBean(); - } - } - - - private static class MySpecialArg { - - public MySpecialArg(String value) { - } - } - - - @Controller - @RequestMapping(params = "myParam=myValue") - private static class MyTypedCommandProvidingFormController - extends MyCommandProvidingFormController { - - } - - - @Controller - @RequestMapping(params = "myParam=myOtherValue") - private static class MyOtherTypedCommandProvidingFormController - extends MyCommandProvidingFormController { - - @Override - @RequestMapping("VIEW") - @RenderMapping - public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) { - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myOtherView"; - } - } - - - @Controller - @SuppressWarnings("rawtypes") - private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - - @InitBinder - private void initBinder(WebDataBinder binder) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - - @Controller - @SuppressWarnings("rawtypes") - private static class MySpecificBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - - @InitBinder({"myCommand", "date"}) - private void initBinder(WebDataBinder binder) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - - private static class MyWebBindingInitializer implements WebBindingInitializer { - - @Override - public void initBinder(WebDataBinder binder, WebRequest request) { - assertNotNull(request.getLocale()); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - - private static class MySpecialArgumentResolver implements WebArgumentResolver { - - @Override - public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { - if (methodParameter.getParameterType().equals(MySpecialArg.class)) { - return new MySpecialArg("myValue"); - } - return UNRESOLVED; - } - } - - - @Controller - @RequestMapping("VIEW") - private static class MyParameterDispatchingController { - - @Autowired - private PortletContext portletContext; - - @Autowired - private PortletRequest request; - - @Autowired - private PortletResponse response; - - @Autowired - private PortletSession session; - - @Autowired - private WebRequest webRequest; - - @RenderMapping - public void myHandle(RenderResponse response) throws IOException { - if (this.portletContext == null || this.request == null || this.response == null || - this.session == null || this.webRequest == null) { - throw new IllegalStateException(); - } - response.getWriter().write("myView"); - } - - @RenderMapping(params = {"view", "!lang"}) - public void myOtherHandle(RenderResponse response) throws IOException { - response.getWriter().write("myOtherView"); - } - - @RenderMapping(params = {"view=my", "lang=de"}) - public void myLangHandle(RenderResponse response) throws IOException { - response.getWriter().write("myLangView"); - } - - @RenderMapping(params = "surprise") - public void mySurpriseHandle(RenderResponse response) throws IOException { - response.getWriter().write("mySurpriseView"); - } - } - - - @Controller - @RequestMapping(value = "EDIT", params = "myParam=myValue") - private static class MyTypeLevelParameterDispatchingController extends MyParameterDispatchingController { - - } - - - @Controller - @RequestMapping("EDIT") - private static class MySpecialParameterDispatchingController { - - @RenderMapping(params = "myParam=mySpecialValue") - public void myHandle(RenderResponse response) throws IOException { - response.getWriter().write("mySpecialView"); - } - - @RenderMapping - public void myDefaultHandle(RenderResponse response) throws IOException { - response.getWriter().write("myDefaultView"); - } - } - - - @Controller - @RequestMapping("EDIT") - private static class MyOtherSpecialParameterDispatchingController { - - @RenderMapping(params = "myParam=myOtherSpecialValue") - public void myHandle(RenderResponse response) throws IOException { - response.getWriter().write("myOtherSpecialView"); - } - } - - - @Controller - @RequestMapping("VIEW") - private static class MyPortlet20DispatchingController { - - @ActionMapping(name = "this") - public void myHandle(StateAwareResponse response) { - response.setRenderParameter("test", "value"); - } - - @ActionMapping("that") - public void myHandle2(StateAwareResponse response) { - response.setRenderParameter("test", "value2"); - } - - @ActionMapping("error") - public void myError(StateAwareResponse response) { - throw new IllegalStateException("XXX"); - } - - @EventMapping("event1") - public void myHandle(EventResponse response) throws IOException { - response.setRenderParameter("test", "value3"); - } - - @EventMapping("event2") - public void myHandle2(EventResponse response) throws IOException { - response.setRenderParameter("test", "value4"); - } - - @RenderMapping("MAXIMIZED") - public void myHandle(Writer writer, @RequestParam("test") String renderParam) throws IOException { - writer.write("myLargeView-" + renderParam); - } - - @RenderMapping - public void myDefaultHandle(Writer writer) throws IOException { - writer.write("myView"); - } - - @ExceptionHandler - public void handleException(Exception ex, Writer writer) throws IOException { - writer.write(ex.getMessage()); - } - - @ResourceMapping("resource1") - public void myResource(Writer writer) throws IOException { - writer.write("myResource"); - } - } - - - @Controller - @RequestMapping("VIEW") - private static class DetailsController { - - @ActionMapping("else") - public void myHandle(StateAwareResponse response) { - response.setRenderParameter("test", "value3"); - } - - @EventMapping("event3") - public void myHandle2(EventResponse response) throws IOException { - response.setRenderParameter("test", "value4"); - } - - @ActionMapping(params = "action=details") - public void renderDetails(ActionRequest request, ActionResponse response, Model model) { - response.setRenderParameter("test", "details"); - } - - @ResourceMapping - public void myDefaultResource(Writer writer) throws IOException { - writer.write("myDefaultResource"); - } - } - - - private static class TestView { - - @SuppressWarnings("deprecation") - public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception { - TestBean tb = (TestBean) model.get("testBean"); - if (tb == null) { - tb = (TestBean) model.get("myCommand"); - } - if (tb.getName().endsWith("myDefaultName")) { - assertEquals(107, tb.getDate().getYear()); - } - Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean"); - if (errors == null) { - errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "myCommand"); - } - if (errors.hasFieldErrors("date")) { - throw new IllegalStateException(); - } - List testBeans = (List) model.get("testBeanList"); - response.getWriter().write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() + - "-" + ((TestBean) testBeans.get(0)).getName() + "-" + model.get("myKey")); - } - } - - - @RequestMapping("view") - public static class FirstController { - - @RenderMapping - public String renderFirst(RenderResponse response) { - response.setProperty("RESPONSE", "renderFirst"); - return "renderFirst"; - } - - @ResourceMapping("first") - public String resourceFirst(ResourceResponse response) { - response.setProperty("RESPONSE", "resourceFirst"); - return "resourceFirst"; - } - } - - - @RequestMapping("view") - public static class SecondController { - - @ResourceMapping("second") - public String processResource(ResourceResponse response) { - response.setProperty("RESPONSE", "resourceSecond"); - return "resourceSecond"; - } - - @RenderMapping(windowState = "MAXIMIZED", params = "report=second") - public String renderSecond(RenderResponse response) { - response.setProperty("RESPONSE", "renderSecond"); - return "renderSecond"; - } - } - - - @RequestMapping("view") - public static class ThirdController { - - @ResourceMapping("third") - public String processResource(ResourceResponse response) { - response.setProperty("RESPONSE", "resourceThird"); - return "resourceThird"; - } - - @RenderMapping(windowState = "MAXIMIZED", params = "report=third") - public String renderSecond(RenderResponse response) { - response.setProperty("RESPONSE", "renderThird"); - return "renderThird"; - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java deleted file mode 100644 index db72a361fe..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java +++ /dev/null @@ -1,874 +0,0 @@ -/* - * Copyright 2002-2015 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.annotation; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.MimeResponse; -import javax.portlet.PortletContext; -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; -import javax.portlet.PortletSession; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Test; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.propertyeditors.CustomDateEditor; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.AnnotationConfigUtils; -import org.springframework.core.MethodParameter; -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockPortletConfig; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockRenderRequest; -import org.springframework.mock.web.portlet.MockRenderResponse; -import org.springframework.stereotype.Controller; -import org.springframework.tests.sample.beans.DerivedTestBean; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.ui.ExtendedModelMap; -import org.springframework.ui.Model; -import org.springframework.ui.ModelMap; -import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; -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.RequestParam; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.bind.support.WebBindingInitializer; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.portlet.DispatcherPortlet; -import org.springframework.web.portlet.ModelAndView; -import org.springframework.web.portlet.NoHandlerFoundException; -import org.springframework.web.portlet.context.StaticPortletApplicationContext; -import org.springframework.web.portlet.mvc.AbstractController; -import org.springframework.web.servlet.View; -import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver; - -import static org.junit.Assert.*; - -/** - * @author Juergen Hoeller - * @since 2.5 - */ -public class PortletAnnotationControllerTests { - - @Test - public void standardHandleMethod() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class)); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test", response.getContentAsString()); - } - - @Test - public void adaptedHandleMethods() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController.class); - } - - @Test - public void adaptedHandleMethods2() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController2.class); - } - - @Test - public void adaptedHandleMethods3() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController3.class); - } - - public void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass)); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockActionRequest actionRequest = new MockActionRequest(PortletMode.VIEW); - MockActionResponse actionResponse = new MockActionResponse(); - portlet.processAction(actionRequest, actionResponse); - assertEquals("value", actionResponse.getRenderParameter("test")); - - MockRenderRequest request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("param1", "value1"); - request.addParameter("param2", "2"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test-value1-2", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.HELP); - request.addParameter("name", "name1"); - request.addParameter("age", "2"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test-name1-2", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("test-name1-typeMismatch", response.getContentAsString()); - } - - @Test - public void formController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); - } - - @Test - public void modelFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyModelFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); - } - - @Test - public void commandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyCommandProvidingFormController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void typedCommandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyTypedCommandProvidingFormController.class)); - wac.registerBeanDefinition("controller2", new RootBeanDefinition(MyOtherTypedCommandProvidingFormController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer()); - adapterDef.getPropertyValues().add("customArgumentResolver", new MySpecialArgumentResolver()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("myParam", "myValue"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("myParam", "myOtherValue"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void binderInitializingCommandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyBinderInitializingCommandProvidingFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void specificBinderInitializingCommandProvidingFormController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MySpecificBinderInitializingCommandProvidingFormController.class)); - wac.refresh(); - return wac; - } - @Override - protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception { - new TestView().render(mv.getViewName(), mv.getModel(), request, response); - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void parameterDispatchingController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletContext(new MockPortletContext()); - RootBeanDefinition bd = new RootBeanDefinition(MyParameterDispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("view", "other"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - request.addParameter("surprise", "!"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void typeLevelParameterDispatchingController() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - StaticPortletApplicationContext wac = new StaticPortletApplicationContext(); - wac.setPortletContext(new MockPortletContext()); - RootBeanDefinition bd = new RootBeanDefinition(MyTypeLevelParameterDispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - RootBeanDefinition bd2 = new RootBeanDefinition(MySpecialParameterDispatchingController.class); - bd2.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller2", bd2); - RootBeanDefinition bd3 = new RootBeanDefinition(MyOtherSpecialParameterDispatchingController.class); - bd3.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller3", bd3); - RootBeanDefinition bd4 = new RootBeanDefinition(MyParameterDispatchingController.class); - bd4.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller4", bd4); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.HELP); - MockRenderResponse response = new MockRenderResponse(); - try { - portlet.render(request, response); - fail("Should have thrown NoHandlerFoundException"); - } - catch (NoHandlerFoundException ex) { - // expected - } - - request = new MockRenderRequest(PortletMode.EDIT); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myDefaultView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "mySpecialValue"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("mySpecialView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myOtherSpecialValue"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherSpecialView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.VIEW); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("view", "other"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockRenderRequest(PortletMode.EDIT); - request.addParameter("myParam", "myValue"); - request.addParameter("surprise", "!"); - response = new MockRenderResponse(); - portlet.render(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void mavResolver() throws Exception { - DispatcherPortlet portlet = new DispatcherPortlet() { - @Override - protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(ModelAndViewResolverController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues() - .add("customModelAndViewResolver", new MyModelAndViewResolver()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - portlet.init(new MockPortletConfig()); - - MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW); - MockRenderResponse response = new MockRenderResponse(); - portlet.render(request, response); - } - - - @RequestMapping("VIEW") - private static class MyController extends AbstractController { - - @Override - protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) throws Exception { - response.getWriter().write("test"); - return null; - } - } - - - @Controller - private static class MyAdaptedController { - - @RequestMapping("VIEW") - public void myHandle(ActionRequest request, ActionResponse response) throws IOException { - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - public void myHandle(@RequestParam("param1")String p1, @RequestParam("param2")int p2, RenderResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + p2); - } - - @RequestMapping("HELP") - public void myHandle(TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("VIEW") - public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - private static class MyAdaptedController2 { - - @RequestMapping("VIEW") - public void myHandle(ActionRequest request, ActionResponse response) throws IOException { - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - public void myHandle(@RequestParam("param1")String p1, int param2, RenderResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2); - } - - @RequestMapping("HELP") - public void myHandle(TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("VIEW") - public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - @RequestMapping({"VIEW", "EDIT", "HELP"}) - private static class MyAdaptedController3 { - - @RequestMapping - public void myHandle(ActionRequest request, ActionResponse response) { - response.setRenderParameter("test", "value"); - } - - @RequestMapping("EDIT") - public void myHandle(@RequestParam("param1")String p1, @RequestParam("param2")int p2, RenderResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + p2); - } - - @RequestMapping("HELP") - public void myHandle(TestBean tb, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping - public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - - @Controller - private static class MyFormController { - - @ModelAttribute("testBeanList") - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @RequestMapping("VIEW") - public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, ModelMap model) { - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - } - - - @Controller - private static class MyModelFormController { - - @ModelAttribute - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @RequestMapping("VIEW") - public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, Model model) { - if (!model.containsAttribute("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - } - - - @Controller - private static class MyCommandProvidingFormController extends MyFormController { - - @ModelAttribute("myCommand") - private TestBean createTestBean( - @RequestParam T defaultName, Map model, @RequestParam Date date) { - model.put("myKey", "myOriginalValue"); - return new TestBean(defaultName.getClass().getSimpleName() + ":" + defaultName.toString()); - } - - @Override - @RequestMapping("VIEW") - public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) { - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - - @RequestMapping("EDIT") - public String myOtherHandle(TB tb, BindingResult errors, ExtendedModelMap model, MySpecialArg arg) { - TestBean tbReal = (TestBean) tb; - tbReal.setName("myName"); - assertTrue(model.get("ITestBean") instanceof DerivedTestBean); - assertNotNull(arg); - return super.myHandle(tbReal, errors, model); - } - - @ModelAttribute - @SuppressWarnings("unchecked") - protected TB2 getModelAttr() { - return (TB2) new DerivedTestBean(); - } - } - - - private static class MySpecialArg { - - public MySpecialArg(String value) { - } - } - - - @Controller - @RequestMapping(params = "myParam=myValue") - private static class MyTypedCommandProvidingFormController - extends MyCommandProvidingFormController { - - } - - - @Controller - @RequestMapping(params = "myParam=myOtherValue") - private static class MyOtherTypedCommandProvidingFormController - extends MyCommandProvidingFormController { - - @Override - @RequestMapping("VIEW") - public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) { - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myOtherView"; - } - } - - - @Controller - @SuppressWarnings("rawtypes") - private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - - @InitBinder - private void initBinder(WebDataBinder binder) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - - @Controller - @SuppressWarnings("rawtypes") - private static class MySpecificBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - - @InitBinder({"myCommand", "date"}) - private void initBinder(WebDataBinder binder) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - - private static class MyWebBindingInitializer implements WebBindingInitializer { - - @Override - public void initBinder(WebDataBinder binder, WebRequest request) { - assertNotNull(request.getLocale()); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - - private static class MySpecialArgumentResolver implements WebArgumentResolver { - - @Override - public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { - if (methodParameter.getParameterType().equals(MySpecialArg.class)) { - return new MySpecialArg("myValue"); - } - return UNRESOLVED; - } - } - - - @Controller - @RequestMapping("VIEW") - private static class MyParameterDispatchingController { - - @Autowired - private PortletContext portletContext; - - @Autowired - private PortletSession session; - - @Autowired - private PortletRequest request; - - @RequestMapping - public void myHandle(RenderResponse response) throws IOException { - if (this.portletContext == null || this.session == null || this.request == null) { - throw new IllegalStateException(); - } - response.getWriter().write("myView"); - } - - @RequestMapping(params = {"view", "!lang"}) - public void myOtherHandle(RenderResponse response) throws IOException { - response.getWriter().write("myOtherView"); - } - - @RequestMapping(params = {"view=my", "lang=de"}) - public void myLangHandle(RenderResponse response) throws IOException { - response.getWriter().write("myLangView"); - } - - @RequestMapping(params = "surprise") - public void mySurpriseHandle(RenderResponse response) throws IOException { - response.getWriter().write("mySurpriseView"); - } - } - - - @Controller - @RequestMapping(value = "EDIT", params = "myParam=myValue") - private static class MyTypeLevelParameterDispatchingController extends MyParameterDispatchingController { - - } - - - @Controller - @RequestMapping("EDIT") - private static class MySpecialParameterDispatchingController { - - @RequestMapping(params = "myParam=mySpecialValue") - public void myHandle(RenderResponse response) throws IOException { - response.getWriter().write("mySpecialView"); - } - - @RequestMapping - public void myDefaultHandle(RenderResponse response) throws IOException { - response.getWriter().write("myDefaultView"); - } - } - - - @Controller - @RequestMapping("EDIT") - private static class MyOtherSpecialParameterDispatchingController { - - @RequestMapping(params = "myParam=myOtherSpecialValue") - public void myHandle(RenderResponse response) throws IOException { - response.getWriter().write("myOtherSpecialView"); - } - } - - - private static class TestView { - - @SuppressWarnings("deprecation") - public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception { - TestBean tb = (TestBean) model.get("testBean"); - if (tb == null) { - tb = (TestBean) model.get("myCommand"); - } - if (tb.getName().endsWith("myDefaultName")) { - assertEquals(107, tb.getDate().getYear()); - } - Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean"); - if (errors == null) { - errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "myCommand"); - } - if (errors.hasFieldErrors("date")) { - throw new IllegalStateException(); - } - List testBeans = (List) model.get("testBeanList"); - response.getWriter().write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() + - "-" + ((TestBean) testBeans.get(0)).getName() + "-" + model.get("myKey")); - } - } - - @Controller - public static class ModelAndViewResolverController { - - @RequestMapping("VIEW") - public MySpecialArg handle() { - return new MySpecialArg("foo"); - } - } - - public static class MyModelAndViewResolver implements ModelAndViewResolver { - - @Override - public org.springframework.web.servlet.ModelAndView resolveModelAndView(Method handlerMethod, - Class handlerType, - Object returnValue, - ExtendedModelMap implicitModel, - NativeWebRequest webRequest) { - if (returnValue instanceof MySpecialArg) { - return new org.springframework.web.servlet.ModelAndView(new View() { - @Override - public String getContentType() { - return "text/html"; - } - - @Override - public void render(Map model, HttpServletRequest request, HttpServletResponse response) - throws Exception { - response.getWriter().write("myValue"); - } - - }); - } - return UNRESOLVED; - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java deleted file mode 100644 index 7ab898b277..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java +++ /dev/null @@ -1,503 +0,0 @@ -/* - * Copyright 2002-2014 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.File; -import java.io.FileNotFoundException; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequest; -import javax.portlet.PortletSession; - -import org.junit.Test; - -import org.springframework.mock.web.portlet.MockActionRequest; -import org.springframework.mock.web.portlet.MockActionResponse; -import org.springframework.mock.web.portlet.MockPortletContext; -import org.springframework.mock.web.portlet.MockPortletRequest; -import org.springframework.mock.web.portlet.MockPortletSession; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.web.util.WebUtils; - -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.*; - -/** - * @author Rick Evans - * @author Chris Beams - */ -public final class PortletUtilsTests { - - @Test(expected=IllegalArgumentException.class) - public void testGetTempDirWithNullPortletContext() throws Exception { - PortletUtils.getTempDir(null); - } - - public void testGetTempDirSunnyDay() throws Exception { - MockPortletContext ctx = new MockPortletContext(); - Object expectedTempDir = new File("doesn't exist but that's ok in the context of this test"); - ctx.setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, expectedTempDir); - assertSame(expectedTempDir, PortletUtils.getTempDir(ctx)); - } - - public void testGetRealPathInterpretsLocationAsRelativeToWebAppRootIfPathDoesNotBeginWithALeadingSlash() throws Exception { - final String originalPath = "web/foo"; - final String expectedRealPath = "/" + originalPath; - PortletContext ctx = mock(PortletContext.class); - given(ctx.getRealPath(expectedRealPath)).willReturn(expectedRealPath); - - String actualRealPath = PortletUtils.getRealPath(ctx, originalPath); - assertEquals(expectedRealPath, actualRealPath); - - verify(ctx); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetRealPathWithNullPortletContext() throws Exception { - PortletUtils.getRealPath(null, "/foo"); - } - - @Test(expected=NullPointerException.class) - public void testGetRealPathWithNullPath() throws Exception { - PortletUtils.getRealPath(new MockPortletContext(), null); - } - - @Test(expected=FileNotFoundException.class) - public void testGetRealPathWithPathThatCannotBeResolvedToFile() throws Exception { - PortletUtils.getRealPath(new MockPortletContext() { - @Override - public String getRealPath(String path) { - return null; - } - }, "/rubbish"); - } - - @Test - public void testPassAllParametersToRenderPhase() throws Exception { - MockActionRequest request = new MockActionRequest(); - request.setParameter("William", "Baskerville"); - request.setParameter("Adso", "Melk"); - MockActionResponse response = new MockActionResponse(); - PortletUtils.passAllParametersToRenderPhase(request, response); - assertEquals("The render parameters map is obviously not being populated with the request parameters.", - request.getParameterMap().size(), response.getRenderParameterMap().size()); - } - - @Test - public void testGetParametersStartingWith() throws Exception { - final String targetPrefix = "francisan_"; - final String badKey = "dominican_Bernard"; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetPrefix + "William", "Baskerville"); - request.setParameter(targetPrefix + "Adso", "Melk"); - request.setParameter(badKey, "Gui"); - Map actualParameters = PortletUtils.getParametersStartingWith(request, targetPrefix); - assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters); - assertEquals("Obviously not finding all of the correct parameters", 2, actualParameters.size()); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William")); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso")); - assertFalse("Obviously not finding all of the correct parameters (is returning a parameter whose name does not start with the desired prefix", - actualParameters.containsKey(badKey)); - } - - @Test - public void testGetParametersStartingWithUnpicksScalarParameterValues() throws Exception { - final String targetPrefix = "francisan_"; - final String badKey = "dominican_Bernard"; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetPrefix + "William", "Baskerville"); - request.setParameter(targetPrefix + "Adso", new String[]{"Melk", "Of Melk"}); - request.setParameter(badKey, "Gui"); - Map actualParameters = PortletUtils.getParametersStartingWith(request, targetPrefix); - assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters); - assertEquals("Obviously not finding all of the correct parameters", 2, actualParameters.size()); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William")); - assertEquals("Not picking scalar parameter value out correctly", - "Baskerville", actualParameters.get("William")); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso")); - assertFalse("Obviously not finding all of the correct parameters (is returning a parameter whose name does not start with the desired prefix", - actualParameters.containsKey(badKey)); - } - - @Test - public void testGetParametersStartingWithYieldsEverythingIfTargetPrefixIsNull() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - request.setParameter("William", "Baskerville"); - request.setParameter("Adso", "Melk"); - request.setParameter("dominican_Bernard", "Gui"); - Map actualParameters = PortletUtils.getParametersStartingWith(request, null); - assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters); - assertEquals("Obviously not finding all of the correct parameters", request.getParameterMap().size(), actualParameters.size()); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William")); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso")); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("dominican_Bernard")); - } - - @Test - public void testGetParametersStartingWithYieldsEverythingIfTargetPrefixIsTheEmptyString() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - request.setParameter("William", "Baskerville"); - request.setParameter("Adso", "Melk"); - request.setParameter("dominican_Bernard", "Gui"); - Map actualParameters = PortletUtils.getParametersStartingWith(request, ""); - assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters); - assertEquals("Obviously not finding all of the correct parameters", request.getParameterMap().size(), actualParameters.size()); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William")); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso")); - assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("dominican_Bernard")); - } - - @Test - public void testGetParametersStartingWithYieldsEmptyNonNullMapWhenNoParamaterExistInRequest() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - Map actualParameters = PortletUtils.getParametersStartingWith(request, null); - assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters); - assertEquals("Obviously finding some parameters from somewhere (incorrectly)", - request.getParameterMap().size(), actualParameters.size()); - } - - @Test - public void testGetSubmitParameterWithStraightNameMatch() throws Exception { - final String targetSubmitParameter = "William"; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetSubmitParameter, "Baskerville"); - request.setParameter("Adso", "Melk"); - request.setParameter("dominican_Bernard", "Gui"); - String submitParameter = PortletUtils.getSubmitParameter(request, targetSubmitParameter); - assertNotNull(submitParameter); - assertEquals(targetSubmitParameter, submitParameter); - } - - @Test - public void testGetSubmitParameterWithPrefixedParameterMatch() throws Exception { - final String bareParameterName = "William"; - final String targetParameterName = bareParameterName + WebUtils.SUBMIT_IMAGE_SUFFIXES[0]; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetParameterName, "Baskerville"); - request.setParameter("Adso", "Melk"); - String submitParameter = PortletUtils.getSubmitParameter(request, bareParameterName); - assertNotNull(submitParameter); - assertEquals(targetParameterName, submitParameter); - } - - @Test - public void testGetSubmitParameterWithNoParameterMatchJustReturnsNull() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - request.setParameter("Bill", "Baskerville"); - request.setParameter("Adso", "Melk"); - String submitParameter = PortletUtils.getSubmitParameter(request, "William"); - assertNull(submitParameter); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetSubmitParameterWithNullRequest() throws Exception { - final String targetSubmitParameter = "William"; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetSubmitParameter, "Baskerville"); - request.setParameter("Adso", "Melk"); - PortletUtils.getSubmitParameter(null, targetSubmitParameter); - } - - @Test - public void testPassAllParametersToRenderPhaseDoesNotPropagateExceptionIfRedirectAlreadySentAtTimeOfCall() throws Exception { - MockActionRequest request = new MockActionRequest(); - request.setParameter("William", "Baskerville"); - request.setParameter("Adso", "Melk"); - MockActionResponse response = new MockActionResponse() { - @Override - public void setRenderParameter(String key, String[] values) { - throw new IllegalStateException(); - } - }; - PortletUtils.passAllParametersToRenderPhase(request, response); - assertEquals("The render parameters map must not be being populated with the request parameters (Action.sendRedirect(..) aleady called).", - 0, response.getRenderParameterMap().size()); - } - - @Test - public void testClearAllRenderParameters() throws Exception { - MockActionResponse response = new MockActionResponse(); - response.setRenderParameter("William", "Baskerville"); - response.setRenderParameter("Adso", "Melk"); - PortletUtils.clearAllRenderParameters(response); - assertEquals("The render parameters map is obviously not being cleared out.", - 0, response.getRenderParameterMap().size()); - } - - @Test - public void testClearAllRenderParametersDoesNotPropagateExceptionIfRedirectAlreadySentAtTimeOfCall() throws Exception { - MockActionResponse response = new MockActionResponse() { - @Override - public void setRenderParameters(Map parameters) { - throw new IllegalStateException(); - } - }; - response.setRenderParameter("William", "Baskerville"); - response.setRenderParameter("Adso", "Melk"); - PortletUtils.clearAllRenderParameters(response); - assertEquals("The render parameters map must not be cleared if ActionResponse.sendRedirect() has been called (already).", - 2, response.getRenderParameterMap().size()); - } - - @Test - public void testHasSubmitParameterWithStraightNameMatch() throws Exception { - final String targetSubmitParameter = "William"; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetSubmitParameter, "Baskerville"); - request.setParameter("Adso", "Melk"); - request.setParameter("dominican_Bernard", "Gui"); - assertTrue(PortletUtils.hasSubmitParameter(request, targetSubmitParameter)); - } - - @Test - public void testHasSubmitParameterWithPrefixedParameterMatch() throws Exception { - final String bareParameterName = "William"; - final String targetParameterName = bareParameterName + WebUtils.SUBMIT_IMAGE_SUFFIXES[0]; - MockPortletRequest request = new MockPortletRequest(); - request.setParameter(targetParameterName, "Baskerville"); - request.setParameter("Adso", "Melk"); - assertTrue(PortletUtils.hasSubmitParameter(request, bareParameterName)); - } - - @Test - public void testHasSubmitParameterWithNoParameterMatch() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - request.setParameter("Bill", "Baskerville"); - request.setParameter("Adso", "Melk"); - assertFalse(PortletUtils.hasSubmitParameter(request, "William")); - } - - @Test(expected=IllegalArgumentException.class) - public void testHasSubmitParameterWithNullRequest() throws Exception { - PortletUtils.hasSubmitParameter(null, "bingo"); - } - - - @SuppressWarnings("unchecked") - @Test(expected=IllegalArgumentException.class) - public void testExposeRequestAttributesWithNullRequest() throws Exception { - PortletUtils.exposeRequestAttributes(null, Collections.EMPTY_MAP); - } - - @Test(expected=IllegalArgumentException.class) - public void testExposeRequestAttributesWithNullAttributesMap() throws Exception { - PortletUtils.exposeRequestAttributes(new MockPortletRequest(), null); - } - - @Test - public void testExposeRequestAttributesSunnyDay() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - Map attributes = new HashMap(); - attributes.put("ace", "Rick Hunter"); - attributes.put("mentor", "Roy Fokker"); - PortletUtils.exposeRequestAttributes(request, attributes); - assertEquals("Rick Hunter", request.getAttribute("ace")); - assertEquals("Roy Fokker", request.getAttribute("mentor")); - } - - @Test - public void testExposeRequestAttributesWithEmptyAttributesMapIsAnIdempotentOperation() throws Exception { - MockPortletRequest request = new MockPortletRequest(); - Map attributes = new HashMap(); - PortletUtils.exposeRequestAttributes(request, attributes); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetOrCreateSessionAttributeWithNullSession() throws Exception { - PortletUtils.getOrCreateSessionAttribute(null, "bean", TestBean.class); - } - - @Test - public void testGetOrCreateSessionAttributeJustReturnsAttributeIfItAlreadyExists() throws Exception { - MockPortletSession session = new MockPortletSession(); - final TestBean expectedAttribute = new TestBean("Donna Tartt"); - session.setAttribute("donna", expectedAttribute); - Object actualAttribute = PortletUtils.getOrCreateSessionAttribute(session, "donna", TestBean.class); - assertSame(expectedAttribute, actualAttribute); - } - - @Test - public void testGetOrCreateSessionAttributeCreatesAttributeIfItDoesNotAlreadyExist() throws Exception { - MockPortletSession session = new MockPortletSession(); - Object actualAttribute = PortletUtils.getOrCreateSessionAttribute(session, "bean", TestBean.class); - assertNotNull(actualAttribute); - assertEquals("Wrong type of object being instantiated", TestBean.class, actualAttribute.getClass()); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndNullClass() throws Exception { - PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", null); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndClassThatIsAnInterfaceType() throws Exception { - PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", ITestBean.class); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndClassWithNoPublicCtor() throws Exception { - PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", NoPublicCtor.class); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetSessionMutexWithNullSession() throws Exception { - PortletUtils.getSessionMutex(null); - } - - @Test - public void testGetSessionMutexWithNoExistingSessionMutexDefinedJustReturnsTheSessionArgument() throws Exception { - MockPortletSession session = new MockPortletSession(); - Object sessionMutex = PortletUtils.getSessionMutex(session); - assertNotNull("PortletUtils.getSessionMutex(..) must never return a null mutex", sessionMutex); - assertSame("PortletUtils.getSessionMutex(..) must return the exact same PortletSession supplied as an argument if no mutex has been bound as a Session attribute beforehand", - session, sessionMutex); - } - - @Test - public void testGetSessionMutexWithExistingSessionMutexReturnsTheExistingSessionMutex() throws Exception { - MockPortletSession session = new MockPortletSession(); - Object expectSessionMutex = new Object(); - session.setAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE, expectSessionMutex, PortletSession.APPLICATION_SCOPE); - Object actualSessionMutex = PortletUtils.getSessionMutex(session); - assertNotNull("PortletUtils.getSessionMutex(..) must never return a null mutex", actualSessionMutex); - assertSame("PortletUtils.getSessionMutex(..) must return the bound mutex attribute if a mutex has been bound as a Session attribute beforehand", - expectSessionMutex, actualSessionMutex); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetSessionAttributeWithNullPortletRequest() throws Exception { - PortletUtils.getSessionAttribute(null, "foo"); - } - - @Test(expected=IllegalArgumentException.class) - public void testGetRequiredSessionAttributeWithNullPortletRequest() throws Exception { - PortletUtils.getRequiredSessionAttribute(null, "foo"); - } - - @Test(expected=IllegalArgumentException.class) - public void testSetSessionAttributeWithNullPortletRequest() throws Exception { - PortletUtils.setSessionAttribute(null, "foo", "bar"); - } - - @Test - public void testGetSessionAttributeDoes_Not_CreateANewSession() throws Exception { - PortletRequest request = mock(PortletRequest.class); - - Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo"); - assertNull("Must return null if session attribute does not exist (or if Session does not exist)", sessionAttribute); - verify(request).getPortletSession(false); - } - - @Test - public void testGetSessionAttributeWithExistingSession() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute("foo", "foo"); - - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession(false)).willReturn(session); - - Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo"); - assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); - assertEquals("foo", sessionAttribute); - } - - @Test - public void testGetRequiredSessionAttributeWithExistingSession() throws Exception { - MockPortletSession session = new MockPortletSession(); - session.setAttribute("foo", "foo"); - - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession(false)).willReturn(session); - - Object sessionAttribute = PortletUtils.getRequiredSessionAttribute(request, "foo"); - assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); - assertEquals("foo", sessionAttribute); - } - - @Test - public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception { - MockPortletSession session = new MockPortletSession(); - - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession(false)).willReturn(session); - try { - PortletUtils.getRequiredSessionAttribute(request, "foo"); - fail("expected IllegalStateException"); - } - catch (IllegalStateException ex) { /* expected */ } - - } - - @Test - public void testSetSessionAttributeWithExistingSessionAndNullValue() throws Exception { - PortletSession session = mock(PortletSession.class); - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession(false)).willReturn(session); // must not create Session for null value... - PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE); - verify(session).removeAttribute("foo", PortletSession.APPLICATION_SCOPE); - } - - @Test - public void testSetSessionAttributeWithNoExistingSessionAndNullValue() throws Exception { - PortletRequest request = mock(PortletRequest.class); - PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE); - verify(request).getPortletSession(false); // must not create Session for null value... - } - - @Test - public void testSetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception { - PortletSession session = mock(PortletSession.class); - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession()).willReturn(session); // must not create Session ... - PortletUtils.setSessionAttribute(request, "foo", "foo", PortletSession.APPLICATION_SCOPE); - verify(session).setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE); - } - - @Test - public void testGetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception { - PortletSession session = mock(PortletSession.class); - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession(false)).willReturn(session); - given(session.getAttribute("foo", PortletSession.APPLICATION_SCOPE)).willReturn("foo"); - Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo", PortletSession.APPLICATION_SCOPE); - assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); - assertEquals("foo", sessionAttribute); - } - - @Test - public void testGetSessionAttributeWithExistingSessionDefaultsToPortletScope() throws Exception { - PortletSession session = mock(PortletSession.class); - PortletRequest request = mock(PortletRequest.class); - given(request.getPortletSession(false)).willReturn(session); - given(session.getAttribute("foo", PortletSession.PORTLET_SCOPE)).willReturn("foo"); - Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo"); - assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute); - assertEquals("foo", sessionAttribute); - } - - - private static final class NoPublicCtor { - - private NoPublicCtor() { - throw new IllegalArgumentException("Just for eclipse..."); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/resources/log4j.properties b/spring-webmvc-portlet/src/test/resources/log4j.properties deleted file mode 100644 index 0be56f7376..0000000000 --- a/spring-webmvc-portlet/src/test/resources/log4j.properties +++ /dev/null @@ -1,10 +0,0 @@ -log4j.appender.console=org.apache.log4j.ConsoleAppender -log4j.appender.console.layout=org.apache.log4j.PatternLayout -log4j.appender.console.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%c] - %m%n - -log4j.rootCategory=WARN, console -log4j.logger.org.springframework.beans=WARN -log4j.logger.org.springframework.binding=DEBUG - -#log4j.logger.org.springframework.web.portlet=TRACE - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml deleted file mode 100644 index 9a4a216313..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml +++ /dev/null @@ -1,81 +0,0 @@ - - -]> - - - - - - - - - - - - - - - - - - - - - - - dummy - - - -1 - - - - - - - - - true - - - &contextInclude; - - - - /org/springframework/web/portlet/context/WEB-INF/myoverride.properties - - - - - - - classpath:/org/springframework/web/portlet/context/WEB-INF/myplace*.properties - classpath:/org/springframework/web/portlet/context/WEB-INF/myover*.properties - - - - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages.properties b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages.properties deleted file mode 100644 index 57aa4782a7..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages.properties +++ /dev/null @@ -1,6 +0,0 @@ -code1=message1 -code2=message2 - -# Example taken from the javadocs for the java.text.MessageFormat class -message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}. -message.format.example2=This is a test message in the message catalog with no args. diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_GB.properties b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_GB.properties deleted file mode 100644 index 623a71a840..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_GB.properties +++ /dev/null @@ -1,2 +0,0 @@ -# Example taken from the javadocs for the java.text.MessageFormat class -message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on station number {0,number,integer}. \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_US.properties b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_US.properties deleted file mode 100644 index 2bdc094486..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/context-messages_en_US.properties +++ /dev/null @@ -1,5 +0,0 @@ -code1=message1 - -# Example taken from the javadocs for the java.text.MessageFormat class -message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}. -message.format.example2=This is a test message in the message catalog with no args. \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/contextInclude.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/contextInclude.xml deleted file mode 100644 index 5f178d50eb..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/contextInclude.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - yetanotherdummy - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/empty-portlet.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/empty-portlet.xml deleted file mode 100644 index dbfec50abc..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/empty-portlet.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/more-context-messages.properties b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/more-context-messages.properties deleted file mode 100644 index c703c78757..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/more-context-messages.properties +++ /dev/null @@ -1,2 +0,0 @@ -code1=message1x -code3=message3 diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myoverride.properties b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myoverride.properties deleted file mode 100644 index 62b6240c8e..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myoverride.properties +++ /dev/null @@ -1,3 +0,0 @@ -father.name=Albert -rod.age=31 -rod.name=Roderick diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myplaceholder.properties b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myplaceholder.properties deleted file mode 100644 index 707c08dc24..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/myplaceholder.properties +++ /dev/null @@ -1,4 +0,0 @@ -useCodeAsDefaultMessage=false -message-file=context-messages -objectName=test:service=myservice -theme-base=org/springframework/web/portlet/context/WEB-INF/ diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/messageSource.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/messageSource.xml deleted file mode 100644 index 58e00ac37e..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/messageSource.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - ${useCodeAsDefaultMessage} - - - - org/springframework/web/portlet/context/WEB-INF/${message-file} - org/springframework/web/portlet/context/WEB-INF/more-context-messages - - - - - - - - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/themeSource.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/themeSource.xml deleted file mode 100644 index 1e7d04517d..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/resources/themeSource.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - ${theme-base} - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml deleted file mode 100644 index b11c4b291a..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml deleted file mode 100644 index 1169e1f06f..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - org/springframework/web/context/WEB-INF/test-messages - - - - org/springframework/web/context/WEB-INF/test- - - - - - - - - Rod - 31 - - - - - - - Roderick - 31 - - - - - - Kerry - 34 - - - - - typeMismatch - 34x - - - - - - - - false - - - - listenerVeto - 66 - - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/parameterMapping.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/parameterMapping.xml deleted file mode 100644 index 8873f1101b..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/parameterMapping.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeMapping.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeMapping.xml deleted file mode 100644 index 2ca24dbd71..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeMapping.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeParameterMapping.xml b/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeParameterMapping.xml deleted file mode 100644 index b417b0daa4..0000000000 --- a/spring-webmvc-portlet/src/test/resources/org/springframework/web/portlet/handler/portletModeParameterMapping.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java deleted file mode 100644 index f634ac805d..0000000000 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/ViewRendererServlet.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2002-2015 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.servlet; - -import java.io.IOException; -import java.util.Map; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.util.NestedServletException; - -/** - * ViewRendererServlet is a bridge servlet, mainly for the Portlet MVC support. - * - *

        For usage with Portlets, this Servlet is necessary to force the portlet container - * to convert the PortletRequest to a ServletRequest, which it has to do when - * including a resource via the PortletRequestDispatcher. This allows for reuse - * of the entire Servlet-based View support even in a Portlet environment. - * - *

        The actual mapping of the bridge servlet is configurable in the DispatcherPortlet, - * via a "viewRendererUrl" property. The default is "/WEB-INF/servlet/view", which is - * just available for internal resource dispatching. - * - * @author William G. Thompson, Jr. - * @author John A. Lewis - * @author Juergen Hoeller - * @since 2.0 - */ -@SuppressWarnings("serial") -public class ViewRendererServlet extends HttpServlet { - - /** - * Request attribute to hold current web application context. - * Otherwise only the global web app context is obtainable by tags etc. - * @see org.springframework.web.servlet.support.RequestContextUtils#findWebApplicationContext - */ - public static final String WEB_APPLICATION_CONTEXT_ATTRIBUTE = DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE; - - /** Name of request attribute that holds the View object */ - public static final String VIEW_ATTRIBUTE = ViewRendererServlet.class.getName() + ".VIEW"; - - /** Name of request attribute that holds the model Map */ - public static final String MODEL_ATTRIBUTE = ViewRendererServlet.class.getName() + ".MODEL"; - - - @Override - protected final void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - processRequest(request, response); - } - - @Override - protected final void doPost(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - processRequest(request, response); - } - - /** - * Process this request, handling exceptions. - * The actually event handling is performed by the abstract - * {@code renderView()} template method. - * @see #renderView - */ - protected final void processRequest(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - try { - renderView(request, response); - } - catch (ServletException ex) { - throw ex; - } - catch (IOException ex) { - throw ex; - } - catch (Exception ex) { - throw new NestedServletException("View rendering failed", ex); - } - } - - /** - * Retrieve the View instance and model Map to render - * and trigger actual rendering. - * @param request current HTTP request - * @param response current HTTP response - * @throws Exception in case of any kind of processing failure - * @see org.springframework.web.servlet.View#render - */ - @SuppressWarnings("unchecked") - protected void renderView(HttpServletRequest request, HttpServletResponse response) throws Exception { - View view = (View) request.getAttribute(VIEW_ATTRIBUTE); - if (view == null) { - throw new ServletException("Could not complete render request: View is null"); - } - Map model = (Map) request.getAttribute(MODEL_ATTRIBUTE); - view.render(model, request, response); - } - -} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java deleted file mode 100644 index 2a26985c13..0000000000 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.java +++ /dev/null @@ -1,1294 +0,0 @@ -/* - * Copyright 2002-2015 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.servlet.mvc.annotation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.lang.reflect.Method; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.xml.transform.Source; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.BeanExpressionContext; -import org.springframework.beans.factory.config.BeanExpressionResolver; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.core.DefaultParameterNameDiscoverer; -import org.springframework.core.Ordered; -import org.springframework.core.ParameterNameDiscoverer; -import org.springframework.core.annotation.AnnotatedElementUtils; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.ByteArrayHttpMessageConverter; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.xml.SourceHttpMessageConverter; -import org.springframework.http.server.ServerHttpRequest; -import org.springframework.http.server.ServerHttpResponse; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.http.server.ServletServerHttpResponse; -import org.springframework.ui.ExtendedModelMap; -import org.springframework.ui.Model; -import org.springframework.util.AntPathMatcher; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.PathMatcher; -import org.springframework.util.StringUtils; -import org.springframework.validation.support.BindingAwareModelMap; -import org.springframework.web.HttpMediaTypeNotAcceptableException; -import org.springframework.web.HttpRequestMethodNotSupportedException; -import org.springframework.web.HttpSessionRequiredException; -import org.springframework.web.bind.MissingServletRequestParameterException; -import org.springframework.web.bind.ServletRequestDataBinder; -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.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.SessionAttributes; -import org.springframework.web.bind.support.DefaultSessionAttributeStore; -import org.springframework.web.bind.support.SessionAttributeStore; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.bind.support.WebBindingInitializer; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.RequestScope; -import org.springframework.web.context.request.ServletWebRequest; -import org.springframework.web.multipart.MultipartRequest; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.HandlerMapping; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.View; -import org.springframework.web.servlet.support.RequestContextUtils; -import org.springframework.web.servlet.support.WebContentGenerator; -import org.springframework.web.util.UrlPathHelper; -import org.springframework.web.util.WebUtils; - -/** - * Implementation of the {@link org.springframework.web.servlet.HandlerAdapter} interface - * that maps handler methods based on HTTP paths, HTTP methods, and request parameters - * expressed through the {@link RequestMapping} annotation. - * - *

        Supports request parameter binding through the {@link RequestParam} annotation. - * Also supports the {@link ModelAttribute} annotation for exposing model attribute - * values to the view, as well as {@link InitBinder} for binder initialization methods - * and {@link SessionAttributes} for automatic session management of specific attributes. - * - *

        This adapter can be customized through various bean properties. - * A common use case is to apply shared binder initialization logic through - * a custom {@link #setWebBindingInitializer WebBindingInitializer}. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @author Sam Brannen - * @since 2.5 - * @see #setPathMatcher - * @see #setMethodNameResolver - * @see #setWebBindingInitializer - * @see #setSessionAttributeStore - * @deprecated as of Spring 3.2, in favor of - * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter RequestMappingHandlerAdapter} - */ -@Deprecated -public class AnnotationMethodHandlerAdapter extends WebContentGenerator - implements HandlerAdapter, Ordered, BeanFactoryAware { - - /** - * Log category to use when no mapped handler is found for a request. - * @see #pageNotFoundLogger - */ - public static final String PAGE_NOT_FOUND_LOG_CATEGORY = "org.springframework.web.servlet.PageNotFound"; - - /** - * Additional logger to use when no mapped handler is found for a request. - * @see #PAGE_NOT_FOUND_LOG_CATEGORY - */ - protected static final Log pageNotFoundLogger = LogFactory.getLog(PAGE_NOT_FOUND_LOG_CATEGORY); - - - private UrlPathHelper urlPathHelper = new UrlPathHelper(); - - private PathMatcher pathMatcher = new AntPathMatcher(); - - private org.springframework.web.servlet.mvc.multiaction.MethodNameResolver methodNameResolver = - new org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver(); - - private WebBindingInitializer webBindingInitializer; - - private SessionAttributeStore sessionAttributeStore = new DefaultSessionAttributeStore(); - - private int cacheSecondsForSessionAttributeHandlers = 0; - - private boolean synchronizeOnSession = false; - - private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); - - private WebArgumentResolver[] customArgumentResolvers; - - private ModelAndViewResolver[] customModelAndViewResolvers; - - private HttpMessageConverter[] messageConverters; - - private int order = Ordered.LOWEST_PRECEDENCE; - - private ConfigurableBeanFactory beanFactory; - - private BeanExpressionContext expressionContext; - - private final Map, ServletHandlerMethodResolver> methodResolverCache = - new ConcurrentHashMap, ServletHandlerMethodResolver>(64); - - private final Map, Boolean> sessionAnnotatedClassesCache = new ConcurrentHashMap, Boolean>(64); - - - public AnnotationMethodHandlerAdapter() { - // no restriction of HTTP methods by default - super(false); - - // See SPR-7316 - StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); - stringHttpMessageConverter.setWriteAcceptCharset(false); - this.messageConverters = new HttpMessageConverter[] { - new ByteArrayHttpMessageConverter(), stringHttpMessageConverter, - new SourceHttpMessageConverter(), - new org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter() }; - } - - - /** - * Set if URL lookup should always use the full path within the current servlet - * context. Else, the path within the current servlet mapping is used if applicable - * (that is, in the case of a ".../*" servlet mapping in web.xml). - *

        Default is "false". - * @see org.springframework.web.util.UrlPathHelper#setAlwaysUseFullPath - */ - public void setAlwaysUseFullPath(boolean alwaysUseFullPath) { - this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath); - } - - /** - * Set if context path and request URI should be URL-decoded. Both are returned - * undecoded by the Servlet API, in contrast to the servlet path. - *

        Uses either the request encoding or the default encoding according - * to the Servlet spec (ISO-8859-1). - * @see org.springframework.web.util.UrlPathHelper#setUrlDecode - */ - public void setUrlDecode(boolean urlDecode) { - this.urlPathHelper.setUrlDecode(urlDecode); - } - - /** - * Set the UrlPathHelper to use for resolution of lookup paths. - *

        Use this to override the default UrlPathHelper with a custom subclass, - * or to share common UrlPathHelper settings across multiple HandlerMappings and HandlerAdapters. - */ - public void setUrlPathHelper(UrlPathHelper urlPathHelper) { - Assert.notNull(urlPathHelper, "UrlPathHelper must not be null"); - this.urlPathHelper = urlPathHelper; - } - - /** - * Set the PathMatcher implementation to use for matching URL paths against registered URL patterns. - *

        Default is {@link org.springframework.util.AntPathMatcher}. - */ - public void setPathMatcher(PathMatcher pathMatcher) { - Assert.notNull(pathMatcher, "PathMatcher must not be null"); - this.pathMatcher = pathMatcher; - } - - /** - * Set the MethodNameResolver to use for resolving default handler methods - * (carrying an empty {@code @RequestMapping} annotation). - *

        Will only kick in when the handler method cannot be resolved uniquely - * through the annotation metadata already. - */ - public void setMethodNameResolver(org.springframework.web.servlet.mvc.multiaction.MethodNameResolver methodNameResolver) { - this.methodNameResolver = methodNameResolver; - } - - /** - * Specify a WebBindingInitializer which will apply pre-configured - * configuration to every DataBinder that this controller uses. - */ - public void setWebBindingInitializer(WebBindingInitializer webBindingInitializer) { - this.webBindingInitializer = webBindingInitializer; - } - - /** - * Specify the strategy to store session attributes with. - *

        Default is {@link org.springframework.web.bind.support.DefaultSessionAttributeStore}, - * storing session attributes in the HttpSession, using the same attribute name as in the model. - */ - public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore) { - Assert.notNull(sessionAttributeStore, "SessionAttributeStore must not be null"); - this.sessionAttributeStore = sessionAttributeStore; - } - - /** - * Cache content produced by {@code @SessionAttributes} annotated handlers - * for the given number of seconds. Default is 0, preventing caching completely. - *

        In contrast to the "cacheSeconds" property which will apply to all general handlers - * (but not to {@code @SessionAttributes} annotated handlers), this setting will - * apply to {@code @SessionAttributes} annotated handlers only. - * @see #setCacheSeconds - * @see org.springframework.web.bind.annotation.SessionAttributes - */ - public void setCacheSecondsForSessionAttributeHandlers(int cacheSecondsForSessionAttributeHandlers) { - this.cacheSecondsForSessionAttributeHandlers = cacheSecondsForSessionAttributeHandlers; - } - - /** - * Set if controller execution should be synchronized on the session, - * to serialize parallel invocations from the same client. - *

        More specifically, the execution of the {@code handleRequestInternal} - * method will get synchronized if this flag is "true". The best available - * session mutex will be used for the synchronization; ideally, this will - * be a mutex exposed by HttpSessionMutexListener. - *

        The session mutex is guaranteed to be the same object during - * the entire lifetime of the session, available under the key defined - * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a - * safe reference to synchronize on for locking on the current session. - *

        In many cases, the HttpSession reference itself is a safe mutex - * as well, since it will always be the same object reference for the - * same active logical session. However, this is not guaranteed across - * different servlet containers; the only 100% safe way is a session mutex. - * @see org.springframework.web.util.HttpSessionMutexListener - * @see org.springframework.web.util.WebUtils#getSessionMutex(javax.servlet.http.HttpSession) - */ - public void setSynchronizeOnSession(boolean synchronizeOnSession) { - this.synchronizeOnSession = synchronizeOnSession; - } - - /** - * Set the ParameterNameDiscoverer to use for resolving method parameter names if needed - * (e.g. for default attribute names). - *

        Default is a {@link org.springframework.core.DefaultParameterNameDiscoverer}. - */ - public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) { - this.parameterNameDiscoverer = parameterNameDiscoverer; - } - - /** - * Set a custom WebArgumentResolvers to use for special method parameter types. - *

        Such a custom WebArgumentResolver will kick in first, having a chance to resolve - * an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolver(WebArgumentResolver argumentResolver) { - this.customArgumentResolvers = new WebArgumentResolver[] {argumentResolver}; - } - - /** - * Set one or more custom WebArgumentResolvers to use for special method parameter types. - *

        Any such custom WebArgumentResolver will kick in first, having a chance to resolve - * an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolvers(WebArgumentResolver... argumentResolvers) { - this.customArgumentResolvers = argumentResolvers; - } - - /** - * Set a custom ModelAndViewResolvers to use for special method return types. - *

        Such a custom ModelAndViewResolver will kick in first, having a chance to resolve - * a return value before the standard ModelAndView handling kicks in. - */ - public void setCustomModelAndViewResolver(ModelAndViewResolver customModelAndViewResolver) { - this.customModelAndViewResolvers = new ModelAndViewResolver[] {customModelAndViewResolver}; - } - - /** - * Set one or more custom ModelAndViewResolvers to use for special method return types. - *

        Any such custom ModelAndViewResolver will kick in first, having a chance to resolve - * a return value before the standard ModelAndView handling kicks in. - */ - public void setCustomModelAndViewResolvers(ModelAndViewResolver... customModelAndViewResolvers) { - this.customModelAndViewResolvers = customModelAndViewResolvers; - } - - /** - * Set the message body converters to use. - *

        These converters are used to convert from and to HTTP requests and responses. - */ - public void setMessageConverters(HttpMessageConverter[] messageConverters) { - this.messageConverters = messageConverters; - } - - /** - * Return the message body converters that this adapter has been configured with. - */ - public HttpMessageConverter[] getMessageConverters() { - return messageConverters; - } - - /** - * Specify the order value for this HandlerAdapter bean. - *

        Default value is {@code Integer.MAX_VALUE}, meaning that it's non-ordered. - * @see org.springframework.core.Ordered#getOrder() - */ - public void setOrder(int order) { - this.order = order; - } - - @Override - public int getOrder() { - return this.order; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - if (beanFactory instanceof ConfigurableBeanFactory) { - this.beanFactory = (ConfigurableBeanFactory) beanFactory; - this.expressionContext = new BeanExpressionContext(this.beanFactory, new RequestScope()); - } - } - - - @Override - public boolean supports(Object handler) { - return getMethodResolver(handler).hasHandlerMethods(); - } - - @Override - public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - - Class clazz = ClassUtils.getUserClass(handler); - Boolean annotatedWithSessionAttributes = this.sessionAnnotatedClassesCache.get(clazz); - if (annotatedWithSessionAttributes == null) { - annotatedWithSessionAttributes = (AnnotationUtils.findAnnotation(clazz, SessionAttributes.class) != null); - this.sessionAnnotatedClassesCache.put(clazz, annotatedWithSessionAttributes); - } - - if (annotatedWithSessionAttributes) { - checkAndPrepare(request, response, this.cacheSecondsForSessionAttributeHandlers, true); - } - else { - checkAndPrepare(request, response, true); - } - - // Execute invokeHandlerMethod in synchronized block if required. - if (this.synchronizeOnSession) { - HttpSession session = request.getSession(false); - if (session != null) { - Object mutex = WebUtils.getSessionMutex(session); - synchronized (mutex) { - return invokeHandlerMethod(request, response, handler); - } - } - } - - return invokeHandlerMethod(request, response, handler); - } - - protected ModelAndView invokeHandlerMethod(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - - ServletHandlerMethodResolver methodResolver = getMethodResolver(handler); - Method handlerMethod = methodResolver.resolveHandlerMethod(request); - ServletHandlerMethodInvoker methodInvoker = new ServletHandlerMethodInvoker(methodResolver); - ServletWebRequest webRequest = new ServletWebRequest(request, response); - ExtendedModelMap implicitModel = new BindingAwareModelMap(); - - Object result = methodInvoker.invokeHandlerMethod(handlerMethod, handler, webRequest, implicitModel); - ModelAndView mav = - methodInvoker.getModelAndView(handlerMethod, handler.getClass(), result, implicitModel, webRequest); - methodInvoker.updateModelAttributes(handler, (mav != null ? mav.getModel() : null), implicitModel, webRequest); - return mav; - } - - /** - * This method always returns -1 since an annotated controller can have many methods, - * each requiring separate lastModified calculations. Instead, an - * {@link RequestMapping}-annotated method can calculate the lastModified value, call - * {@link org.springframework.web.context.request.WebRequest#checkNotModified(long)} - * to check it, and return {@code null} if that returns {@code true}. - * @see org.springframework.web.context.request.WebRequest#checkNotModified(long) - */ - @Override - public long getLastModified(HttpServletRequest request, Object handler) { - return -1; - } - - - /** - * Build a HandlerMethodResolver for the given handler type. - */ - private ServletHandlerMethodResolver getMethodResolver(Object handler) { - Class handlerClass = ClassUtils.getUserClass(handler); - ServletHandlerMethodResolver resolver = this.methodResolverCache.get(handlerClass); - if (resolver == null) { - synchronized (this.methodResolverCache) { - resolver = this.methodResolverCache.get(handlerClass); - if (resolver == null) { - resolver = new ServletHandlerMethodResolver(handlerClass); - this.methodResolverCache.put(handlerClass, resolver); - } - } - } - return resolver; - } - - - /** - * Template method for creating a new ServletRequestDataBinder instance. - *

        The default implementation creates a standard ServletRequestDataBinder. - * This can be overridden for custom ServletRequestDataBinder subclasses. - * @param request current HTTP request - * @param target the target object to bind onto (or {@code null} - * if the binder is just used to convert a plain parameter value) - * @param objectName the objectName of the target object - * @return the ServletRequestDataBinder instance to use - * @throws Exception in case of invalid state or arguments - * @see ServletRequestDataBinder#bind(javax.servlet.ServletRequest) - * @see ServletRequestDataBinder#convertIfNecessary(Object, Class, org.springframework.core.MethodParameter) - */ - protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object target, String objectName) throws Exception { - return new ServletRequestDataBinder(target, objectName); - } - - /** - * Template method for creating a new HttpInputMessage instance. - *

        The default implementation creates a standard {@link ServletServerHttpRequest}. - * This can be overridden for custom {@code HttpInputMessage} implementations - * @param servletRequest current HTTP request - * @return the HttpInputMessage instance to use - * @throws Exception in case of errors - */ - protected HttpInputMessage createHttpInputMessage(HttpServletRequest servletRequest) throws Exception { - return new ServletServerHttpRequest(servletRequest); - } - - /** - * Template method for creating a new HttpOutputMessage instance. - *

        The default implementation creates a standard {@link ServletServerHttpResponse}. - * This can be overridden for custom {@code HttpOutputMessage} implementations - * @param servletResponse current HTTP response - * @return the HttpInputMessage instance to use - * @throws Exception in case of errors - */ - protected HttpOutputMessage createHttpOutputMessage(HttpServletResponse servletResponse) throws Exception { - return new ServletServerHttpResponse(servletResponse); - } - - - /** - * Servlet-specific subclass of {@code HandlerMethodResolver}. - */ - @SuppressWarnings("deprecation") - private class ServletHandlerMethodResolver extends org.springframework.web.bind.annotation.support.HandlerMethodResolver { - - private final Map mappings = new HashMap(); - - private ServletHandlerMethodResolver(Class handlerType) { - init(handlerType); - } - - @Override - protected boolean isHandlerMethod(Method method) { - if (this.mappings.containsKey(method)) { - return true; - } - RequestMapping mapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); - if (mapping != null) { - String[] patterns = mapping.value(); - RequestMethod[] methods = new RequestMethod[0]; - String[] params = new String[0]; - String[] headers = new String[0]; - if (!hasTypeLevelMapping() || !Arrays.equals(mapping.method(), getTypeLevelMapping().method())) { - methods = mapping.method(); - } - if (!hasTypeLevelMapping() || !Arrays.equals(mapping.params(), getTypeLevelMapping().params())) { - params = mapping.params(); - } - if (!hasTypeLevelMapping() || !Arrays.equals(mapping.headers(), getTypeLevelMapping().headers())) { - headers = mapping.headers(); - } - RequestMappingInfo mappingInfo = new RequestMappingInfo(patterns, methods, params, headers); - this.mappings.put(method, mappingInfo); - return true; - } - return false; - } - - public Method resolveHandlerMethod(HttpServletRequest request) throws ServletException { - String lookupPath = urlPathHelper.getLookupPathForRequest(request); - Comparator pathComparator = pathMatcher.getPatternComparator(lookupPath); - Map targetHandlerMethods = new LinkedHashMap(); - Set allowedMethods = new LinkedHashSet(7); - String resolvedMethodName = null; - for (Method handlerMethod : getHandlerMethods()) { - RequestSpecificMappingInfo mappingInfo = new RequestSpecificMappingInfo(this.mappings.get(handlerMethod)); - boolean match = false; - if (mappingInfo.hasPatterns()) { - for (String pattern : mappingInfo.getPatterns()) { - if (!hasTypeLevelMapping() && !pattern.startsWith("/")) { - pattern = "/" + pattern; - } - String combinedPattern = getCombinedPattern(pattern, lookupPath, request); - if (combinedPattern != null) { - if (mappingInfo.matches(request)) { - match = true; - mappingInfo.addMatchedPattern(combinedPattern); - } - else { - if (!mappingInfo.matchesRequestMethod(request)) { - allowedMethods.addAll(mappingInfo.methodNames()); - } - break; - } - } - } - mappingInfo.sortMatchedPatterns(pathComparator); - } - else if (useTypeLevelMapping(request)) { - String[] typeLevelPatterns = getTypeLevelMapping().value(); - for (String typeLevelPattern : typeLevelPatterns) { - if (!typeLevelPattern.startsWith("/")) { - typeLevelPattern = "/" + typeLevelPattern; - } - boolean useSuffixPattern = useSuffixPattern(request); - if (getMatchingPattern(typeLevelPattern, lookupPath, useSuffixPattern) != null) { - if (mappingInfo.matches(request)) { - match = true; - mappingInfo.addMatchedPattern(typeLevelPattern); - } - else { - if (!mappingInfo.matchesRequestMethod(request)) { - allowedMethods.addAll(mappingInfo.methodNames()); - } - break; - } - } - } - mappingInfo.sortMatchedPatterns(pathComparator); - } - else { - // No paths specified: parameter match sufficient. - match = mappingInfo.matches(request); - if (match && mappingInfo.getMethodCount() == 0 && mappingInfo.getParamCount() == 0 && - resolvedMethodName != null && !resolvedMethodName.equals(handlerMethod.getName())) { - match = false; - } - else { - if (!mappingInfo.matchesRequestMethod(request)) { - allowedMethods.addAll(mappingInfo.methodNames()); - } - } - } - if (match) { - Method oldMappedMethod = targetHandlerMethods.put(mappingInfo, handlerMethod); - if (oldMappedMethod != null && oldMappedMethod != handlerMethod) { - if (methodNameResolver != null && !mappingInfo.hasPatterns()) { - if (!oldMappedMethod.getName().equals(handlerMethod.getName())) { - if (resolvedMethodName == null) { - resolvedMethodName = methodNameResolver.getHandlerMethodName(request); - } - if (!resolvedMethodName.equals(oldMappedMethod.getName())) { - oldMappedMethod = null; - } - if (!resolvedMethodName.equals(handlerMethod.getName())) { - if (oldMappedMethod != null) { - targetHandlerMethods.put(mappingInfo, oldMappedMethod); - oldMappedMethod = null; - } - else { - targetHandlerMethods.remove(mappingInfo); - } - } - } - } - if (oldMappedMethod != null) { - throw new IllegalStateException( - "Ambiguous handler methods mapped for HTTP path '" + lookupPath + "': {" + - oldMappedMethod + ", " + handlerMethod + - "}. If you intend to handle the same path in multiple methods, then factor " + - "them out into a dedicated handler class with that path mapped at the type level!"); - } - } - } - } - if (!targetHandlerMethods.isEmpty()) { - List matches = new ArrayList(targetHandlerMethods.keySet()); - RequestSpecificMappingInfoComparator requestMappingInfoComparator = - new RequestSpecificMappingInfoComparator(pathComparator, request); - Collections.sort(matches, requestMappingInfoComparator); - RequestSpecificMappingInfo bestMappingMatch = matches.get(0); - String bestMatchedPath = bestMappingMatch.bestMatchedPattern(); - if (bestMatchedPath != null) { - extractHandlerMethodUriTemplates(bestMatchedPath, lookupPath, request); - } - return targetHandlerMethods.get(bestMappingMatch); - } - else { - if (!allowedMethods.isEmpty()) { - throw new HttpRequestMethodNotSupportedException(request.getMethod(), StringUtils.toStringArray(allowedMethods)); - } - throw new org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException( - lookupPath, request.getMethod(), request.getParameterMap()); - } - } - - private boolean useTypeLevelMapping(HttpServletRequest request) { - if (!hasTypeLevelMapping() || ObjectUtils.isEmpty(getTypeLevelMapping().value())) { - return false; - } - Object value = request.getAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING); - return (value != null) ? (Boolean) value : Boolean.TRUE; - } - - private boolean useSuffixPattern(HttpServletRequest request) { - Object value = request.getAttribute(DefaultAnnotationHandlerMapping.USE_DEFAULT_SUFFIX_PATTERN); - return (value != null) ? (Boolean) value : Boolean.TRUE; - } - - /** - * Determines the combined pattern for the given methodLevelPattern and path. - *

        Uses the following algorithm: - *

          - *
        1. If there is a type-level mapping with path information, it is {@linkplain - * PathMatcher#combine(String, String) combined} with the method-level pattern.
        2. - *
        3. If there is a {@linkplain HandlerMapping#BEST_MATCHING_PATTERN_ATTRIBUTE best matching pattern} - * in the request, it is combined with the method-level pattern.
        4. - *
        5. Otherwise, the method-level pattern is returned.
        6. - *
        - */ - private String getCombinedPattern(String methodLevelPattern, String lookupPath, HttpServletRequest request) { - boolean useSuffixPattern = useSuffixPattern(request); - if (useTypeLevelMapping(request)) { - String[] typeLevelPatterns = getTypeLevelMapping().value(); - for (String typeLevelPattern : typeLevelPatterns) { - if (!typeLevelPattern.startsWith("/")) { - typeLevelPattern = "/" + typeLevelPattern; - } - String combinedPattern = pathMatcher.combine(typeLevelPattern, methodLevelPattern); - String matchingPattern = getMatchingPattern(combinedPattern, lookupPath, useSuffixPattern); - if (matchingPattern != null) { - return matchingPattern; - } - } - return null; - } - String bestMatchingPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE); - if (StringUtils.hasText(bestMatchingPattern) && bestMatchingPattern.endsWith("*")) { - String combinedPattern = pathMatcher.combine(bestMatchingPattern, methodLevelPattern); - String matchingPattern = getMatchingPattern(combinedPattern, lookupPath, useSuffixPattern); - if (matchingPattern != null && !matchingPattern.equals(bestMatchingPattern)) { - return matchingPattern; - } - } - return getMatchingPattern(methodLevelPattern, lookupPath, useSuffixPattern); - } - - private String getMatchingPattern(String pattern, String lookupPath, boolean useSuffixPattern) { - if (pattern.equals(lookupPath)) { - return pattern; - } - boolean hasSuffix = pattern.indexOf('.') != -1; - if (useSuffixPattern && !hasSuffix) { - String patternWithSuffix = pattern + ".*"; - if (pathMatcher.match(patternWithSuffix, lookupPath)) { - return patternWithSuffix; - } - } - if (pathMatcher.match(pattern, lookupPath)) { - return pattern; - } - boolean endsWithSlash = pattern.endsWith("/"); - if (useSuffixPattern && !endsWithSlash) { - String patternWithSlash = pattern + "/"; - if (pathMatcher.match(patternWithSlash, lookupPath)) { - return patternWithSlash; - } - } - return null; - } - - @SuppressWarnings("unchecked") - private void extractHandlerMethodUriTemplates(String mappedPattern, String lookupPath, HttpServletRequest request) { - Map variables = - (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); - int patternVariableCount = StringUtils.countOccurrencesOf(mappedPattern, "{"); - if ((variables == null || patternVariableCount != variables.size()) && pathMatcher.match(mappedPattern, lookupPath)) { - variables = pathMatcher.extractUriTemplateVariables(mappedPattern, lookupPath); - Map decodedVariables = urlPathHelper.decodePathVariables(request, variables); - request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedVariables); - } - } - } - - - /** - * Servlet-specific subclass of {@code HandlerMethodInvoker}. - */ - @SuppressWarnings("deprecation") - private class ServletHandlerMethodInvoker extends org.springframework.web.bind.annotation.support.HandlerMethodInvoker { - - private boolean responseArgumentUsed = false; - - private ServletHandlerMethodInvoker(org.springframework.web.bind.annotation.support.HandlerMethodResolver resolver) { - super(resolver, webBindingInitializer, sessionAttributeStore, parameterNameDiscoverer, - customArgumentResolvers, messageConverters); - } - - @Override - protected void raiseMissingParameterException(String paramName, Class paramType) throws Exception { - throw new MissingServletRequestParameterException(paramName, paramType.getSimpleName()); - } - - @Override - protected void raiseSessionRequiredException(String message) throws Exception { - throw new HttpSessionRequiredException(message); - } - - @Override - protected WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) - throws Exception { - - return AnnotationMethodHandlerAdapter.this.createBinder( - webRequest.getNativeRequest(HttpServletRequest.class), target, objectName); - } - - @Override - protected void doBind(WebDataBinder binder, NativeWebRequest webRequest) throws Exception { - ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder; - servletBinder.bind(webRequest.getNativeRequest(ServletRequest.class)); - } - - @Override - protected HttpInputMessage createHttpInputMessage(NativeWebRequest webRequest) throws Exception { - HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); - return AnnotationMethodHandlerAdapter.this.createHttpInputMessage(servletRequest); - } - - @Override - protected HttpOutputMessage createHttpOutputMessage(NativeWebRequest webRequest) throws Exception { - HttpServletResponse servletResponse = (HttpServletResponse) webRequest.getNativeResponse(); - return AnnotationMethodHandlerAdapter.this.createHttpOutputMessage(servletResponse); - } - - @Override - protected Object resolveDefaultValue(String value) { - if (beanFactory == null) { - return value; - } - String placeholdersResolved = beanFactory.resolveEmbeddedValue(value); - BeanExpressionResolver exprResolver = beanFactory.getBeanExpressionResolver(); - if (exprResolver == null) { - return value; - } - return exprResolver.evaluate(placeholdersResolved, expressionContext); - } - - @Override - protected Object resolveCookieValue(String cookieName, Class paramType, NativeWebRequest webRequest) - throws Exception { - - HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); - Cookie cookieValue = WebUtils.getCookie(servletRequest, cookieName); - if (Cookie.class.isAssignableFrom(paramType)) { - return cookieValue; - } - else if (cookieValue != null) { - return urlPathHelper.decodeRequestString(servletRequest, cookieValue.getValue()); - } - else { - return null; - } - } - - @Override - @SuppressWarnings({"unchecked"}) - protected String resolvePathVariable(String pathVarName, Class paramType, NativeWebRequest webRequest) - throws Exception { - - HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class); - Map uriTemplateVariables = - (Map) servletRequest.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); - if (uriTemplateVariables == null || !uriTemplateVariables.containsKey(pathVarName)) { - throw new IllegalStateException( - "Could not find @PathVariable [" + pathVarName + "] in @RequestMapping"); - } - return uriTemplateVariables.get(pathVarName); - } - - @Override - protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest) throws Exception { - HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); - HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); - - if (ServletRequest.class.isAssignableFrom(parameterType) || - MultipartRequest.class.isAssignableFrom(parameterType)) { - Object nativeRequest = webRequest.getNativeRequest(parameterType); - if (nativeRequest == null) { - throw new IllegalStateException( - "Current request is not of type [" + parameterType.getName() + "]: " + request); - } - return nativeRequest; - } - else if (ServletResponse.class.isAssignableFrom(parameterType)) { - this.responseArgumentUsed = true; - Object nativeResponse = webRequest.getNativeResponse(parameterType); - if (nativeResponse == null) { - throw new IllegalStateException( - "Current response is not of type [" + parameterType.getName() + "]: " + response); - } - return nativeResponse; - } - else if (HttpSession.class.isAssignableFrom(parameterType)) { - return request.getSession(); - } - else if (Principal.class.isAssignableFrom(parameterType)) { - return request.getUserPrincipal(); - } - else if (Locale.class == parameterType) { - return RequestContextUtils.getLocale(request); - } - else if (InputStream.class.isAssignableFrom(parameterType)) { - return request.getInputStream(); - } - else if (Reader.class.isAssignableFrom(parameterType)) { - return request.getReader(); - } - else if (OutputStream.class.isAssignableFrom(parameterType)) { - this.responseArgumentUsed = true; - return response.getOutputStream(); - } - else if (Writer.class.isAssignableFrom(parameterType)) { - this.responseArgumentUsed = true; - return response.getWriter(); - } - return super.resolveStandardArgument(parameterType, webRequest); - } - - @SuppressWarnings("unchecked") - public ModelAndView getModelAndView(Method handlerMethod, Class handlerType, Object returnValue, - ExtendedModelMap implicitModel, ServletWebRequest webRequest) throws Exception { - - ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(handlerMethod, ResponseStatus.class); - if (responseStatus != null) { - HttpStatus statusCode = responseStatus.code(); - String reason = responseStatus.reason(); - if (!StringUtils.hasText(reason)) { - webRequest.getResponse().setStatus(statusCode.value()); - } - else { - webRequest.getResponse().sendError(statusCode.value(), reason); - } - - // to be picked up by the RedirectView - webRequest.getRequest().setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, statusCode); - - this.responseArgumentUsed = true; - } - - // Invoke custom resolvers if present... - if (customModelAndViewResolvers != null) { - for (ModelAndViewResolver mavResolver : customModelAndViewResolvers) { - ModelAndView mav = mavResolver.resolveModelAndView( - handlerMethod, handlerType, returnValue, implicitModel, webRequest); - if (mav != ModelAndViewResolver.UNRESOLVED) { - return mav; - } - } - } - - if (returnValue instanceof HttpEntity) { - handleHttpEntityResponse((HttpEntity) returnValue, webRequest); - return null; - } - else if (AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) != null) { - handleResponseBody(returnValue, webRequest); - return null; - } - else if (returnValue instanceof ModelAndView) { - ModelAndView mav = (ModelAndView) returnValue; - mav.getModelMap().mergeAttributes(implicitModel); - return mav; - } - else if (returnValue instanceof Model) { - return new ModelAndView().addAllObjects(implicitModel).addAllObjects(((Model) returnValue).asMap()); - } - else if (returnValue instanceof View) { - return new ModelAndView((View) returnValue).addAllObjects(implicitModel); - } - else if (AnnotationUtils.findAnnotation(handlerMethod, ModelAttribute.class) != null) { - addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel); - return new ModelAndView().addAllObjects(implicitModel); - } - else if (returnValue instanceof Map) { - return new ModelAndView().addAllObjects(implicitModel).addAllObjects((Map) returnValue); - } - else if (returnValue instanceof String) { - return new ModelAndView((String) returnValue).addAllObjects(implicitModel); - } - else if (returnValue == null) { - // Either returned null or was 'void' return. - if (this.responseArgumentUsed || webRequest.isNotModified()) { - return null; - } - else { - // Assuming view name translation... - return new ModelAndView().addAllObjects(implicitModel); - } - } - else if (!BeanUtils.isSimpleProperty(returnValue.getClass())) { - // Assume a single model attribute... - addReturnValueAsModelAttribute(handlerMethod, handlerType, returnValue, implicitModel); - return new ModelAndView().addAllObjects(implicitModel); - } - else { - throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); - } - } - - private void handleResponseBody(Object returnValue, ServletWebRequest webRequest) throws Exception { - if (returnValue == null) { - return; - } - HttpInputMessage inputMessage = createHttpInputMessage(webRequest); - HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest); - writeWithMessageConverters(returnValue, inputMessage, outputMessage); - } - - private void handleHttpEntityResponse(HttpEntity responseEntity, ServletWebRequest webRequest) throws Exception { - if (responseEntity == null) { - return; - } - HttpInputMessage inputMessage = createHttpInputMessage(webRequest); - HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest); - if (responseEntity instanceof ResponseEntity && outputMessage instanceof ServerHttpResponse) { - ((ServerHttpResponse) outputMessage).setStatusCode(((ResponseEntity) responseEntity).getStatusCode()); - } - HttpHeaders entityHeaders = responseEntity.getHeaders(); - if (!entityHeaders.isEmpty()) { - outputMessage.getHeaders().putAll(entityHeaders); - } - Object body = responseEntity.getBody(); - if (body != null) { - writeWithMessageConverters(body, inputMessage, outputMessage); - } - else { - // flush headers - outputMessage.getBody(); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - private void writeWithMessageConverters(Object returnValue, - HttpInputMessage inputMessage, HttpOutputMessage outputMessage) - throws IOException, HttpMediaTypeNotAcceptableException { - - List acceptedMediaTypes = inputMessage.getHeaders().getAccept(); - if (acceptedMediaTypes.isEmpty()) { - acceptedMediaTypes = Collections.singletonList(MediaType.ALL); - } - MediaType.sortByQualityValue(acceptedMediaTypes); - Class returnValueType = returnValue.getClass(); - List allSupportedMediaTypes = new ArrayList(); - if (getMessageConverters() != null) { - for (MediaType acceptedMediaType : acceptedMediaTypes) { - for (HttpMessageConverter messageConverter : getMessageConverters()) { - if (messageConverter.canWrite(returnValueType, acceptedMediaType)) { - messageConverter.write(returnValue, acceptedMediaType, outputMessage); - if (logger.isDebugEnabled()) { - MediaType contentType = outputMessage.getHeaders().getContentType(); - if (contentType == null) { - contentType = acceptedMediaType; - } - logger.debug("Written [" + returnValue + "] as \"" + contentType + - "\" using [" + messageConverter + "]"); - } - this.responseArgumentUsed = true; - return; - } - } - } - for (HttpMessageConverter messageConverter : messageConverters) { - allSupportedMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); - } - } - throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes); - } - } - - - /** - * Holder for request mapping metadata. - */ - static class RequestMappingInfo { - - private final String[] patterns; - - private final RequestMethod[] methods; - - private final String[] params; - - private final String[] headers; - - RequestMappingInfo(String[] patterns, RequestMethod[] methods, String[] params, String[] headers) { - this.patterns = (patterns != null ? patterns : new String[0]); - this.methods = (methods != null ? methods : new RequestMethod[0]); - this.params = (params != null ? params : new String[0]); - this.headers = (headers != null ? headers : new String[0]); - } - - public boolean hasPatterns() { - return (this.patterns.length > 0); - } - - public String[] getPatterns() { - return this.patterns; - } - - public int getMethodCount() { - return this.methods.length; - } - - public int getParamCount() { - return this.params.length; - } - - public int getHeaderCount() { - return this.headers.length; - } - - public boolean matches(HttpServletRequest request) { - return matchesRequestMethod(request) && matchesParameters(request) && matchesHeaders(request); - } - - public boolean matchesHeaders(HttpServletRequest request) { - return ServletAnnotationMappingUtils.checkHeaders(this.headers, request); - } - - public boolean matchesParameters(HttpServletRequest request) { - return ServletAnnotationMappingUtils.checkParameters(this.params, request); - } - - public boolean matchesRequestMethod(HttpServletRequest request) { - return ServletAnnotationMappingUtils.checkRequestMethod(this.methods, request); - } - - public Set methodNames() { - Set methodNames = new LinkedHashSet(this.methods.length); - for (RequestMethod method : this.methods) { - methodNames.add(method.name()); - } - return methodNames; - } - - @Override - public boolean equals(Object obj) { - RequestMappingInfo other = (RequestMappingInfo) obj; - return (Arrays.equals(this.patterns, other.patterns) && Arrays.equals(this.methods, other.methods) && - Arrays.equals(this.params, other.params) && Arrays.equals(this.headers, other.headers)); - } - - @Override - public int hashCode() { - return (Arrays.hashCode(this.patterns) * 23 + Arrays.hashCode(this.methods) * 29 + - Arrays.hashCode(this.params) * 31 + Arrays.hashCode(this.headers)); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append(Arrays.asList(this.patterns)); - if (this.methods.length > 0) { - builder.append(','); - builder.append(Arrays.asList(this.methods)); - } - if (this.headers.length > 0) { - builder.append(','); - builder.append(Arrays.asList(this.headers)); - } - if (this.params.length > 0) { - builder.append(','); - builder.append(Arrays.asList(this.params)); - } - return builder.toString(); - } - } - - - /** - * Subclass of {@link RequestMappingInfo} that holds request-specific data. - */ - static class RequestSpecificMappingInfo extends RequestMappingInfo { - - private final List matchedPatterns = new ArrayList(); - - RequestSpecificMappingInfo(String[] patterns, RequestMethod[] methods, String[] params, String[] headers) { - super(patterns, methods, params, headers); - } - - RequestSpecificMappingInfo(RequestMappingInfo other) { - super(other.patterns, other.methods, other.params, other.headers); - } - - public void addMatchedPattern(String matchedPattern) { - matchedPatterns.add(matchedPattern); - } - - public void sortMatchedPatterns(Comparator pathComparator) { - Collections.sort(matchedPatterns, pathComparator); - } - - public String bestMatchedPattern() { - return (!this.matchedPatterns.isEmpty() ? this.matchedPatterns.get(0) : null); - } - } - - - /** - * Comparator capable of sorting {@link RequestSpecificMappingInfo}s (RHIs) so that - * sorting a list with this comparator will result in: - *
          - *
        • RHIs with {@linkplain AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo#matchedPatterns better matched paths} - * take precedence over those with a weaker match (as expressed by the {@linkplain PathMatcher#getPatternComparator(String) - * path pattern comparator}.) Typically, this means that patterns without wild cards and uri templates - * will be ordered before those without.
        • - *
        • RHIs with one single {@linkplain RequestMappingInfo#methods request method} will be - * ordered before those without a method, or with more than one method.
        • - *
        • RHIs with more {@linkplain RequestMappingInfo#params request parameters} will be ordered - * before those with less parameters
        • - * - */ - static class RequestSpecificMappingInfoComparator implements Comparator { - - private final Comparator pathComparator; - - private final ServerHttpRequest request; - - RequestSpecificMappingInfoComparator(Comparator pathComparator, HttpServletRequest request) { - this.pathComparator = pathComparator; - this.request = new ServletServerHttpRequest(request); - } - - @Override - public int compare(RequestSpecificMappingInfo info1, RequestSpecificMappingInfo info2) { - int pathComparison = pathComparator.compare(info1.bestMatchedPattern(), info2.bestMatchedPattern()); - if (pathComparison != 0) { - return pathComparison; - } - int info1ParamCount = info1.getParamCount(); - int info2ParamCount = info2.getParamCount(); - if (info1ParamCount != info2ParamCount) { - return info2ParamCount - info1ParamCount; - } - int info1HeaderCount = info1.getHeaderCount(); - int info2HeaderCount = info2.getHeaderCount(); - if (info1HeaderCount != info2HeaderCount) { - return info2HeaderCount - info1HeaderCount; - } - int acceptComparison = compareAcceptHeaders(info1, info2); - if (acceptComparison != 0) { - return acceptComparison; - } - int info1MethodCount = info1.getMethodCount(); - int info2MethodCount = info2.getMethodCount(); - if (info1MethodCount == 0 && info2MethodCount > 0) { - return 1; - } - else if (info2MethodCount == 0 && info1MethodCount > 0) { - return -1; - } - else if (info1MethodCount == 1 & info2MethodCount > 1) { - return -1; - } - else if (info2MethodCount == 1 & info1MethodCount > 1) { - return 1; - } - return 0; - } - - private int compareAcceptHeaders(RequestMappingInfo info1, RequestMappingInfo info2) { - List requestAccepts = request.getHeaders().getAccept(); - MediaType.sortByQualityValue(requestAccepts); - - List info1Accepts = getAcceptHeaderValue(info1); - List info2Accepts = getAcceptHeaderValue(info2); - - for (MediaType requestAccept : requestAccepts) { - int pos1 = indexOfIncluded(info1Accepts, requestAccept); - int pos2 = indexOfIncluded(info2Accepts, requestAccept); - if (pos1 != pos2) { - return pos2 - pos1; - } - } - return 0; - } - - private int indexOfIncluded(List infoAccepts, MediaType requestAccept) { - for (int i = 0; i < infoAccepts.size(); i++) { - MediaType info1Accept = infoAccepts.get(i); - if (requestAccept.includes(info1Accept)) { - return i; - } - } - return -1; - } - - private List getAcceptHeaderValue(RequestMappingInfo info) { - for (String header : info.headers) { - int separator = header.indexOf('='); - if (separator != -1) { - String key = header.substring(0, separator); - String value = header.substring(separator + 1); - if ("Accept".equalsIgnoreCase(key)) { - return MediaType.parseMediaTypes(value); - } - } - } - return Collections.emptyList(); - } - } - -} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java deleted file mode 100644 index 70a5970213..0000000000 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolver.java +++ /dev/null @@ -1,452 +0,0 @@ -/* - * Copyright 2002-2015 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.servlet.mvc.annotation; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.Writer; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.security.Principal; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.xml.transform.Source; - -import org.springframework.core.ExceptionDepthComparator; -import org.springframework.core.GenericTypeResolver; -import org.springframework.core.MethodParameter; -import org.springframework.core.annotation.AnnotatedElementUtils; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.annotation.SynthesizingMethodParameter; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.converter.ByteArrayHttpMessageConverter; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.xml.SourceHttpMessageConverter; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.http.server.ServletServerHttpResponse; -import org.springframework.ui.Model; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.ServletWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.View; -import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; -import org.springframework.web.servlet.support.RequestContextUtils; - -/** - * Implementation of the {@link org.springframework.web.servlet.HandlerExceptionResolver} interface that handles - * exceptions through the {@link ExceptionHandler} annotation. - * - *

          This exception resolver is enabled by default in the {@link org.springframework.web.servlet.DispatcherServlet}. - * - * @author Arjen Poutsma - * @author Juergen Hoeller - * @since 3.0 - * @deprecated as of Spring 3.2, in favor of - * {@link org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver ExceptionHandlerExceptionResolver} - */ -@Deprecated -public class AnnotationMethodHandlerExceptionResolver extends AbstractHandlerExceptionResolver { - - /** - * Arbitrary {@link Method} reference, indicating no method found in the cache. - */ - private static final Method NO_METHOD_FOUND = ClassUtils.getMethodIfAvailable(System.class, "currentTimeMillis"); - - - private final Map, Map, Method>> exceptionHandlerCache = - new ConcurrentHashMap, Map, Method>>(64); - - private WebArgumentResolver[] customArgumentResolvers; - - private HttpMessageConverter[] messageConverters = - new HttpMessageConverter[] {new ByteArrayHttpMessageConverter(), new StringHttpMessageConverter(), - new SourceHttpMessageConverter(), - new org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter()}; - - - /** - * Set a custom ArgumentResolvers to use for special method parameter types. - *

          Such a custom ArgumentResolver will kick in first, having a chance to resolve - * an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolver(WebArgumentResolver argumentResolver) { - this.customArgumentResolvers = new WebArgumentResolver[]{argumentResolver}; - } - - /** - * Set one or more custom ArgumentResolvers to use for special method parameter types. - *

          Any such custom ArgumentResolver will kick in first, having a chance to resolve - * an argument value before the standard argument handling kicks in. - */ - public void setCustomArgumentResolvers(WebArgumentResolver[] argumentResolvers) { - this.customArgumentResolvers = argumentResolvers; - } - - /** - * Set the message body converters to use. - *

          These converters are used to convert from and to HTTP requests and responses. - */ - public void setMessageConverters(HttpMessageConverter[] messageConverters) { - this.messageConverters = messageConverters; - } - - - @Override - protected ModelAndView doResolveException( - HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { - - if (handler != null) { - Method handlerMethod = findBestExceptionHandlerMethod(handler, ex); - if (handlerMethod != null) { - ServletWebRequest webRequest = new ServletWebRequest(request, response); - try { - Object[] args = resolveHandlerArguments(handlerMethod, handler, webRequest, ex); - if (logger.isDebugEnabled()) { - logger.debug("Invoking request handler method: " + handlerMethod); - } - Object retVal = doInvokeMethod(handlerMethod, handler, args); - return getModelAndView(handlerMethod, retVal, webRequest); - } - catch (Exception invocationEx) { - logger.error("Invoking request method resulted in exception : " + handlerMethod, invocationEx); - } - } - } - return null; - } - - /** - * Finds the handler method that matches the thrown exception best. - * @param handler the handler object - * @param thrownException the exception to be handled - * @return the best matching method; or {@code null} if none is found - */ - private Method findBestExceptionHandlerMethod(Object handler, final Exception thrownException) { - final Class handlerType = ClassUtils.getUserClass(handler); - final Class thrownExceptionType = thrownException.getClass(); - Method handlerMethod = null; - - Map, Method> handlers = this.exceptionHandlerCache.get(handlerType); - if (handlers != null) { - handlerMethod = handlers.get(thrownExceptionType); - if (handlerMethod != null) { - return (handlerMethod == NO_METHOD_FOUND ? null : handlerMethod); - } - } - else { - handlers = new ConcurrentHashMap, Method>(16); - this.exceptionHandlerCache.put(handlerType, handlers); - } - - final Map, Method> matchedHandlers = new HashMap, Method>(); - - ReflectionUtils.doWithMethods(handlerType, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) { - method = ClassUtils.getMostSpecificMethod(method, handlerType); - List> handledExceptions = getHandledExceptions(method); - for (Class handledException : handledExceptions) { - if (handledException.isAssignableFrom(thrownExceptionType)) { - if (!matchedHandlers.containsKey(handledException)) { - matchedHandlers.put(handledException, method); - } - else { - Method oldMappedMethod = matchedHandlers.get(handledException); - if (!oldMappedMethod.equals(method)) { - throw new IllegalStateException( - "Ambiguous exception handler mapped for " + handledException + "]: {" + - oldMappedMethod + ", " + method + "}."); - } - } - } - } - } - }); - - handlerMethod = getBestMatchingMethod(matchedHandlers, thrownException); - handlers.put(thrownExceptionType, (handlerMethod == null ? NO_METHOD_FOUND : handlerMethod)); - return handlerMethod; - } - - /** - * Returns all the exception classes handled by the given method. - *

          The default implementation looks for exceptions in the annotation, - * or - if that annotation element is empty - any exceptions listed in the method parameters if the method - * is annotated with {@code @ExceptionHandler}. - * @param method the method - * @return the handled exceptions - */ - @SuppressWarnings("unchecked") - protected List> getHandledExceptions(Method method) { - List> result = new ArrayList>(); - ExceptionHandler exceptionHandler = AnnotationUtils.findAnnotation(method, ExceptionHandler.class); - if (exceptionHandler != null) { - if (!ObjectUtils.isEmpty(exceptionHandler.value())) { - result.addAll(Arrays.asList(exceptionHandler.value())); - } - else { - for (Class param : method.getParameterTypes()) { - if (Throwable.class.isAssignableFrom(param)) { - result.add((Class) param); - } - } - } - } - return result; - } - - /** - * Uses the {@link ExceptionDepthComparator} to find the best matching method. - * @return the best matching method, or {@code null} if none found - */ - private Method getBestMatchingMethod( - Map, Method> resolverMethods, Exception thrownException) { - - if (resolverMethods.isEmpty()) { - return null; - } - Class closestMatch = - ExceptionDepthComparator.findClosestMatch(resolverMethods.keySet(), thrownException); - Method method = resolverMethods.get(closestMatch); - return ((method == null) || (NO_METHOD_FOUND == method)) ? null : method; - } - - /** - * Resolves the arguments for the given method. Delegates to {@link #resolveCommonArgument}. - */ - private Object[] resolveHandlerArguments(Method handlerMethod, Object handler, - NativeWebRequest webRequest, Exception thrownException) throws Exception { - - Class[] paramTypes = handlerMethod.getParameterTypes(); - Object[] args = new Object[paramTypes.length]; - Class handlerType = handler.getClass(); - for (int i = 0; i < args.length; i++) { - MethodParameter methodParam = new SynthesizingMethodParameter(handlerMethod, i); - GenericTypeResolver.resolveParameterType(methodParam, handlerType); - Class paramType = methodParam.getParameterType(); - Object argValue = resolveCommonArgument(methodParam, webRequest, thrownException); - if (argValue != WebArgumentResolver.UNRESOLVED) { - args[i] = argValue; - } - else { - throw new IllegalStateException("Unsupported argument [" + paramType.getName() + - "] for @ExceptionHandler method: " + handlerMethod); - } - } - return args; - } - - /** - * Resolves common method arguments. Delegates to registered {@link #setCustomArgumentResolver(WebArgumentResolver) - * argumentResolvers} first, then checking {@link #resolveStandardArgument}. - * @param methodParameter the method parameter - * @param webRequest the request - * @param thrownException the exception thrown - * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED} - */ - protected Object resolveCommonArgument(MethodParameter methodParameter, NativeWebRequest webRequest, - Exception thrownException) throws Exception { - - // Invoke custom argument resolvers if present... - if (this.customArgumentResolvers != null) { - for (WebArgumentResolver argumentResolver : this.customArgumentResolvers) { - Object value = argumentResolver.resolveArgument(methodParameter, webRequest); - if (value != WebArgumentResolver.UNRESOLVED) { - return value; - } - } - } - - // Resolution of standard parameter types... - Class paramType = methodParameter.getParameterType(); - Object value = resolveStandardArgument(paramType, webRequest, thrownException); - if (value != WebArgumentResolver.UNRESOLVED && !ClassUtils.isAssignableValue(paramType, value)) { - throw new IllegalStateException( - "Standard argument type [" + paramType.getName() + "] resolved to incompatible value of type [" + - (value != null ? value.getClass() : null) + - "]. Consider declaring the argument type in a less specific fashion."); - } - return value; - } - - /** - * Resolves standard method arguments. The default implementation handles {@link NativeWebRequest}, - * {@link ServletRequest}, {@link ServletResponse}, {@link HttpSession}, {@link Principal}, - * {@link Locale}, request {@link InputStream}, request {@link Reader}, response {@link OutputStream}, - * response {@link Writer}, and the given {@code thrownException}. - * @param parameterType the method parameter type - * @param webRequest the request - * @param thrownException the exception thrown - * @return the argument value, or {@link WebArgumentResolver#UNRESOLVED} - */ - protected Object resolveStandardArgument(Class parameterType, NativeWebRequest webRequest, - Exception thrownException) throws Exception { - - if (parameterType.isInstance(thrownException)) { - return thrownException; - } - else if (WebRequest.class.isAssignableFrom(parameterType)) { - return webRequest; - } - - HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); - HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class); - - if (ServletRequest.class.isAssignableFrom(parameterType)) { - return request; - } - else if (ServletResponse.class.isAssignableFrom(parameterType)) { - return response; - } - else if (HttpSession.class.isAssignableFrom(parameterType)) { - return request.getSession(); - } - else if (Principal.class.isAssignableFrom(parameterType)) { - return request.getUserPrincipal(); - } - else if (Locale.class == parameterType) { - return RequestContextUtils.getLocale(request); - } - else if (InputStream.class.isAssignableFrom(parameterType)) { - return request.getInputStream(); - } - else if (Reader.class.isAssignableFrom(parameterType)) { - return request.getReader(); - } - else if (OutputStream.class.isAssignableFrom(parameterType)) { - return response.getOutputStream(); - } - else if (Writer.class.isAssignableFrom(parameterType)) { - return response.getWriter(); - } - else { - return WebArgumentResolver.UNRESOLVED; - - } - } - - private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception { - ReflectionUtils.makeAccessible(method); - try { - return method.invoke(target, args); - } - catch (InvocationTargetException ex) { - ReflectionUtils.rethrowException(ex.getTargetException()); - } - throw new IllegalStateException("Should never get here"); - } - - @SuppressWarnings("unchecked") - private ModelAndView getModelAndView(Method handlerMethod, Object returnValue, ServletWebRequest webRequest) - throws Exception { - - ResponseStatus responseStatus = AnnotatedElementUtils.findMergedAnnotation(handlerMethod, ResponseStatus.class); - if (responseStatus != null) { - HttpStatus statusCode = responseStatus.code(); - String reason = responseStatus.reason(); - if (!StringUtils.hasText(reason)) { - webRequest.getResponse().setStatus(statusCode.value()); - } - else { - webRequest.getResponse().sendError(statusCode.value(), reason); - } - } - - if (returnValue != null && AnnotationUtils.findAnnotation(handlerMethod, ResponseBody.class) != null) { - return handleResponseBody(returnValue, webRequest); - } - - if (returnValue instanceof ModelAndView) { - return (ModelAndView) returnValue; - } - else if (returnValue instanceof Model) { - return new ModelAndView().addAllObjects(((Model) returnValue).asMap()); - } - else if (returnValue instanceof Map) { - return new ModelAndView().addAllObjects((Map) returnValue); - } - else if (returnValue instanceof View) { - return new ModelAndView((View) returnValue); - } - else if (returnValue instanceof String) { - return new ModelAndView((String) returnValue); - } - else if (returnValue == null) { - return new ModelAndView(); - } - else { - throw new IllegalArgumentException("Invalid handler method return value: " + returnValue); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes", "resource" }) - private ModelAndView handleResponseBody(Object returnValue, ServletWebRequest webRequest) - throws ServletException, IOException { - - HttpInputMessage inputMessage = new ServletServerHttpRequest(webRequest.getRequest()); - List acceptedMediaTypes = inputMessage.getHeaders().getAccept(); - if (acceptedMediaTypes.isEmpty()) { - acceptedMediaTypes = Collections.singletonList(MediaType.ALL); - } - MediaType.sortByQualityValue(acceptedMediaTypes); - HttpOutputMessage outputMessage = new ServletServerHttpResponse(webRequest.getResponse()); - Class returnValueType = returnValue.getClass(); - if (this.messageConverters != null) { - for (MediaType acceptedMediaType : acceptedMediaTypes) { - for (HttpMessageConverter messageConverter : this.messageConverters) { - if (messageConverter.canWrite(returnValueType, acceptedMediaType)) { - messageConverter.write(returnValue, acceptedMediaType, outputMessage); - return new ModelAndView(); - } - } - } - } - if (logger.isWarnEnabled()) { - logger.warn("Could not find HttpMessageConverter that supports return type [" + returnValueType + "] and " + - acceptedMediaTypes); - } - return null; - } - -} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java deleted file mode 100644 index a1275c9c68..0000000000 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright 2002-2015 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.servlet.mvc.annotation; - -import java.lang.reflect.Method; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.context.ApplicationContext; -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.HttpRequestMethodNotSupportedException; -import org.springframework.web.bind.ServletRequestBindingException; -import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.servlet.handler.AbstractDetectingUrlHandlerMapping; - -/** - * Implementation of the {@link org.springframework.web.servlet.HandlerMapping} - * interface that maps handlers based on HTTP paths expressed through the - * {@link RequestMapping} annotation at the type or method level. - * - *

          Registered by default in {@link org.springframework.web.servlet.DispatcherServlet} - * on Java 5+. NOTE: If you define custom HandlerMapping beans in your - * DispatcherServlet context, you need to add a DefaultAnnotationHandlerMapping bean - * explicitly, since custom HandlerMapping beans replace the default mapping strategies. - * Defining a DefaultAnnotationHandlerMapping also allows for registering custom - * interceptors: - * - *

          - * <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
          - *   <property name="interceptors">
          - *     ...
          - *   </property>
          - * </bean>
          - * - * Annotated controllers are usually marked with the {@link Controller} stereotype - * at the type level. This is not strictly necessary when {@link RequestMapping} is - * applied at the type level (since such a handler usually implements the - * {@link org.springframework.web.servlet.mvc.Controller} interface). However, - * {@link Controller} is required for detecting {@link RequestMapping} annotations - * at the method level if {@link RequestMapping} is not present at the type level. - * - *

          NOTE: Method-level mappings are only allowed to narrow the mapping - * expressed at the class level (if any). HTTP paths need to uniquely map onto - * specific handler beans, with any given HTTP path only allowed to be mapped - * onto one specific handler bean (not spread across multiple handler beans). - * It is strongly recommended to co-locate related handler methods into the same bean. - * - *

          The {@link AnnotationMethodHandlerAdapter} is responsible for processing - * annotated handler methods, as mapped by this HandlerMapping. For - * {@link RequestMapping} at the type level, specific HandlerAdapters such as - * {@link org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter} apply. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @since 2.5 - * @see RequestMapping - * @see AnnotationMethodHandlerAdapter - * @deprecated as of Spring 3.2, in favor of - * {@link org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping RequestMappingHandlerMapping} - */ -@Deprecated -public class DefaultAnnotationHandlerMapping extends AbstractDetectingUrlHandlerMapping { - - static final String USE_DEFAULT_SUFFIX_PATTERN = DefaultAnnotationHandlerMapping.class.getName() + ".useDefaultSuffixPattern"; - - private boolean useDefaultSuffixPattern = true; - - private final Map, RequestMapping> cachedMappings = new HashMap, RequestMapping>(); - - - /** - * Set whether to register paths using the default suffix pattern as well: - * i.e. whether "/users" should be registered as "/users.*" and "/users/" too. - *

          Default is "true". Turn this convention off if you intend to interpret - * your {@code @RequestMapping} paths strictly. - *

          Note that paths which include a ".xxx" suffix or end with "/" already will not be - * transformed using the default suffix pattern in any case. - */ - public void setUseDefaultSuffixPattern(boolean useDefaultSuffixPattern) { - this.useDefaultSuffixPattern = useDefaultSuffixPattern; - } - - - /** - * Checks for presence of the {@link org.springframework.web.bind.annotation.RequestMapping} - * annotation on the handler class and on any of its methods. - */ - @Override - protected String[] determineUrlsForHandler(String beanName) { - ApplicationContext context = getApplicationContext(); - Class handlerType = context.getType(beanName); - RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class); - if (mapping != null) { - // @RequestMapping found at type level - this.cachedMappings.put(handlerType, mapping); - Set urls = new LinkedHashSet(); - String[] typeLevelPatterns = mapping.value(); - if (typeLevelPatterns.length > 0) { - // @RequestMapping specifies paths at type level - String[] methodLevelPatterns = determineUrlsForHandlerMethods(handlerType, true); - for (String typeLevelPattern : typeLevelPatterns) { - if (!typeLevelPattern.startsWith("/")) { - typeLevelPattern = "/" + typeLevelPattern; - } - boolean hasEmptyMethodLevelMappings = false; - for (String methodLevelPattern : methodLevelPatterns) { - if (methodLevelPattern == null) { - hasEmptyMethodLevelMappings = true; - } - else { - String combinedPattern = getPathMatcher().combine(typeLevelPattern, methodLevelPattern); - addUrlsForPath(urls, combinedPattern); - } - } - if (hasEmptyMethodLevelMappings || - org.springframework.web.servlet.mvc.Controller.class.isAssignableFrom(handlerType)) { - addUrlsForPath(urls, typeLevelPattern); - } - } - return StringUtils.toStringArray(urls); - } - else { - // actual paths specified by @RequestMapping at method level - return determineUrlsForHandlerMethods(handlerType, false); - } - } - else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) { - // @RequestMapping to be introspected at method level - return determineUrlsForHandlerMethods(handlerType, false); - } - else { - return null; - } - } - - /** - * Derive URL mappings from the handler's method-level mappings. - * @param handlerType the handler type to introspect - * @param hasTypeLevelMapping whether the method-level mappings are nested - * within a type-level mapping - * @return the array of mapped URLs - */ - protected String[] determineUrlsForHandlerMethods(Class handlerType, final boolean hasTypeLevelMapping) { - String[] subclassResult = determineUrlsForHandlerMethods(handlerType); - if (subclassResult != null) { - return subclassResult; - } - - final Set urls = new LinkedHashSet(); - Set> handlerTypes = new LinkedHashSet>(); - handlerTypes.add(handlerType); - handlerTypes.addAll(Arrays.asList(handlerType.getInterfaces())); - for (Class currentHandlerType : handlerTypes) { - ReflectionUtils.doWithMethods(currentHandlerType, new ReflectionUtils.MethodCallback() { - @Override - public void doWith(Method method) { - RequestMapping mapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); - if (mapping != null) { - String[] mappedPatterns = mapping.value(); - if (mappedPatterns.length > 0) { - for (String mappedPattern : mappedPatterns) { - if (!hasTypeLevelMapping && !mappedPattern.startsWith("/")) { - mappedPattern = "/" + mappedPattern; - } - addUrlsForPath(urls, mappedPattern); - } - } - else if (hasTypeLevelMapping) { - // empty method-level RequestMapping - urls.add(null); - } - } - } - }, ReflectionUtils.USER_DECLARED_METHODS); - } - return StringUtils.toStringArray(urls); - } - - /** - * Derive URL mappings from the handler's method-level mappings. - * @param handlerType the handler type to introspect - * @return the array of mapped URLs - */ - protected String[] determineUrlsForHandlerMethods(Class handlerType) { - return null; - } - - /** - * Add URLs and/or URL patterns for the given path. - * @param urls the Set of URLs for the current bean - * @param path the currently introspected path - */ - protected void addUrlsForPath(Set urls, String path) { - urls.add(path); - if (this.useDefaultSuffixPattern && path.indexOf('.') == -1 && !path.endsWith("/")) { - urls.add(path + ".*"); - urls.add(path + "/"); - } - } - - - /** - * Validate the given annotated handler against the current request. - * @see #validateMapping - */ - @Override - protected void validateHandler(Object handler, HttpServletRequest request) throws Exception { - RequestMapping mapping = this.cachedMappings.get(handler.getClass()); - if (mapping == null) { - mapping = AnnotationUtils.findAnnotation(handler.getClass(), RequestMapping.class); - } - if (mapping != null) { - validateMapping(mapping, request); - } - request.setAttribute(USE_DEFAULT_SUFFIX_PATTERN, this.useDefaultSuffixPattern); - } - - /** - * Validate the given type-level mapping metadata against the current request, - * checking HTTP request method and parameter conditions. - * @param mapping the mapping metadata to validate - * @param request current HTTP request - * @throws Exception if validation failed - */ - protected void validateMapping(RequestMapping mapping, HttpServletRequest request) throws Exception { - RequestMethod[] mappedMethods = mapping.method(); - if (!ServletAnnotationMappingUtils.checkRequestMethod(mappedMethods, request)) { - String[] supportedMethods = new String[mappedMethods.length]; - for (int i = 0; i < mappedMethods.length; i++) { - supportedMethods[i] = mappedMethods[i].name(); - } - throw new HttpRequestMethodNotSupportedException(request.getMethod(), supportedMethods); - } - - String[] mappedParams = mapping.params(); - if (!ServletAnnotationMappingUtils.checkParameters(mappedParams, request)) { - throw new UnsatisfiedServletRequestParameterException(mappedParams, request.getParameterMap()); - } - - String[] mappedHeaders = mapping.headers(); - if (!ServletAnnotationMappingUtils.checkHeaders(mappedHeaders, request)) { - throw new ServletRequestBindingException("Header conditions \"" + - StringUtils.arrayToDelimitedString(mappedHeaders, ", ") + - "\" not met for actual request"); - } - } - - @Override - protected boolean supportsTypeLevelMappings() { - return true; - } -} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtils.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtils.java deleted file mode 100644 index 331da2050c..0000000000 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtils.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2002-2016 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.servlet.mvc.annotation; - -import java.util.Iterator; -import java.util.List; -import javax.servlet.http.HttpServletRequest; - -import org.springframework.http.MediaType; -import org.springframework.util.ObjectUtils; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.util.WebUtils; - -/** - * Helper class for annotation-based request mapping. - * - * @author Juergen Hoeller - * @author Arjen Poutsma - * @author Rossen Stoyanchev - * @since 2.5.2 - * @deprecated as of Spring 3.2, together with {@link DefaultAnnotationHandlerMapping}, - * {@link AnnotationMethodHandlerAdapter}, and {@link AnnotationMethodHandlerExceptionResolver}. - */ -@Deprecated -abstract class ServletAnnotationMappingUtils { - - /** - * Check whether the given request matches the specified request methods. - * @param methods the HTTP request methods to check against - * @param request the current HTTP request to check - */ - public static boolean checkRequestMethod(RequestMethod[] methods, HttpServletRequest request) { - String inputMethod = request.getMethod(); - if (ObjectUtils.isEmpty(methods) && !RequestMethod.OPTIONS.name().equals(inputMethod)) { - return true; - } - for (RequestMethod method : methods) { - if (method.name().equals(inputMethod)) { - return true; - } - } - return false; - } - - /** - * Check whether the given request matches the specified parameter conditions. - * @param params the parameter conditions, following - * {@link org.springframework.web.bind.annotation.RequestMapping#params() RequestMapping.#params()} - * @param request the current HTTP request to check - */ - public static boolean checkParameters(String[] params, HttpServletRequest request) { - if (!ObjectUtils.isEmpty(params)) { - for (String param : params) { - int separator = param.indexOf('='); - if (separator == -1) { - if (param.startsWith("!")) { - if (WebUtils.hasSubmitParameter(request, param.substring(1))) { - return false; - } - } - else if (!WebUtils.hasSubmitParameter(request, param)) { - return false; - } - } - else { - boolean negated = separator > 0 && param.charAt(separator - 1) == '!'; - String key = !negated ? param.substring(0, separator) : param.substring(0, separator - 1); - String value = param.substring(separator + 1); - boolean match = value.equals(request.getParameter(key)); - if (negated) { - match = !match; - } - if (!match) { - return false; - } - } - } - } - return true; - } - - /** - * Check whether the given request matches the specified header conditions. - * @param headers the header conditions, following - * {@link org.springframework.web.bind.annotation.RequestMapping#headers() RequestMapping.headers()} - * @param request the current HTTP request to check - */ - public static boolean checkHeaders(String[] headers, HttpServletRequest request) { - if (!ObjectUtils.isEmpty(headers)) { - for (String header : headers) { - int separator = header.indexOf('='); - if (separator == -1) { - if (header.startsWith("!")) { - if (request.getHeader(header.substring(1)) != null) { - return false; - } - } - else if (request.getHeader(header) == null) { - return false; - } - } - else { - boolean negated = (separator > 0 && header.charAt(separator - 1) == '!'); - String key = !negated ? header.substring(0, separator) : header.substring(0, separator - 1); - String value = header.substring(separator + 1); - if (isMediaTypeHeader(key)) { - List requestMediaTypes = MediaType.parseMediaTypes(request.getHeader(key)); - List valueMediaTypes = MediaType.parseMediaTypes(value); - boolean found = false; - for (Iterator valIter = valueMediaTypes.iterator(); valIter.hasNext() && !found;) { - MediaType valueMediaType = valIter.next(); - for (Iterator reqIter = requestMediaTypes.iterator(); - reqIter.hasNext() && !found;) { - MediaType requestMediaType = reqIter.next(); - if (valueMediaType.includes(requestMediaType)) { - found = true; - } - } - - } - if (negated) { - found = !found; - } - if (!found) { - return false; - } - } - else { - boolean match = value.equals(request.getHeader(key)); - if (negated) { - match = !match; - } - if (!match) { - return false; - } - } - } - } - } - return true; - } - - private static boolean isMediaTypeHeader(String headerName) { - return ("Accept".equalsIgnoreCase(headerName) || "Content-Type".equalsIgnoreCase(headerName)); - } - -} diff --git a/spring-webmvc/src/main/resources/org/springframework/web/servlet/DispatcherServlet.properties b/spring-webmvc/src/main/resources/org/springframework/web/servlet/DispatcherServlet.properties index c8e5ab298c..52920de27d 100644 --- a/spring-webmvc/src/main/resources/org/springframework/web/servlet/DispatcherServlet.properties +++ b/spring-webmvc/src/main/resources/org/springframework/web/servlet/DispatcherServlet.properties @@ -7,13 +7,13 @@ org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\ - org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping + org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\ org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\ - org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter + org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter -org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\ +org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver,\ org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\ org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java index d3bf4853f0..f7e1099b3c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/handler/HandlerMappingIntrospectorTests.java @@ -88,8 +88,7 @@ public class HandlerMappingIntrospectorTests { List actual = new HandlerMappingIntrospector(cxt).getHandlerMappings(); assertEquals(2, actual.size()); assertEquals(BeanNameUrlHandlerMapping.class, actual.get(0).getClass()); - assertEquals(org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping.class, - actual.get(1).getClass()); + assertEquals(RequestMappingHandlerMapping.class, actual.get(1).getClass()); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java deleted file mode 100644 index 7103d09df7..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerExceptionResolverTests.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2002-2015 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.servlet.mvc.annotation; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.net.BindException; -import java.net.SocketException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Test; - -import org.springframework.core.annotation.AliasFor; -import org.springframework.http.HttpStatus; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.servlet.ModelAndView; - -import static org.junit.Assert.*; - -/** - * @author Arjen Poutsma - * @author Juergen Hoeller - * @author Sam Brannen - */ -@Deprecated -public class AnnotationMethodHandlerExceptionResolverTests { - - private final AnnotationMethodHandlerExceptionResolver exceptionResolver = new AnnotationMethodHandlerExceptionResolver(); - - private final MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); - - private final MockHttpServletResponse response = new MockHttpServletResponse(); - - - @Test - public void simpleWithIOException() { - IOException ex = new IOException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "X:IOException", mav.getViewName()); - assertEquals("Invalid status code returned", 500, response.getStatus()); - } - - @Test - public void simpleWithSocketException() { - SocketException ex = new SocketException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "Y:SocketException", mav.getViewName()); - assertEquals("Invalid status code returned", 406, response.getStatus()); - assertEquals("Invalid status reason returned", "This is simply unacceptable!", response.getErrorMessage()); - } - - @Test - public void simpleWithFileNotFoundException() { - FileNotFoundException ex = new FileNotFoundException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "X:FileNotFoundException", mav.getViewName()); - assertEquals("Invalid status code returned", 500, response.getStatus()); - } - - @Test - public void simpleWithBindException() { - BindException ex = new BindException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "Y:BindException", mav.getViewName()); - assertEquals("Invalid status code returned", 406, response.getStatus()); - } - - @Test - public void simpleWithNumberFormatExceptionAndComposedResponseStatusAnnotation() { - NumberFormatException ex = new NumberFormatException(); - SimpleController controller = new SimpleController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "X:NumberFormatException", mav.getViewName()); - assertEquals("Invalid status code returned", 400, response.getStatus()); - } - - @Test - public void inherited() { - IOException ex = new IOException(); - InheritedController controller = new InheritedController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertEquals("Invalid view name returned", "GenericError", mav.getViewName()); - assertEquals("Invalid status code returned", 500, response.getStatus()); - } - - @Test(expected = IllegalStateException.class) - public void ambiguous() { - IllegalArgumentException ex = new IllegalArgumentException(); - AmbiguousController controller = new AmbiguousController(); - exceptionResolver.resolveException(request, response, controller, ex); - } - - @Test - public void noModelAndView() throws UnsupportedEncodingException { - IllegalArgumentException ex = new IllegalArgumentException(); - NoMAVReturningController controller = new NoMAVReturningController(); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("ModelAndView not empty", mav.isEmpty()); - assertEquals("Invalid response written", "IllegalArgumentException", response.getContentAsString()); - } - - @Test - public void responseBody() throws UnsupportedEncodingException { - IllegalArgumentException ex = new IllegalArgumentException(); - ResponseBodyController controller = new ResponseBodyController(); - request.addHeader("Accept", "text/plain"); - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - assertTrue("ModelAndView not empty", mav.isEmpty()); - assertEquals("Invalid response written", "IllegalArgumentException", response.getContentAsString()); - } - - // SPR-9209 - - @Test - public void cachingSideEffect() { - IllegalArgumentException ex = new IllegalArgumentException(); - SimpleController controller = new SimpleController(); - - ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex); - assertNotNull("No ModelAndView returned", mav); - - mav = exceptionResolver.resolveException(request, response, controller, new NullPointerException()); - assertNull(mav); - } - - @ResponseStatus - @Retention(RetentionPolicy.RUNTIME) - @interface ComposedResponseStatus { - - @AliasFor(annotation = ResponseStatus.class, attribute = "code") - HttpStatus responseStatus() default HttpStatus.INTERNAL_SERVER_ERROR; - } - - @Controller - private static class SimpleController { - - @ExceptionHandler(IOException.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public String handleIOException(IOException ex, HttpServletRequest request) { - return "X:" + ex.getClass().getSimpleName(); - } - - @ExceptionHandler(SocketException.class) - @ResponseStatus(code = HttpStatus.NOT_ACCEPTABLE, reason = "This is simply unacceptable!") - public String handleSocketException(Exception ex, HttpServletResponse response) { - return "Y:" + ex.getClass().getSimpleName(); - } - - @ExceptionHandler(IllegalArgumentException.class) - public String handleIllegalArgumentException(Exception ex) { - return ex.getClass().getSimpleName(); - } - - @ExceptionHandler(NumberFormatException.class) - @ComposedResponseStatus(responseStatus = HttpStatus.BAD_REQUEST) - public String handleNumberFormatException(NumberFormatException ex) { - return "X:" + ex.getClass().getSimpleName(); - } - } - - - @Controller - private static class InheritedController extends SimpleController { - - @Override - public String handleIOException(IOException ex, HttpServletRequest request) { - return "GenericError"; - } - } - - - @Controller - private static class AmbiguousController { - - @ExceptionHandler({BindException.class, IllegalArgumentException.class}) - public String handle1(Exception ex, HttpServletRequest request, HttpServletResponse response) - throws IOException { - return ex.getClass().getSimpleName(); - } - - @ExceptionHandler - public String handle2(IllegalArgumentException ex) { - return ex.getClass().getSimpleName(); - } - } - - - @Controller - private static class NoMAVReturningController { - - @ExceptionHandler(Exception.class) - public void handle(Exception ex, Writer writer) throws IOException { - writer.write(ex.getClass().getSimpleName()); - } - } - - - @Controller - private static class ResponseBodyController { - - @ExceptionHandler(Exception.class) - @ResponseBody - public String handle(Exception ex) { - return ex.getClass().getSimpleName(); - } - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/RequestSpecificMappingInfoComparatorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/RequestSpecificMappingInfoComparatorTests.java deleted file mode 100644 index b20e3fe5a6..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/RequestSpecificMappingInfoComparatorTests.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2002-2012 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.servlet.mvc.annotation; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import org.junit.Before; -import org.junit.Test; - -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.web.bind.annotation.RequestMethod; - -import static org.junit.Assert.*; - -/** - * @author Arjen Poutsma - */ -@Deprecated -public class RequestSpecificMappingInfoComparatorTests { - - private AnnotationMethodHandlerAdapter.RequestSpecificMappingInfoComparator comparator; - - private AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo emptyInfo; - - private AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo oneMethodInfo; - - private AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo twoMethodsInfo; - - private AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo oneMethodOneParamInfo; - - private AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo oneMethodTwoParamsInfo; - - - @Before - public void setUp() throws NoSuchMethodException { - comparator = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfoComparator(new MockComparator(), new MockHttpServletRequest()); - - emptyInfo = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, new RequestMethod[0],null, null); - - oneMethodInfo = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, new RequestMethod[]{RequestMethod.GET}, null, null); - - twoMethodsInfo = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, new RequestMethod[]{RequestMethod.GET, RequestMethod.POST}, null, null); - - oneMethodOneParamInfo = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, new RequestMethod[]{RequestMethod.GET}, new String[]{"param"}, null); - - oneMethodTwoParamsInfo = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, new RequestMethod[]{RequestMethod.GET}, new String[]{"param1", "param2"}, null); - } - - @Test - public void sort() { - List infos = new ArrayList(); - infos.add(emptyInfo); - infos.add(oneMethodInfo); - infos.add(twoMethodsInfo); - infos.add(oneMethodOneParamInfo); - infos.add(oneMethodTwoParamsInfo); - - Collections.shuffle(infos); - Collections.sort(infos, comparator); - - assertEquals(oneMethodTwoParamsInfo, infos.get(0)); - assertEquals(oneMethodOneParamInfo, infos.get(1)); - assertEquals(oneMethodInfo, infos.get(2)); - assertEquals(twoMethodsInfo, infos.get(3)); - assertEquals(emptyInfo, infos.get(4)); - } - - @Test - public void acceptHeaders() { - AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo html = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, null, null, new String[] {"accept=text/html"}); - - AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo xml = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, null, null, new String[] {"accept=application/xml"}); - - AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo none = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfo(null, null, null, null); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.addHeader("Accept", "application/xml, text/html"); - comparator = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfoComparator(new MockComparator(), request); - - assertTrue(comparator.compare(html, xml) > 0); - assertTrue(comparator.compare(xml, html) < 0); - assertTrue(comparator.compare(xml, none) < 0); - assertTrue(comparator.compare(none, xml) > 0); - assertTrue(comparator.compare(html, none) < 0); - assertTrue(comparator.compare(none, html) > 0); - - request = new MockHttpServletRequest(); - request.addHeader("Accept", "application/xml, text/*"); - comparator = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfoComparator(new MockComparator(), request); - - assertTrue(comparator.compare(html, xml) > 0); - assertTrue(comparator.compare(xml, html) < 0); - - request = new MockHttpServletRequest(); - request.addHeader("Accept", "application/pdf"); - comparator = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfoComparator(new MockComparator(), request); - - assertTrue(comparator.compare(html, xml) == 0); - assertTrue(comparator.compare(xml, html) == 0); - - // See SPR-7000 - request = new MockHttpServletRequest(); - request.addHeader("Accept", "text/html;q=0.9,application/xml"); - comparator = new AnnotationMethodHandlerAdapter.RequestSpecificMappingInfoComparator(new MockComparator(), request); - - assertTrue(comparator.compare(html, xml) > 0); - assertTrue(comparator.compare(xml, html) < 0); - } - - private static class MockComparator implements Comparator { - - @Override - public int compare(String s1, String s2) { - return 0; - } - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java deleted file mode 100644 index fc4bf0bcca..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java +++ /dev/null @@ -1,3356 +0,0 @@ -/* - * Copyright 2002-2016 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.servlet.mvc.annotation; - -import java.beans.PropertyEditorSupport; -import java.io.IOException; -import java.io.Serializable; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Method; -import java.security.Principal; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.validation.constraints.NotNull; -import javax.xml.bind.annotation.XmlRootElement; - -import org.junit.Test; - -import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; -import org.springframework.aop.interceptor.SimpleTraceInterceptor; -import org.springframework.aop.support.DefaultPointcutAdvisor; -import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyEditorRegistrar; -import org.springframework.beans.PropertyEditorRegistry; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.propertyeditors.CustomDateEditor; -import org.springframework.context.annotation.AnnotationConfigUtils; -import org.springframework.core.MethodParameter; -import org.springframework.core.convert.converter.Converter; -import org.springframework.format.support.FormattingConversionServiceFactoryBean; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpInputMessage; -import org.springframework.http.HttpOutputMessage; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.ByteArrayHttpMessageConverter; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.http.converter.HttpMessageNotWritableException; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.mock.web.test.MockMultipartFile; -import org.springframework.mock.web.test.MockMultipartHttpServletRequest; -import org.springframework.mock.web.test.MockServletConfig; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.oxm.jaxb.Jaxb2Marshaller; -import org.springframework.stereotype.Controller; -import org.springframework.tests.sample.beans.DerivedTestBean; -import org.springframework.tests.sample.beans.GenericBean; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.ui.ExtendedModelMap; -import org.springframework.ui.Model; -import org.springframework.ui.ModelMap; -import org.springframework.util.MultiValueMap; -import org.springframework.util.SerializationTestUtils; -import org.springframework.util.StringUtils; -import org.springframework.validation.BindingResult; -import org.springframework.validation.Errors; -import org.springframework.validation.FieldError; -import org.springframework.validation.annotation.Validated; -import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.ModelAttribute; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -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.ResponseBody; -import org.springframework.web.bind.annotation.ResponseStatus; -import org.springframework.web.bind.annotation.SessionAttributes; -import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; -import org.springframework.web.bind.support.WebArgumentResolver; -import org.springframework.web.bind.support.WebBindingInitializer; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.multipart.support.StringMultipartFileEditor; -import org.springframework.web.servlet.DispatcherServlet; -import org.springframework.web.servlet.ModelAndView; -import org.springframework.web.servlet.View; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; -import org.springframework.web.servlet.mvc.AbstractController; -import org.springframework.web.servlet.mvc.multiaction.InternalPathMethodNameResolver; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; -import org.springframework.web.servlet.mvc.support.RedirectAttributes; -import org.springframework.web.servlet.view.InternalResourceViewResolver; -import org.springframework.web.util.NestedServletException; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -/** - * @author Juergen Hoeller - * @author Sam Brannen - * @author Arjen Poutsma - * @since 2.5 - */ -@SuppressWarnings("deprecation") -public class ServletAnnotationControllerTests { - - private DispatcherServlet servlet; - - @Test - public void standardHandleMethod() throws Exception { - initServlet(MyController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void emptyRequestMapping() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(ControllerWithEmptyMapping.class)); - RootBeanDefinition mbd = new RootBeanDefinition(ControllerClassNameHandlerMapping.class); - mbd.getPropertyValues().add("excludedPackages", null); - mbd.getPropertyValues().add("order", 0); - wac.registerBeanDefinition("mapping", mbd); - wac.registerBeanDefinition("mapping2", new RootBeanDefinition(DefaultAnnotationHandlerMapping.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/servletannotationcontrollertests.controllerwithemptymapping"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void emptyValueMapping() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(ControllerWithEmptyValueMapping.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo"); - request.setContextPath("/foo"); - request.setServletPath(""); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test", response.getContentAsString()); - } - - @Test - public void customAnnotationController() throws Exception { - initServlet(CustomAnnotationController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_OK, response.getStatus()); - } - - @Test - public void requiredParamMissing() throws Exception { - initServlet(RequiredParamController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); - assertTrue(servlet.getWebApplicationContext().isSingleton("controller")); - } - - @Test - public void typeConversionError() throws Exception { - initServlet(RequiredParamController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("id", "foo"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); - } - - @Test - public void optionalParamPresent() throws Exception { - initServlet(OptionalParamController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("id", "val"); - request.addParameter("flag", "true"); - request.addHeader("header", "otherVal"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("val-true-otherVal", response.getContentAsString()); - } - - @Test - public void optionalParamMissing() throws Exception { - initServlet(OptionalParamController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("null-false-null", response.getContentAsString()); - } - - @Test - public void defaultParameters() throws Exception { - initServlet(DefaultValueParamController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("foo--bar", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void defaultExpressionParameters() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(DefaultExpressionValueParamController.class)); - RootBeanDefinition ppc = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); - ppc.getPropertyValues().add("properties", "myKey=foo"); - wac.registerBeanDefinition("ppc", ppc); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myPath.do"); - request.setContextPath("/myApp"); - MockHttpServletResponse response = new MockHttpServletResponse(); - System.setProperty("myHeader", "bar"); - try { - servlet.service(request, response); - } - finally { - System.clearProperty("myHeader"); - } - assertEquals("foo-bar-/myApp", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void typeNestedSetBinding() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(NestedSetController.class)); - RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); - csDef.getPropertyValues().add("converters", new TestBeanConverter()); - RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); - wbiDef.getPropertyValues().add("conversionService", csDef); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("testBeanSet", new String[] {"1", "2"}); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); - } - - @Test - public void methodNotAllowed() throws Exception { - initServlet(MethodNotAllowedController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status", HttpServletResponse.SC_METHOD_NOT_ALLOWED, response.getStatus()); - String allowHeader = response.getHeader("Allow"); - assertNotNull("No Allow header", allowHeader); - Set allowedMethods = new HashSet(); - allowedMethods.addAll(Arrays.asList(StringUtils.delimitedListToStringArray(allowHeader, ", "))); - assertEquals("Invalid amount of supported methods", 6, allowedMethods.size()); - assertTrue("PUT not allowed", allowedMethods.contains("PUT")); - assertTrue("DELETE not allowed", allowedMethods.contains("DELETE")); - assertTrue("HEAD not allowed", allowedMethods.contains("HEAD")); - assertTrue("TRACE not allowed", allowedMethods.contains("TRACE")); - assertTrue("OPTIONS not allowed", allowedMethods.contains("OPTIONS")); - assertTrue("POST not allowed", allowedMethods.contains("POST")); - } - - @Test - @SuppressWarnings("serial") - public void proxiedStandardHandleMethod() throws Exception { - DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class)); - DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); - autoProxyCreator.setBeanFactory(wac.getBeanFactory()); - wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator); - wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test", response.getContentAsString()); - } - - @Test - public void emptyParameterListHandleMethod() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(EmptyParameterListHandlerMethodController.class)); - RootBeanDefinition vrDef = new RootBeanDefinition(InternalResourceViewResolver.class); - vrDef.getPropertyValues().add("suffix", ".jsp"); - wac.registerBeanDefinition("viewResolver", vrDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/emptyParameterListHandler"); - MockHttpServletResponse response = new MockHttpServletResponse(); - - EmptyParameterListHandlerMethodController.called = false; - servlet.service(request, response); - assertTrue(EmptyParameterListHandlerMethodController.called); - assertEquals("", response.getContentAsString()); - } - - @Test - public void sessionAttributeExposure() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MySessionAttributesController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(ModelExposingViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page1", request.getAttribute("viewName")); - HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - - request = new MockHttpServletRequest("POST", "/myPage"); - request.setSession(session); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - } - - @Test - public void sessionAttributeExposureWithInterface() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MySessionAttributesControllerImpl.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(ModelExposingViewResolver.class)); - DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); - autoProxyCreator.setBeanFactory(wac.getBeanFactory()); - wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator); - wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page1", request.getAttribute("viewName")); - HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - - request = new MockHttpServletRequest("POST", "/myPage"); - request.setSession(session); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - } - - @Test - public void parameterizedAnnotatedInterface() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyParameterizedControllerImpl.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(ModelExposingViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page1", request.getAttribute("viewName")); - HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); - - request = new MockHttpServletRequest("POST", "/myPage"); - request.setSession(session); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); - } - - @Test - public void parameterizedAnnotatedInterfaceWithOverriddenMappingsInImpl() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(MyParameterizedControllerImplWithOverriddenMappings.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(ModelExposingViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPage"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page1", request.getAttribute("viewName")); - HttpSession session = request.getSession(); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); - - request = new MockHttpServletRequest("POST", "/myPage"); - request.setSession(session); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("page2", request.getAttribute("viewName")); - assertTrue(session.getAttribute("object1") != null); - assertTrue(session.getAttribute("object2") != null); - assertTrue(((Map) session.getAttribute("model")).containsKey("object1")); - assertTrue(((Map) session.getAttribute("model")).containsKey("object2")); - assertTrue(((Map) session.getAttribute("model")).containsKey("testBeanList")); - } - - @Test - public void adaptedHandleMethods() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController.class); - } - - @Test - public void adaptedHandleMethods2() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController2.class); - } - - @Test - public void adaptedHandleMethods3() throws Exception { - doTestAdaptedHandleMethods(MyAdaptedController3.class); - } - - @SuppressWarnings("serial") - private void initServlet(final Class controllerClass) throws ServletException { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - } - - private void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception { - initServlet(controllerClass); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath1.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - request.addParameter("param1", "value1"); - request.addParameter("param2", "2"); - servlet.service(request, response); - assertEquals("test", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myPath2.do"); - request.addParameter("param1", "value1"); - request.addParameter("param2", "2"); - request.addHeader("header1", "10"); - request.setCookies(new Cookie("cookie1", "3")); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-value1-2-10-3", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myPath3.do"); - request.addParameter("param1", "value1"); - request.addParameter("param2", "2"); - request.addParameter("name", "name1"); - request.addParameter("age", "2"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-name1-2", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myPath4.do"); - request.addParameter("param1", "value1"); - request.addParameter("param2", "2"); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-name1-typeMismatch", response.getContentAsString()); - } - - @Test - public void formController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); - } - - @Test - public void modelFormController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyModelFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myPath-name1-typeMismatch-tb1-myValue-yourValue", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void proxiedFormController() throws Exception { - DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MyFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); - autoProxyCreator.setBeanFactory(wac.getBeanFactory()); - wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator); - wac.getBeanFactory() - .registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("name", "name1"); - request.addParameter("age", "value2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString()); - } - - @Test - public void commandProvidingFormControllerWithCustomEditor() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(MyCommandProvidingFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void typedCommandProvidingFormController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(MyTypedCommandProvidingFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer()); - adapterDef.getPropertyValues().add("customArgumentResolver", new MySpecialArgumentResolver()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myOtherPath.do"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myThirdPath.do"); - request.addParameter("defaultName", "10"); - request.addParameter("age", "100"); - request.addParameter("date", "2007-10-02"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-special-99-special-99", response.getContentAsString()); - } - - @Test - public void binderInitializingCommandProvidingFormController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(MyBinderInitializingCommandProvidingFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void specificBinderInitializingCommandProvidingFormController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(MySpecificBinderInitializingCommandProvidingFormController.class)); - wac.registerBeanDefinition("viewResolver", new RootBeanDefinition(TestViewResolver.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath.do"); - request.addParameter("defaultName", "myDefaultName"); - request.addParameter("age", "value2"); - request.addParameter("date", "2007-10-02"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString()); - } - - @Test - public void parameterDispatchingController() throws Exception { - final MockServletContext servletContext = new MockServletContext(); - final MockServletConfig servletConfig = new MockServletConfig(servletContext); - - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.setServletContext(servletContext); - RootBeanDefinition bd = new RootBeanDefinition(MyParameterDispatchingController.class); - //bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - AnnotationConfigUtils.registerAnnotationConfigProcessors(wac); - wac.getBeanFactory().registerResolvableDependency(ServletConfig.class, servletConfig); - wac.refresh(); - return wac; - } - }; - servlet.init(servletConfig); - - MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - HttpSession session = request.getSession(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - assertSame(servletContext, request.getAttribute("servletContext")); - assertSame(servletConfig, request.getAttribute("servletConfig")); - assertSame(session.getId(), request.getAttribute("sessionId")); - assertSame(request.getRequestURI(), request.getAttribute("requestUri")); - assertSame(request.getLocale(), request.getAttribute("locale")); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - response = new MockHttpServletResponse(); - session = request.getSession(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - assertSame(servletContext, request.getAttribute("servletContext")); - assertSame(servletConfig, request.getAttribute("servletConfig")); - assertSame(session.getId(), request.getAttribute("sessionId")); - assertSame(request.getRequestURI(), request.getAttribute("requestUri")); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("view", "other"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("surprise", "!"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - - MyParameterDispatchingController deserialized = (MyParameterDispatchingController) SerializationTestUtils - .serializeAndDeserialize(servlet.getWebApplicationContext().getBean("controller")); - assertNotNull(deserialized.request); - assertNotNull(deserialized.session); - } - - @Test - public void constrainedParameterDispatchingController() throws Exception { - final MockServletContext servletContext = new MockServletContext(); - final MockServletConfig servletConfig = new MockServletConfig(servletContext); - - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.setServletContext(servletContext); - RootBeanDefinition bd = new RootBeanDefinition(MyConstrainedParameterDispatchingController.class); - bd.setScope(WebApplicationContext.SCOPE_REQUEST); - wac.registerBeanDefinition("controller", bd); - wac.refresh(); - return wac; - } - }; - servlet.init(servletConfig); - - MockHttpServletRequest request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("view", "other"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(400, response.getStatus()); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("active", "true"); - request.addParameter("view", "other"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(400, response.getStatus()); - - request = new MockHttpServletRequest(servletContext, "GET", "/myPath.do"); - request.addParameter("view", "my"); - request.addParameter("lang", "de"); - request.addParameter("active", "true"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - } - - @Test - public void methodNameDispatchingController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MethodNameDispatchingController.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myHandle.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myOtherHandle.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/myLangHandle.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/mySurpriseHandle.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void methodNameDispatchingControllerWithSuffix() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MethodNameDispatchingController.class)); - InternalPathMethodNameResolver methodNameResolver = new InternalPathMethodNameResolver(); - methodNameResolver.setSuffix("Handle"); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("methodNameResolver", methodNameResolver); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/my.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myOther.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/myLang.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/mySurprise.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void controllerClassNamePlusMethodNameDispatchingController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - RootBeanDefinition mapping = new RootBeanDefinition(ControllerClassNameHandlerMapping.class); - mapping.getPropertyValues().add("excludedPackages", null); - wac.registerBeanDefinition("handlerMapping", mapping); - wac.registerBeanDefinition("controller", new RootBeanDefinition(MethodNameDispatchingController.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/methodnamedispatching/myHandle"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/methodnamedispatching/myOtherHandle.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/methodnamedispatching/myLangHandle.x"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/methodnamedispatching/mySurpriseHandle.y"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void postMethodNameDispatchingController() throws Exception { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", - new RootBeanDefinition(MyPostMethodNameDispatchingController.class)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myHandle.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(405, response.getStatus()); - - request = new MockHttpServletRequest("POST", "/myUnknownHandle.do"); - request.addParameter("myParam", "myValue"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(404, response.getStatus()); - - request = new MockHttpServletRequest("POST", "/myHandle.do"); - request.addParameter("myParam", "myValue"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/myOtherHandle.do"); - request.addParameter("myParam", "myValue"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/myLangHandle.do"); - request.addParameter("myParam", "myValue"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/mySurpriseHandle.do"); - request.addParameter("myParam", "myValue"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void relativePathDispatchingController() throws Exception { - initServlet(MyRelativePathDispatchingController.class); - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myHandle"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myApp/myOther"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myApp/myLang"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/myApp/surprise.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void relativeMethodPathDispatchingController() throws Exception { - initServlet(MyRelativeMethodPathDispatchingController.class); - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myApp/myHandle"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/yourApp/myOther"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myOtherView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/hisApp/myLang"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myLangView", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/herApp/surprise.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("mySurpriseView", response.getContentAsString()); - } - - @Test - public void nullCommandController() throws Exception { - initServlet(MyNullCommandController.class); - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myPath"); - request.setUserPrincipal(new OtherPrincipal()); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myView", response.getContentAsString()); - } - - @Test - public void equivalentMappingsWithSameMethodName() throws Exception { - initServlet(ChildController.class); - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/child/test"); - request.addParameter("childId", "100"); - MockHttpServletResponse response = new MockHttpServletResponse(); - try { - servlet.service(request, response); - fail("Didn't fail with due to ambiguous method mapping"); - } - catch (NestedServletException ex) { - assertTrue(ex.getCause() instanceof IllegalStateException); - assertTrue(ex.getCause().getMessage().contains("doGet")); - } - } - - @Test - public void pathOrdering() throws ServletException, IOException { - initServlet(PathOrderingController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/dir/myPath1.do"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("method1", response.getContentAsString()); - } - - @Test - public void requestBodyResponseBody() throws ServletException, IOException { - initServlet(RequestResponseBodyController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "text/plain; charset=utf-8"); - request.addHeader("Accept", "text/*, */*"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); - } - - @Test - public void responseBodyNoAcceptableMediaType() throws ServletException, IOException { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class)); - RootBeanDefinition converterDef = new RootBeanDefinition(StringHttpMessageConverter.class); - converterDef.getPropertyValues().add("supportedMediaTypes", new MediaType("text", "plain")); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - StringHttpMessageConverter converter = new StringHttpMessageConverter(); - converter.setSupportedMediaTypes(Collections.singletonList(new MediaType("text", "plain"))); - adapterDef.getPropertyValues().add("messageConverters", converter); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "text/plain; charset=utf-8"); - request.addHeader("Accept", "application/pdf, application/msword"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(406, response.getStatus()); - } - - @Test - public void responseBodyWildCardMediaType() throws ServletException, IOException { - initServlet(RequestResponseBodyController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "text/plain; charset=utf-8"); - request.addHeader("Accept", "*/*"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(requestBody, response.getContentAsString()); - } - - @Test - public void unsupportedRequestBody() throws ServletException, IOException { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("messageConverters", new ByteArrayHttpMessageConverter()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "application/pdf"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(415, response.getStatus()); - assertNotNull("No Accept response header set", response.getHeader("Accept")); - } - - @Test - public void responseBodyNoAcceptHeader() throws ServletException, IOException { - initServlet(RequestResponseBodyController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "text/plain; charset=utf-8"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(200, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); - } - - @Test - public void badRequestRequestBody() throws ServletException, IOException { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("messageConverters", new NotReadableMessageConverter()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "application/pdf"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); - } - - @Test - public void httpEntity() throws ServletException, IOException { - initServlet(ResponseEntityController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/foo"); - String requestBody = "Hello World"; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "text/plain; charset=utf-8"); - request.addHeader("Accept", "text/*, */*"); - request.addHeader("MyRequestHeader", "MyValue"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(201, response.getStatus()); - assertEquals(requestBody, response.getContentAsString()); - assertEquals("MyValue", response.getHeader("MyResponseHeader")); - - request = new MockHttpServletRequest("PUT", "/bar"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("MyValue", response.getHeader("MyResponseHeader")); - assertEquals(404, response.getStatus()); - } - - - /* - * See SPR-6877 - */ - @Test - public void overlappingMesssageConvertersRequestBody() throws ServletException, IOException { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestResponseBodyController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - List messageConverters = new ArrayList(); - messageConverters.add(new StringHttpMessageConverter()); - messageConverters - .add(new SimpleMessageConverter(new MediaType("application","json"), MediaType.ALL)); - adapterDef.getPropertyValues().add("messageConverters", messageConverters); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - request.setContent("Hello World".getBytes("UTF-8")); - request.addHeader("Content-Type", "text/plain; charset=utf-8"); - request.addHeader("Accept", "application/json, text/javascript, */*"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status code", "application/json;charset=ISO-8859-1", response.getHeader("Content-Type")); - } - - @Test - public void responseBodyVoid() throws ServletException, IOException { - initServlet(ResponseBodyVoidController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something"); - request.addHeader("Accept", "text/*, */*"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(200, response.getStatus()); - } - - @Test - public void responseBodyArgMismatch() throws ServletException, IOException { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(RequestBodyArgMismatchController.class)); - - Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(A.class, B.class); - try { - marshaller.afterPropertiesSet(); - } - catch (Exception ex) { - throw new BeanCreationException(ex.getMessage(), ex); - } - - MarshallingHttpMessageConverter messageConverter = new MarshallingHttpMessageConverter(marshaller); - - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("messageConverters", messageConverter); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/something"); - String requestBody = ""; - request.setContent(requestBody.getBytes("UTF-8")); - request.addHeader("Content-Type", "application/xml; charset=utf-8"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(400, response.getStatus()); - } - - - @Test - public void contentTypeHeaders() throws ServletException, IOException { - initServlet(ContentTypeHeadersController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/something"); - request.addHeader("Content-Type", "application/pdf"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("pdf", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/something"); - request.addHeader("Content-Type", "text/html"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("text", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/something"); - request.addHeader("Content-Type", "application/xml"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(404, response.getStatus()); - } - - @Test - public void negatedContentTypeHeaders() throws ServletException, IOException { - initServlet(NegatedContentTypeHeadersController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("POST", "/something"); - request.addHeader("Content-Type", "application/pdf"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("pdf", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/something"); - request.addHeader("Content-Type", "text/html"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("non-pdf", response.getContentAsString()); - } - - @Test - public void acceptHeaders() throws ServletException, IOException { - initServlet(AcceptHeadersController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something"); - request.addHeader("Accept", "text/html"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("html", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/something"); - request.addHeader("Accept", "application/xml"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("xml", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/something"); - request.addHeader("Accept", "application/xml, text/html"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("xml", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/something"); - request.addHeader("Accept", "text/html;q=0.9, application/xml"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("xml", response.getContentAsString()); - } - - @Test - public void responseStatus() throws ServletException, IOException { - initServlet(ResponseStatusController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/something"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("something", response.getContentAsString()); - assertEquals(201, response.getStatus()); - assertEquals("It's alive!", response.getErrorMessage()); - } - - @Test - public void mavResolver() throws ServletException, IOException { - @SuppressWarnings("serial") DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(ModelAndViewResolverController.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("customModelAndViewResolver", new MyModelAndViewResolver()); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myValue", response.getContentAsString()); - - } - - @Test - public void bindingCookieValue() throws ServletException, IOException { - initServlet(BindingCookieValueController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); - request.setCookies(new Cookie("date", "2008-11-18")); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-2008", response.getContentAsString()); - } - - @Test - public void ambiguousParams() throws ServletException, IOException { - initServlet(AmbiguousParamsController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("noParams", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/test"); - request.addParameter("myParam", "42"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("myParam-42", response.getContentAsString()); - } - - @Test - public void bridgeMethods() throws Exception { - initServlet(TestControllerImpl.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/method"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - } - - @Test - public void requestParamMap() throws Exception { - initServlet(RequestParamMapController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/map"); - request.addParameter("key1", "value1"); - request.addParameter("key2", new String[]{"value21", "value22"}); - MockHttpServletResponse response = new MockHttpServletResponse(); - - servlet.service(request, response); - assertEquals("key1=value1,key2=value21", response.getContentAsString()); - - request.setRequestURI("/multiValueMap"); - response = new MockHttpServletResponse(); - - servlet.service(request, response); - assertEquals("key1=[value1],key2=[value21,value22]", response.getContentAsString()); - } - - @Test - public void requestHeaderMap() throws Exception { - initServlet(RequestHeaderMapController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/map"); - request.addHeader("Content-Type", "text/html"); - request.addHeader("Custom-Header", new String[]{"value21", "value22"}); - MockHttpServletResponse response = new MockHttpServletResponse(); - - servlet.service(request, response); - assertEquals("Content-Type=text/html,Custom-Header=value21", response.getContentAsString()); - - request.setRequestURI("/multiValueMap"); - response = new MockHttpServletResponse(); - - servlet.service(request, response); - assertEquals("Content-Type=[text/html],Custom-Header=[value21,value22]", response.getContentAsString()); - - request.setRequestURI("/httpHeaders"); - response = new MockHttpServletResponse(); - - servlet.service(request, response); - assertEquals("Content-Type=[text/html],Custom-Header=[value21,value22]", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void controllerClassNameNoTypeLevelAnn() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(BookController.class)); - RootBeanDefinition mapping = new RootBeanDefinition(ControllerClassNameHandlerMapping.class); - mapping.getPropertyValues().add("excludedPackages", null); - wac.registerBeanDefinition("handlerMapping", mapping); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/book/list"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("list", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/book/show"); - request.addParameter("id", "12"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("show-id=12", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/book"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("create", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void simpleUrlHandlerMapping() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(BookController.class)); - RootBeanDefinition hmDef = new RootBeanDefinition(SimpleUrlHandlerMapping.class); - hmDef.getPropertyValues().add("mappings", "/book/*=controller\n/book=controller"); - wac.registerBeanDefinition("handlerMapping", hmDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/book/list"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("list", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/book/show"); - request.addParameter("id", "12"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("show-id=12", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/book"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("create", response.getContentAsString()); - } - - @Test - public void requestMappingInterface() throws Exception { - initServlet(IMyControllerImpl.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle null", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/handle"); - request.addParameter("p", "value"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle value", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void requestMappingInterfaceWithProxy() throws Exception { - DispatcherServlet servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(IMyControllerImpl.class)); - DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator(); - autoProxyCreator.setBeanFactory(wac.getBeanFactory()); - wac.getBeanFactory().addBeanPostProcessor(autoProxyCreator); - wac.getBeanFactory().registerSingleton("advisor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor())); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle null", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/handle"); - request.addParameter("p", "value"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle value", response.getContentAsString()); - } - - @Test - public void requestMappingBaseClass() throws Exception { - initServlet(MyAbstractControllerImpl.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle", response.getContentAsString()); - - } - - @Test - public void trailingSlash() throws Exception { - initServlet(TrailingSlashController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("templatePath", response.getContentAsString()); - } - - @Test - public void testMatchWithoutMethodLevelPath() throws Exception { - initServlet(NoPathGetAndM2PostController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/t1/m2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(405, response.getStatus()); - } - - // SPR-8536 - - @Test - public void testHeadersCondition() throws Exception { - initServlet(HeadersConditionController.class); - - // No "Accept" header - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - - assertEquals(200, response.getStatus()); - assertEquals("home", response.getForwardedUrl()); - - // Accept "*/*" - request = new MockHttpServletRequest("GET", "/"); - request.addHeader("Accept", "*/*"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - - assertEquals(200, response.getStatus()); - assertEquals("home", response.getForwardedUrl()); - - // Accept "application/json" - request = new MockHttpServletRequest("GET", "/"); - request.addHeader("Accept", "application/json"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - - assertEquals(200, response.getStatus()); - assertEquals("application/json;charset=ISO-8859-1", response.getHeader("Content-Type")); - assertEquals("homeJson", response.getContentAsString()); - } - - @Test - public void redirectAttribute() throws Exception { - initServlet(RedirectAttributesController.class); - try { - servlet.service(new MockHttpServletRequest("GET", "/"), new MockHttpServletResponse()); - } - catch (NestedServletException ex) { - assertTrue(ex.getMessage().contains("not assignable from the actual model")); - } - } - - /* - * See SPR-6021 - */ - @Test - public void customMapEditor() throws Exception { - initServlet(CustomMapEditorController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handle"); - request.addParameter("map", "bar"); - MockHttpServletResponse response = new MockHttpServletResponse(); - - servlet.service(request, response); - - assertEquals("test-{foo=bar}", response.getContentAsString()); - } - - @Test - public void multipartFileAsSingleString() throws Exception { - initServlet(MultipartController.class); - - MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); - request.setRequestURI("/singleString"); - request.addFile(new MockMultipartFile("content", "Juergen".getBytes())); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Juergen", response.getContentAsString()); - } - - @Test - public void regularParameterAsSingleString() throws Exception { - initServlet(MultipartController.class); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/singleString"); - request.setMethod("POST"); - request.addParameter("content", "Juergen"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Juergen", response.getContentAsString()); - } - - @Test - public void multipartFileAsStringArray() throws Exception { - initServlet(MultipartController.class); - - MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); - request.setRequestURI("/stringArray"); - request.addFile(new MockMultipartFile("content", "Juergen".getBytes())); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Juergen", response.getContentAsString()); - } - - @Test - public void regularParameterAsStringArray() throws Exception { - initServlet(MultipartController.class); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/stringArray"); - request.setMethod("POST"); - request.addParameter("content", "Juergen"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Juergen", response.getContentAsString()); - } - - @Test - public void multipartFilesAsStringArray() throws Exception { - initServlet(MultipartController.class); - - MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); - request.setRequestURI("/stringArray"); - request.addFile(new MockMultipartFile("content", "Juergen".getBytes())); - request.addFile(new MockMultipartFile("content", "Eva".getBytes())); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Juergen-Eva", response.getContentAsString()); - } - - @Test - public void regularParametersAsStringArray() throws Exception { - initServlet(MultipartController.class); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/stringArray"); - request.setMethod("POST"); - request.addParameter("content", "Juergen"); - request.addParameter("content", "Eva"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Juergen-Eva", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void parameterCsvAsIntegerArray() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(CsvController.class)); - RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); - RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); - wbiDef.getPropertyValues().add("conversionService", csDef); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/integerArray"); - request.setMethod("POST"); - request.addParameter("content", "1,2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("1-2", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void parameterCsvAsIntegerSet() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(CsvController.class)); - RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); - RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); - wbiDef.getPropertyValues().add("conversionService", csDef); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/integerSet"); - request.setMethod("POST"); - request.addParameter("content", "1,2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("1-2", response.getContentAsString()); - } - - @Test - @SuppressWarnings("serial") - public void parameterCsvAsIntegerSetWithCustomSeparator() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(CsvController.class)); - RootBeanDefinition csDef = new RootBeanDefinition(FormattingConversionServiceFactoryBean.class); - RootBeanDefinition wbiDef = new RootBeanDefinition(ConfigurableWebBindingInitializer.class); - wbiDef.getPropertyValues().add("conversionService", csDef); - wbiDef.getPropertyValues().add("propertyEditorRegistrars", new RootBeanDefinition(ListEditorRegistrar.class)); - RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class); - adapterDef.getPropertyValues().add("webBindingInitializer", wbiDef); - wac.registerBeanDefinition("handlerAdapter", adapterDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/integerSet"); - request.setMethod("POST"); - request.addParameter("content", "1;2"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("1-2", response.getContentAsString()); - } - - @Test - public void httpOptions() throws ServletException, IOException { - initServlet(ResponseEntityController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/foo"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(404, response.getStatus()); - } - - - public static class ListEditorRegistrar implements PropertyEditorRegistrar { - - @Override - public void registerCustomEditors(PropertyEditorRegistry registry) { - registry.registerCustomEditor(Set.class, new ListEditor()); - } - } - - public static class ListEditor extends PropertyEditorSupport { - - @SuppressWarnings("unchecked") - @Override - public String getAsText() { - return StringUtils.collectionToDelimitedString((Collection) getValue(), ";"); - } - - @Override - public void setAsText(String text) throws IllegalArgumentException { - Set s = new LinkedHashSet(); - for (String t : text.split(";")) { - s.add(t); - } - setValue(s); - } - } - - - /* - * Controllers - */ - - @RequestMapping("/myPath.do") - private static class MyController extends AbstractController { - - @Override - protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) - throws Exception { - response.getWriter().write("test"); - return null; - } - } - - @Controller - private static class ControllerWithEmptyMapping { - - @RequestMapping - public void myPath2(HttpServletResponse response) throws IOException { - response.getWriter().write("test"); - } - } - - @Controller - private static class ControllerWithEmptyValueMapping { - - @RequestMapping("") - public void myPath2(HttpServletResponse response) throws IOException { - throw new IllegalStateException("test"); - } - - @RequestMapping("/bar") - public void myPath3(HttpServletResponse response) throws IOException { - response.getWriter().write("testX"); - } - - @ExceptionHandler - public void myPath2(Exception ex, HttpServletResponse response) throws IOException { - response.getWriter().write(ex.getMessage()); - } - } - - @Controller - private static class MyAdaptedController { - - @RequestMapping("/myPath1.do") - public void myHandle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("test"); - } - - @RequestMapping("/myPath2.do") - public void myHandle(@RequestParam("param1") String p1, @RequestParam("param2") int p2, - @RequestHeader("header1") long h1, @CookieValue("cookie1") Cookie c1, - HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + p2 + "-" + h1 + "-" + c1.getValue()); - } - - @RequestMapping("/myPath3") - public void myHandle(TestBean tb, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("/myPath4.do") - public void myHandle(TestBean tb, Errors errors, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - @Controller - @RequestMapping("/*.do") - private static class MyAdaptedController2 { - - @RequestMapping - public void myHandle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("test"); - } - - @RequestMapping("/myPath2.do") - public void myHandle(@RequestParam("param1") String p1, int param2, HttpServletResponse response, - @RequestHeader("header1") String h1, @CookieValue("cookie1") String c1) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2 + "-" + h1 + "-" + c1); - } - - @RequestMapping("/myPath3") - public void myHandle(TestBean tb, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("/myPath4.*") - public void myHandle(TestBean tb, Errors errors, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - } - - @Controller - private static class MyAdaptedControllerBase { - - @RequestMapping("/myPath2.do") - public void myHandle(@RequestParam("param1") T p1, int param2, @RequestHeader Integer header1, - @CookieValue int cookie1, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1); - } - - @InitBinder - public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); - } - - @ModelAttribute - public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); - } - } - - @RequestMapping("/*.do") - private static class MyAdaptedController3 extends MyAdaptedControllerBase { - - @RequestMapping - public void myHandle(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.getWriter().write("test"); - } - - @Override - public void myHandle(@RequestParam("param1") String p1, int param2, @RequestHeader Integer header1, - @CookieValue int cookie1, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + p1 + "-" + param2 + "-" + header1 + "-" + cookie1); - } - - @RequestMapping("/myPath3") - public void myHandle(TestBean tb, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge()); - } - - @RequestMapping("/myPath4.*") - public void myHandle(TestBean tb, Errors errors, HttpServletResponse response) throws IOException { - response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode()); - } - - @Override - @InitBinder - public void initBinder(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); - } - - @Override - @ModelAttribute - public void modelAttribute(@RequestParam("param1") String p1, @RequestParam(value="paramX", required=false) String px, int param2) { - assertNull(px); - } - } - - @Controller - @RequestMapping(method = RequestMethod.GET) - private static class EmptyParameterListHandlerMethodController { - - static boolean called; - - @RequestMapping("/emptyParameterListHandler") - public void emptyParameterListHandler() { - EmptyParameterListHandlerMethodController.called = true; - } - - @RequestMapping("/nonEmptyParameterListHandler") - public void nonEmptyParameterListHandler(HttpServletResponse response) { - } - } - - @Controller - @RequestMapping("/myPage") - @SessionAttributes(names = { "object1", "object2" }) - public static class MySessionAttributesController { - - @RequestMapping(method = RequestMethod.GET) - public String get(Model model) { - model.addAttribute("object1", new Object()); - model.addAttribute("object2", new Object()); - return "page1"; - } - - @RequestMapping(method = RequestMethod.POST) - public String post(@ModelAttribute("object1") Object object1) { - //do something with object1 - return "page2"; - - } - } - - @RequestMapping("/myPage") - @SessionAttributes({"object1", "object2"}) - public interface MySessionAttributesControllerIfc { - - @RequestMapping(method = RequestMethod.GET) - String get(Model model); - - @RequestMapping(method = RequestMethod.POST) - String post(@ModelAttribute("object1") Object object1); - } - - @Controller - public static class MySessionAttributesControllerImpl implements MySessionAttributesControllerIfc { - - @Override - public String get(Model model) { - model.addAttribute("object1", new Object()); - model.addAttribute("object2", new Object()); - return "page1"; - } - - @Override - public String post(@ModelAttribute("object1") Object object1) { - //do something with object1 - return "page2"; - } - } - - @RequestMapping("/myPage") - @SessionAttributes({"object1", "object2"}) - public interface MyParameterizedControllerIfc { - - @ModelAttribute("testBeanList") - List getTestBeans(); - - @RequestMapping(method = RequestMethod.GET) - String get(Model model); - } - - public interface MyEditableParameterizedControllerIfc extends MyParameterizedControllerIfc { - - @RequestMapping(method = RequestMethod.POST) - String post(@ModelAttribute("object1") T object); - } - - @Controller - public static class MyParameterizedControllerImpl implements MyEditableParameterizedControllerIfc { - - @Override - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @Override - public String get(Model model) { - model.addAttribute("object1", new TestBean()); - model.addAttribute("object2", new TestBean()); - return "page1"; - } - - @Override - public String post(TestBean object) { - //do something with object1 - return "page2"; - } - } - - @Controller - public static class MyParameterizedControllerImplWithOverriddenMappings implements MyEditableParameterizedControllerIfc { - - @Override - @ModelAttribute("testBeanList") - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @Override - @RequestMapping(method = RequestMethod.GET) - public String get(Model model) { - model.addAttribute("object1", new TestBean()); - model.addAttribute("object2", new TestBean()); - return "page1"; - } - - @Override - @RequestMapping(method = RequestMethod.POST) - public String post(@ModelAttribute("object1") TestBean object1) { - //do something with object1 - return "page2"; - } - } - - @Controller - public static class MyFormController { - - @ModelAttribute("testBeanList") - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @RequestMapping("/myPath.do") - public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) { - FieldError error = errors.getFieldError("age"); - assertNotNull("Must have field error for age property", error); - assertEquals("value2", error.getRejectedValue()); - if (!model.containsKey("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "myView"; - } - } - - public static class ValidTestBean extends TestBean { - - @NotNull(groups = MyGroup.class) - private String validCountry; - - public void setValidCountry(String validCountry) { - this.validCountry = validCountry; - } - - public String getValidCountry() { - return this.validCountry; - } - } - - @Controller - public static class MyModelFormController { - - @ModelAttribute - public List getTestBeans() { - List list = new LinkedList(); - list.add(new TestBean("tb1")); - list.add(new TestBean("tb2")); - return list; - } - - @RequestMapping("/myPath.do") - @ModelAttribute("yourKey") - public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, Model model) { - if (!model.containsAttribute("myKey")) { - model.addAttribute("myKey", "myValue"); - } - return "yourValue"; - } - } - - @Controller - private static class MyCommandProvidingFormController extends MyFormController { - - @SuppressWarnings("unused") - @ModelAttribute("myCommand") - private ValidTestBean createTestBean(@RequestParam T defaultName, Map model, @RequestParam Date date) { - model.put("myKey", "myOriginalValue"); - ValidTestBean tb = new ValidTestBean(); - tb.setName(defaultName.getClass().getSimpleName() + ":" + defaultName.toString()); - return tb; - } - - @Override - @RequestMapping("/myPath.do") - public String myHandle(@ModelAttribute("myCommand") @Validated(MyGroup.class) TestBean tb, BindingResult errors, ModelMap model) { - if (!errors.hasFieldErrors("validCountry")) { - throw new IllegalStateException("Declarative validation not applied"); - } - return super.myHandle(tb, errors, model); - } - - @RequestMapping("/myOtherPath.do") - public String myOtherHandle(TB tb, BindingResult errors, ExtendedModelMap model, MySpecialArg arg) { - TestBean tbReal = (TestBean) tb; - tbReal.setName("myName"); - assertTrue(model.get("ITestBean") instanceof DerivedTestBean); - assertNotNull(arg); - return super.myHandle(tbReal, errors, model); - } - - @RequestMapping("/myThirdPath.do") - public String myThirdHandle(TB tb, Model model) { - model.addAttribute("testBean", new TestBean("special", 99)); - return "myView"; - } - - @ModelAttribute - protected TB2 getModelAttr() { - return (TB2) new DerivedTestBean(); - } - } - - private static class MySpecialArg { - - public MySpecialArg(String value) { - } - } - - @Controller - private static class MyTypedCommandProvidingFormController - extends MyCommandProvidingFormController { - } - - @Validated(MyGroup.class) - @Target({ElementType.PARAMETER}) - @Retention(RetentionPolicy.RUNTIME) - public @interface MyValid { - } - - @Controller - private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController { - - @SuppressWarnings("unused") - @InitBinder - private void initBinder(WebDataBinder binder) { - binder.initBeanPropertyAccess(); - binder.setRequiredFields("sex"); - LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean(); - vf.afterPropertiesSet(); - binder.setValidator(vf); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - - @Override - @RequestMapping("/myPath.do") - public String myHandle(@ModelAttribute("myCommand") @MyValid TestBean tb, BindingResult errors, ModelMap model) { - if (!errors.hasFieldErrors("sex")) { - throw new IllegalStateException("requiredFields not applied"); - } - return super.myHandle(tb, errors, model); - } - } - - @Controller - private static class MySpecificBinderInitializingCommandProvidingFormController - extends MyCommandProvidingFormController { - - @SuppressWarnings("unused") - @InitBinder({"myCommand", "date"}) - private void initBinder(WebDataBinder binder, String date, @RequestParam("date") String[] date2) { - LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean(); - vf.afterPropertiesSet(); - binder.setValidator(vf); - assertEquals("2007-10-02", date); - assertEquals(1, date2.length); - assertEquals("2007-10-02", date2[0]); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - public interface MyGroup { - } - - private static class MyWebBindingInitializer implements WebBindingInitializer { - - @Override - public void initBinder(WebDataBinder binder, WebRequest request) { - LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean(); - vf.afterPropertiesSet(); - binder.setValidator(vf); - assertNotNull(request.getLocale()); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - } - - private static class MySpecialArgumentResolver implements WebArgumentResolver { - - @Override - public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { - if (methodParameter.getParameterType().equals(MySpecialArg.class)) { - return new MySpecialArg("myValue"); - } - return UNRESOLVED; - } - } - - @SuppressWarnings("serial") - @Controller - @RequestMapping("/myPath.do") - private static class MyParameterDispatchingController implements Serializable { - - @Autowired - private transient ServletContext servletContext; - - @Autowired - private transient ServletConfig servletConfig; - - @Autowired - private HttpServletRequest request; - - @Autowired - private HttpServletResponse response; - - @Autowired - private HttpSession session; - - @Autowired - private WebRequest webRequest; - - @RequestMapping - public void myHandle(HttpServletResponse response, HttpServletRequest request) throws IOException { - if (this.servletContext == null || this.servletConfig == null || this.request == null || - this.response == null || this.session == null || this.webRequest == null) { - throw new IllegalStateException(); - } - response.getWriter().write("myView"); - request.setAttribute("servletContext", this.servletContext); - request.setAttribute("servletConfig", this.servletConfig); - request.setAttribute("sessionId", this.session.getId()); - request.setAttribute("requestUri", this.request.getRequestURI()); - request.setAttribute("locale", this.webRequest.getLocale()); - } - - @RequestMapping(params = {"view", "!lang"}) - public void myOtherHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myOtherView"); - } - - @RequestMapping(method = RequestMethod.GET, params = {"view=my", "lang=de"}) - public void myLangHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myLangView"); - } - - @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, params = "surprise") - public void mySurpriseHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("mySurpriseView"); - } - } - - @Controller - @RequestMapping(value = "/myPath.do", params = {"active"}) - private static class MyConstrainedParameterDispatchingController { - - @RequestMapping(params = {"view", "!lang"}) - public void myOtherHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myOtherView"); - } - - @RequestMapping(method = RequestMethod.GET, params = {"view=my", "lang=de"}) - public void myLangHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myLangView"); - } - } - - @Controller - @RequestMapping(value = "/*.do", method = RequestMethod.POST, params = "myParam=myValue") - private static class MyPostMethodNameDispatchingController extends MethodNameDispatchingController { - - } - - @Controller - @RequestMapping("/myApp/*") - private static class MyRelativePathDispatchingController { - - @RequestMapping - public void myHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myView"); - } - - @RequestMapping("*Other") - public void myOtherHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myOtherView"); - } - - @RequestMapping("myLang") - public void myLangHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myLangView"); - } - - @RequestMapping("surprise") - public void mySurpriseHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("mySurpriseView"); - } - } - - @Controller - private static class MyRelativeMethodPathDispatchingController { - - @RequestMapping("**/myHandle") - public void myHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myView"); - } - - @RequestMapping("/**/*Other") - public void myOtherHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myOtherView"); - } - - @RequestMapping("**/myLang") - public void myLangHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("myLangView"); - } - - @RequestMapping("/**/surprise") - public void mySurpriseHandle(HttpServletResponse response) throws IOException { - response.getWriter().write("mySurpriseView"); - } - } - - @Controller - private static class MyNullCommandController { - - @ModelAttribute - public TestBean getTestBean() { - return null; - } - - @ModelAttribute - public Principal getPrincipal() { - return new TestPrincipal(); - } - - @RequestMapping("/myPath") - public void handle(@ModelAttribute TestBean testBean, - Errors errors, - @ModelAttribute TestPrincipal modelPrinc, - OtherPrincipal requestPrinc, - Writer writer) throws IOException { - assertNull(testBean); - assertNotNull(modelPrinc); - assertNotNull(requestPrinc); - assertFalse(errors.hasErrors()); - errors.reject("myCode"); - writer.write("myView"); - } - } - - private static class TestPrincipal implements Principal { - - @Override - public String getName() { - return "test"; - } - } - - private static class OtherPrincipal implements Principal { - - @Override - public String getName() { - return "other"; - } - } - - private static class TestViewResolver implements ViewResolver { - - @Override - public View resolveViewName(final String viewName, Locale locale) throws Exception { - return new View() { - @Override - public String getContentType() { - return null; - } - - @Override - @SuppressWarnings({"unchecked", "deprecation"}) - public void render(Map model, HttpServletRequest request, HttpServletResponse response) - throws Exception { - TestBean tb = (TestBean) model.get("testBean"); - if (tb == null) { - tb = (TestBean) model.get("myCommand"); - } - if (tb.getName() != null && tb.getName().endsWith("myDefaultName")) { - assertEquals(107, tb.getDate().getYear()); - } - Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean"); - if (errors == null) { - errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "myCommand"); - } - if (errors.hasFieldErrors("date")) { - throw new IllegalStateException(); - } - if (model.containsKey("ITestBean")) { - assertTrue(model.get(BindingResult.MODEL_KEY_PREFIX + "ITestBean") instanceof Errors); - } - List testBeans = (List) model.get("testBeanList"); - if (errors.hasFieldErrors("age")) { - response.getWriter() - .write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() + - "-" + testBeans.get(0).getName() + "-" + model.get("myKey") + - (model.containsKey("yourKey") ? "-" + model.get("yourKey") : "")); - } - else { - response.getWriter().write(viewName + "-" + tb.getName() + "-" + tb.getAge() + "-" + - errors.getFieldValue("name") + "-" + errors.getFieldValue("age")); - } - } - }; - } - } - - public static class ModelExposingViewResolver implements ViewResolver { - - @Override - public View resolveViewName(final String viewName, Locale locale) throws Exception { - return new View() { - @Override - public String getContentType() { - return null; - } - @Override - public void render(Map model, HttpServletRequest request, HttpServletResponse response) { - request.setAttribute("viewName", viewName); - request.getSession().setAttribute("model", model); - } - }; - } - } - - public static class ParentController { - - @RequestMapping(method = RequestMethod.GET) - public void doGet(HttpServletRequest req, HttpServletResponse resp) { - } - } - - @Controller - @RequestMapping("/child/test") - public static class ChildController extends ParentController { - - @RequestMapping(method = RequestMethod.GET) - public void doGet(HttpServletRequest req, HttpServletResponse resp, @RequestParam("childId") String id) { - } - } - - @Controller - @Target({ElementType.TYPE}) - @Retention(RetentionPolicy.RUNTIME) - public @interface MyControllerAnnotation { - } - - @MyControllerAnnotation - public static class CustomAnnotationController { - - @RequestMapping("/myPath.do") - public void myHandle() { - } - } - - @Controller - public static class RequiredParamController { - - @RequestMapping("/myPath.do") - public void myHandle(@RequestParam(value = "id", required = true) int id, - @RequestHeader(value = "header", required = true) String header) { - } - } - - @Controller - public static class OptionalParamController { - - @RequestMapping("/myPath.do") - public void myHandle(@RequestParam(required = false) String id, - @RequestParam(required = false) boolean flag, - @RequestHeader(value = "header", required = false) String header, - HttpServletResponse response) throws IOException { - response.getWriter().write(String.valueOf(id) + "-" + flag + "-" + String.valueOf(header)); - } - } - - @Controller - public static class DefaultValueParamController { - - @RequestMapping("/myPath.do") - public void myHandle(@RequestParam(value = "id", defaultValue = "foo") String id, - @RequestParam(value = "otherId", defaultValue = "") String id2, - @RequestHeader(defaultValue = "bar") String header, - HttpServletResponse response) throws IOException { - response.getWriter().write(String.valueOf(id) + "-" + String.valueOf(id2) + "-" + String.valueOf(header)); - } - } - - @Controller - public static class DefaultExpressionValueParamController { - - @RequestMapping("/myPath.do") - public void myHandle(@RequestParam(value = "id", defaultValue = "${myKey}") String id, - @RequestHeader(defaultValue = "#{systemProperties.myHeader}") String header, - @Value("#{request.contextPath}") String contextPath, - HttpServletResponse response) throws IOException { - response.getWriter().write(String.valueOf(id) + "-" + String.valueOf(header) + "-" + contextPath); - } - } - - @Controller - public static class NestedSetController { - - @RequestMapping("/myPath.do") - public void myHandle(GenericBean gb, HttpServletResponse response) throws Exception { - response.getWriter().write(gb.getTestBeanSet().toString() + "-" + - gb.getTestBeanSet().iterator().next().getClass().getName()); - } - } - - public static class TestBeanConverter implements Converter { - - @Override - public ITestBean convert(String source) { - return new TestBean(source); - } - } - - @Controller - public static class MethodNotAllowedController { - - @RequestMapping(value = "/myPath.do", method = RequestMethod.DELETE) - public void delete() { - } - - @RequestMapping(value = "/myPath.do", method = RequestMethod.HEAD) - public void head() { - } - - @RequestMapping(value = "/myPath.do", method = RequestMethod.OPTIONS) - public void options() { - } - - @RequestMapping(value = "/myPath.do", method = RequestMethod.POST) - public void post() { - } - - @RequestMapping(value = "/myPath.do", method = RequestMethod.PUT) - public void put() { - } - - @RequestMapping(value = "/myPath.do", method = RequestMethod.TRACE) - public void trace() { - } - - @RequestMapping(value = "/otherPath.do", method = RequestMethod.GET) - public void get() { - } - } - - @Controller - public static class PathOrderingController { - - @RequestMapping(value = {"/dir/myPath1.do", "/**/*.do"}) - public void method1(Writer writer) throws IOException { - writer.write("method1"); - } - - @RequestMapping("/dir/*.do") - public void method2(Writer writer) throws IOException { - writer.write("method2"); - } - } - - @Controller - public static class RequestResponseBodyController { - - @RequestMapping(value = "/something", method = RequestMethod.PUT) - @ResponseBody - public String handle(@RequestBody String body) throws IOException { - return body; - } - } - - @Controller - public static class ResponseBodyVoidController { - - @RequestMapping("/something") - @ResponseBody - public void handle() throws IOException { - } - } - - @Controller - public static class RequestBodyArgMismatchController { - - @RequestMapping(value = "/something", method = RequestMethod.PUT) - public void handle(@RequestBody A a) throws IOException { - } - } - - @XmlRootElement - public static class A { - - } - - @XmlRootElement - public static class B { - - } - - - public static class NotReadableMessageConverter implements HttpMessageConverter { - - @Override - public boolean canRead(Class clazz, MediaType mediaType) { - return true; - } - - @Override - public boolean canWrite(Class clazz, MediaType mediaType) { - return true; - } - - @Override - public List getSupportedMediaTypes() { - return Collections.singletonList(new MediaType("application", "pdf")); - } - - @Override - public Object read(Class clazz, HttpInputMessage inputMessage) - throws IOException, HttpMessageNotReadableException { - throw new HttpMessageNotReadableException("Could not read"); - } - - @Override - public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) - throws IOException, HttpMessageNotWritableException { - throw new UnsupportedOperationException("Not implemented"); - } - } - - public static class SimpleMessageConverter implements HttpMessageConverter { - - private final List supportedMediaTypes; - - public SimpleMessageConverter(MediaType... supportedMediaTypes) { - this.supportedMediaTypes = Arrays.asList(supportedMediaTypes); - } - - @Override - public boolean canRead(Class clazz, MediaType mediaType) { - return supportedMediaTypes.contains(mediaType); - } - - @Override - public boolean canWrite(Class clazz, MediaType mediaType) { - return supportedMediaTypes.contains(mediaType); - } - - @Override - public List getSupportedMediaTypes() { - return supportedMediaTypes; - } - - @Override - public Object read(Class clazz, HttpInputMessage inputMessage) - throws IOException, HttpMessageNotReadableException { - return null; - } - - @Override - public void write(Object o, MediaType contentType, HttpOutputMessage outputMessage) - throws IOException, HttpMessageNotWritableException { - outputMessage.getHeaders().setContentType(contentType); - outputMessage.getBody(); // force a header write - } - } - - @Controller - public static class ContentTypeHeadersController { - - @RequestMapping(value = "/something", headers = "content-type=application/pdf") - public void handlePdf(Writer writer) throws IOException { - writer.write("pdf"); - } - - @RequestMapping(value = "/something", headers = "content-type=text/*") - public void handleHtml(Writer writer) throws IOException { - writer.write("text"); - } - } - - @Controller - public static class NegatedContentTypeHeadersController { - - @RequestMapping(value = "/something", headers = "content-type=application/pdf") - public void handlePdf(Writer writer) throws IOException { - writer.write("pdf"); - } - - @RequestMapping(value = "/something", headers = "content-type!=application/pdf") - public void handleNonPdf(Writer writer) throws IOException { - writer.write("non-pdf"); - } - - } - - @Controller - public static class AcceptHeadersController { - - @RequestMapping(value = "/something", headers = "accept=text/html") - public void handleHtml(Writer writer) throws IOException { - writer.write("html"); - } - - @RequestMapping(value = "/something", headers = "accept=application/xml") - public void handleXml(Writer writer) throws IOException { - writer.write("xml"); - } - } - - @Controller - public static class ResponseStatusController { - - @RequestMapping("/something") - @ResponseStatus(code = HttpStatus.CREATED, reason = "It's alive!") - public void handle(Writer writer) throws IOException { - writer.write("something"); - } - } - - @Controller - public static class ModelAndViewResolverController { - - @RequestMapping("/") - public MySpecialArg handle() { - return new MySpecialArg("foo"); - } - } - - public static class MyModelAndViewResolver implements ModelAndViewResolver { - - @Override - public ModelAndView resolveModelAndView(Method handlerMethod, - Class handlerType, - Object returnValue, - ExtendedModelMap implicitModel, - NativeWebRequest webRequest) { - if (returnValue instanceof MySpecialArg) { - return new ModelAndView(new View() { - @Override - public String getContentType() { - return "text/html"; - } - - @Override - public void render(Map model, HttpServletRequest request, HttpServletResponse response) - throws Exception { - response.getWriter().write("myValue"); - } - - }); - } - return UNRESOLVED; - } - } - - @Controller - @RequestMapping("/test*") - private static class AmbiguousParamsController { - - @RequestMapping(method = RequestMethod.GET) - public void noParams(Writer writer) throws IOException { - writer.write("noParams"); - } - - @RequestMapping(params = "myParam") - public void param(@RequestParam("myParam") int myParam, Writer writer) throws IOException { - writer.write("myParam-" + myParam); - } - } - - @Controller - @RequestMapping("/test*") - public static class BindingCookieValueController { - - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.initBeanPropertyAccess(); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - - @RequestMapping(method = RequestMethod.GET) - public void handle(@CookieValue("date") Date date, Writer writer) throws IOException { - assertEquals("Invalid path variable value", new GregorianCalendar(2008, 10, 18).getTime(), date); - Calendar c = new GregorianCalendar(); - c.setTime(date); - writer.write("test-" + c.get(Calendar.YEAR)); - } - } - - public interface TestController { - - ModelAndView method(T object); - } - - public static class MyEntity { - - } - - @Controller - public static class TestControllerImpl implements TestController { - - @Override - @RequestMapping("/method") - public ModelAndView method(MyEntity object) { - return new ModelAndView("/something"); - } - } - - @Controller - public static class RequestParamMapController { - - @RequestMapping("/map") - public void map(@RequestParam Map params, Writer writer) throws IOException { - for (Iterator> it = params.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - writer.write(entry.getKey() + "=" + entry.getValue()); - if (it.hasNext()) { - writer.write(','); - } - - } - } - - @RequestMapping("/multiValueMap") - public void multiValueMap(@RequestParam MultiValueMap params, Writer writer) - throws IOException { - for (Iterator>> it1 = params.entrySet().iterator(); it1.hasNext();) { - Map.Entry> entry = it1.next(); - writer.write(entry.getKey() + "=["); - for (Iterator it2 = entry.getValue().iterator(); it2.hasNext();) { - String value = it2.next(); - writer.write(value); - if (it2.hasNext()) { - writer.write(','); - } - } - writer.write(']'); - if (it1.hasNext()) { - writer.write(','); - } - } - } - } - - @Controller - public static class RequestHeaderMapController { - - @RequestMapping("/map") - public void map(@RequestHeader Map headers, Writer writer) throws IOException { - for (Iterator> it = headers.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - writer.write(entry.getKey() + "=" + entry.getValue()); - if (it.hasNext()) { - writer.write(','); - } - - } - } - - @RequestMapping("/multiValueMap") - public void multiValueMap(@RequestHeader MultiValueMap headers, Writer writer) - throws IOException { - for (Iterator>> it1 = headers.entrySet().iterator(); it1.hasNext();) { - Map.Entry> entry = it1.next(); - writer.write(entry.getKey() + "=["); - for (Iterator it2 = entry.getValue().iterator(); it2.hasNext();) { - String value = it2.next(); - writer.write(value); - if (it2.hasNext()) { - writer.write(','); - } - } - writer.write(']'); - if (it1.hasNext()) { - writer.write(','); - } - } - } - - @RequestMapping("/httpHeaders") - public void httpHeaders(@RequestHeader HttpHeaders headers, Writer writer) throws IOException { - assertEquals("Invalid Content-Type", new MediaType("text", "html"), headers.getContentType()); - multiValueMap(headers, writer); - } - - } - - @Controller - public interface IMyController { - - @RequestMapping("/handle") - void handle(Writer writer, @RequestParam(value="p", required=false) String param) throws IOException; - } - - @Controller - public static class IMyControllerImpl implements IMyController { - - @Override - public void handle(Writer writer, @RequestParam(value="p", required=false) String param) throws IOException { - writer.write("handle " + param); - } - } - - public static abstract class MyAbstractController { - - @RequestMapping("/handle") - public abstract void handle(Writer writer) throws IOException; - } - - @Controller - public static class MyAbstractControllerImpl extends MyAbstractController { - - @Override - public void handle(Writer writer) throws IOException { - writer.write("handle"); - } - } - - @Controller - public static class TrailingSlashController { - - @RequestMapping(value = "/", method = RequestMethod.GET) - public void root(Writer writer) throws IOException { - writer.write("root"); - } - - @RequestMapping(value = "/{templatePath}/", method = RequestMethod.GET) - public void templatePath(Writer writer) throws IOException { - writer.write("templatePath"); - } - } - - @Controller - public static class ResponseEntityController { - - @RequestMapping("/foo") - public ResponseEntity foo(HttpEntity requestEntity) throws UnsupportedEncodingException { - assertNotNull(requestEntity); - assertEquals("MyValue", requestEntity.getHeaders().getFirst("MyRequestHeader")); - String requestBody = new String(requestEntity.getBody(), "UTF-8"); - assertEquals("Hello World", requestBody); - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set("MyResponseHeader", "MyValue"); - return new ResponseEntity(requestBody, responseHeaders, HttpStatus.CREATED); - } - - @RequestMapping("/bar") - public ResponseEntity bar() { - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.set("MyResponseHeader", "MyValue"); - return new ResponseEntity(responseHeaders, HttpStatus.NOT_FOUND); - } - - } - - @Controller - public static class CustomMapEditorController { - - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.initBeanPropertyAccess(); - binder.registerCustomEditor(Map.class, new CustomMapEditor()); - } - - @RequestMapping("/handle") - public void handle(@RequestParam("map") Map map, Writer writer) throws IOException { - writer.write("test-" + map); - } - } - - public static class CustomMapEditor extends PropertyEditorSupport { - - @Override - public void setAsText(String text) throws IllegalArgumentException { - if (StringUtils.hasText(text)) { - setValue(Collections.singletonMap("foo", text)); - } - else { - setValue(null); - } - } - - } - - @Controller - public static class MultipartController { - - @InitBinder - public void initBinder(WebDataBinder binder) { - binder.registerCustomEditor(String.class, new StringMultipartFileEditor()); - } - - @RequestMapping("/singleString") - public void processMultipart(@RequestParam("content") String content, HttpServletResponse response) throws IOException { - response.getWriter().write(content); - } - - @RequestMapping("/stringArray") - public void processMultipart(@RequestParam("content") String[] content, HttpServletResponse response) throws IOException { - response.getWriter().write(StringUtils.arrayToDelimitedString(content, "-")); - } - } - - @Controller - public static class CsvController { - - @RequestMapping("/singleInteger") - public void processCsv(@RequestParam("content") Integer content, HttpServletResponse response) throws IOException { - response.getWriter().write(content.toString()); - } - - @RequestMapping("/integerArray") - public void processCsv(@RequestParam("content") Integer[] content, HttpServletResponse response) throws IOException { - response.getWriter().write(StringUtils.arrayToDelimitedString(content, "-")); - } - - @RequestMapping("/integerSet") - public void processCsv(@RequestParam("content") Set content, HttpServletResponse response) throws IOException { - assertThat(content.iterator().next(), instanceOf(Integer.class)); - response.getWriter().write(StringUtils.collectionToDelimitedString(content, "-")); - } - } - - @Controller - @RequestMapping("/t1") - protected static class NoPathGetAndM2PostController { - @RequestMapping(method = RequestMethod.GET) - public void handle1(Writer writer) throws IOException { - writer.write("handle1"); - } - - @RequestMapping(value = "/m2", method = RequestMethod.POST) - public void handle2(Writer writer) throws IOException { - writer.write("handle2"); - } - } - - @Controller - static class HeadersConditionController { - - @RequestMapping(value = "/", method = RequestMethod.GET) - public String home() { - return "home"; - } - - @RequestMapping(value = "/", method = RequestMethod.GET, headers="Accept=application/json") - @ResponseBody - public String homeJson() { - return "homeJson"; - } - } - - @Controller - static class RedirectAttributesController { - - @RequestMapping(value = "/") - public void handle(RedirectAttributes redirectAttrs) { - } - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtilsTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtilsTests.java deleted file mode 100644 index e3c8ff7e4e..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationMappingUtilsTests.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright 2002-2012 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.servlet.mvc.annotation; - -import org.junit.Test; - -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.web.bind.annotation.RequestMethod; - -import static org.junit.Assert.*; - -/** - * @author Arjen Poutsma - */ -@Deprecated -public class ServletAnnotationMappingUtilsTests { - - @Test - public void checkRequestMethodMatch() { - RequestMethod[] methods = new RequestMethod[]{RequestMethod.GET, RequestMethod.POST}; - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - boolean result = ServletAnnotationMappingUtils.checkRequestMethod(methods, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkRequestMethodNoMatch() { - RequestMethod[] methods = new RequestMethod[]{RequestMethod.GET, RequestMethod.POST}; - MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/"); - boolean result = ServletAnnotationMappingUtils.checkRequestMethod(methods, request); - assertFalse("Invalid request method result", result); - } - - @Test - public void checkParametersSimpleMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "value1"); - String[] params = new String[]{"param1", "!param2"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkParametersSimpleNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "value1"); - request.addParameter("param2", "value2"); - String[] params = new String[]{"param1", "!param2"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertFalse("Invalid request method result", result); - } - - @Test - public void checkParametersKeyValueMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "value1"); - String[] params = new String[]{"param1=value1"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkParametersKeyValueNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "value1"); - String[] params = new String[]{"param1=foo"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertFalse("Invalid request method result", result); - } - - @Test - public void checkParametersNegatedValueMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "value1"); - String[] params = new String[]{"param1!=foo"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkParametersNegatedValueNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "foo"); - String[] params = new String[]{"param1!=foo"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertFalse("Invalid request method result", result); - } - - @Test - public void checkParametersCompositeNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addParameter("param1", "foo"); - request.addParameter("param2", "foo"); - String[] params = new String[]{"param1=foo", "param2!=foo"}; - boolean result = ServletAnnotationMappingUtils.checkParameters(params, request); - assertFalse("[SPR-8059] Invalid request method result", result); - } - - @Test - public void checkHeadersSimpleMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("header1", "value1"); - String[] headers = new String[]{"header1", "!header2"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkHeadersSimpleNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("header1", "value1"); - request.addHeader("header2", "value2"); - String[] headers = new String[]{"header1", "!header2"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertFalse("Invalid request method result", result); - } - - @Test - public void checkHeadersKeyValueMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("header1", "value1"); - String[] headers = new String[]{"header1=value1"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkHeadersKeyValueNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("header1", "value1"); - String[] headers = new String[]{"header1=foo"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertFalse("Invalid request method result", result); - } - - // SPR-8862 - - @Test - public void checkHeadersKeyValueNoMatchWithNegation() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("Accept-Encoding", "gzip"); - String[] headers1 = new String[]{"Accept-Encoding!=gzip"}; - String[] headers2 = new String[]{"Accept-Encoding=gzip"}; - assertFalse(ServletAnnotationMappingUtils.checkHeaders(headers1, request)); - assertTrue(ServletAnnotationMappingUtils.checkHeaders(headers2, request)); - } - - @Test - public void checkHeadersAcceptMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("Accept", "application/pdf, text/html"); - String[] headers = new String[]{"accept=text/html, application/*"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertTrue("Invalid request method result", result); - } - - @Test - public void checkHeadersAcceptNoMatch() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("Accept", "application/pdf, text/html"); - String[] headers = new String[]{"accept=audio/basic, application/xml"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertFalse("Invalid request method result", result); - } - - @Test - public void checkHeadersAcceptNoMatchWithNegation() { - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/"); - request.addHeader("Accept", "application/pdf"); - String[] headers = new String[]{"accept!=application/pdf"}; - boolean result = ServletAnnotationMappingUtils.checkHeaders(headers, request); - assertFalse("Invalid request method result", result); - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Controller.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Controller.java deleted file mode 100644 index 128c6fa76b..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Controller.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.springframework.web.servlet.mvc.annotation; - -import java.awt.Color; -import java.util.List; - -import org.springframework.stereotype.Controller; -import org.springframework.util.Assert; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; - -@Controller -public class Spr7766Controller { - - @RequestMapping("/colors") - public void handler(@RequestParam List colors) { - Assert.isTrue(colors.size() == 2); - Assert.isTrue(colors.get(0).equals(Color.WHITE)); - Assert.isTrue(colors.get(1).equals(Color.BLACK)); - } -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Tests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Tests.java deleted file mode 100644 index 7feeb186c0..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7766Tests.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2002-2012 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.servlet.mvc.annotation; - -import java.awt.Color; - -import org.junit.Test; - -import org.springframework.core.convert.converter.Converter; -import org.springframework.core.convert.support.DefaultConversionService; -import org.springframework.core.convert.support.GenericConversionService; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; - -public class Spr7766Tests { - - @Test - @Deprecated - public void test() throws Exception { - AnnotationMethodHandlerAdapter adapter = new AnnotationMethodHandlerAdapter(); - ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer(); - GenericConversionService service = new DefaultConversionService(); - service.addConverter(new ColorConverter()); - binder.setConversionService(service); - adapter.setWebBindingInitializer(binder); - Spr7766Controller controller = new Spr7766Controller(); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setRequestURI("/colors"); - request.setPathInfo("/colors"); - request.addParameter("colors", "#ffffff,000000"); - MockHttpServletResponse response = new MockHttpServletResponse(); - adapter.handle(request, response, controller); - } - - public class ColorConverter implements Converter { - @Override - public Color convert(String source) { if (!source.startsWith("#")) source = "#" + source; return Color.decode(source); } - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java deleted file mode 100644 index 1cc9ff91ba..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/Spr7839Tests.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright 2002-2012 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.servlet.mvc.annotation; - -import java.util.List; -import java.util.Map; - -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import org.springframework.core.convert.converter.Converter; -import org.springframework.core.convert.support.DefaultConversionService; -import org.springframework.core.convert.support.GenericConversionService; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; - -import static org.junit.Assert.*; - -@Deprecated -public class Spr7839Tests { - - AnnotationMethodHandlerAdapter adapter = new AnnotationMethodHandlerAdapter(); - - MockHttpServletRequest request = new MockHttpServletRequest(); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - Spr7839Controller controller = new Spr7839Controller(); - - @Before - public void setUp() { - ConfigurableWebBindingInitializer binder = new ConfigurableWebBindingInitializer(); - GenericConversionService service = new DefaultConversionService(); - service.addConverter(new Converter() { - @Override - public NestedBean convert(String source) { - return new NestedBean(source); - } - }); - binder.setConversionService(service); - adapter.setWebBindingInitializer(binder); - } - - @Test - public void object() throws Exception { - request.setRequestURI("/nested"); - request.addParameter("nested", "Nested"); - adapter.handle(request, response, controller); - } - - @Test - public void list() throws Exception { - request.setRequestURI("/nested/list"); - request.addParameter("nested.list", "Nested1,Nested2"); - adapter.handle(request, response, controller); - } - - @Test - public void listElement() throws Exception { - request.setRequestURI("/nested/listElement"); - request.addParameter("nested.list[0]", "Nested"); - adapter.handle(request, response, controller); - } - - @Test - public void listElementAutogrowObject() throws Exception { - request.setRequestURI("/nested/listElement"); - request.addParameter("nested.list[0].foo", "Nested"); - adapter.handle(request, response, controller); - } - - @Test - @Ignore - public void listElementAutogrowOutOfMemory() throws Exception { - request.setRequestURI("/nested/listElement"); - request.addParameter("nested.list[1000000000].foo", "Nested"); - adapter.handle(request, response, controller); - } - - @Test - public void listOfLists() throws Exception { - request.setRequestURI("/nested/listOfLists"); - request.addParameter("nested.listOfLists[0]", "Nested1,Nested2"); - adapter.handle(request, response, controller); - } - - @Test - public void listOfListsElement() throws Exception { - request.setRequestURI("/nested/listOfListsElement"); - request.addParameter("nested.listOfLists[0][0]", "Nested"); - adapter.handle(request, response, controller); - } - - @Test - public void listOfListsElementAutogrowObject() throws Exception { - request.setRequestURI("/nested/listOfListsElement"); - request.addParameter("nested.listOfLists[0][0].foo", "Nested"); - adapter.handle(request, response, controller); - } - - @Test - @Ignore - public void arrayOfLists() throws Exception { - // TODO TypeDescriptor not capable of accessing nested element type for arrays - request.setRequestURI("/nested/arrayOfLists"); - request.addParameter("nested.arrayOfLists[0]", "Nested1,Nested2"); - adapter.handle(request, response, controller); - } - - @Test - public void map() throws Exception { - request.setRequestURI("/nested/map"); - request.addParameter("nested.map['apple'].foo", "bar"); - adapter.handle(request, response, controller); - } - - @Test - public void mapOfLists() throws Exception { - request.setRequestURI("/nested/mapOfLists"); - request.addParameter("nested.mapOfLists['apples'][0]", "1"); - adapter.handle(request, response, controller); - } - - @Controller - public static class Spr7839Controller { - - @RequestMapping("/nested") - public void handler(JavaBean bean) { - assertEquals("Nested", bean.nested.foo); - } - - @RequestMapping("/nested/list") - public void handlerList(JavaBean bean) { - assertEquals("Nested2", bean.nested.list.get(1).foo); - } - - @RequestMapping("/nested/listElement") - public void handlerListElement(JavaBean bean) { - assertEquals("Nested", bean.nested.list.get(0).foo); - } - - @RequestMapping("/nested/listOfLists") - public void handlerListOfLists(JavaBean bean) { - assertEquals("Nested2", bean.nested.listOfLists.get(0).get(1).foo); - } - - @RequestMapping("/nested/listOfListsElement") - public void handlerListOfListsElement(JavaBean bean) { - assertEquals("Nested", bean.nested.listOfLists.get(0).get(0).foo); - } - - @RequestMapping("/nested/arrayOfLists") - public void handlerArrayOfLists(JavaBean bean) { - assertEquals("Nested2", bean.nested.arrayOfLists[0].get(1).foo); - } - - @RequestMapping("/nested/map") - public void handlerMap(JavaBean bean) { - assertEquals("bar", bean.nested.map.get("apple").foo); - } - - @RequestMapping("/nested/mapOfLists") - public void handlerMapOfLists(JavaBean bean) { - assertEquals(new Integer(1), bean.nested.mapOfLists.get("apples").get(0)); - } - - } - - public static class JavaBean { - - private NestedBean nested; - - public NestedBean getNested() { - return nested; - } - - public void setNested(NestedBean nested) { - this.nested = nested; - } - - - } - - public static class NestedBean { - - private String foo; - - private List list; - - private List> listOfLists; - - private List[] arrayOfLists; - - private Map map; - - private Map> mapOfLists; - - public NestedBean() { - - } - - public NestedBean(String foo) { - this.foo = foo; - } - - public String getFoo() { - return foo; - } - - public void setFoo(String foo) { - this.foo = foo; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public List> getListOfLists() { - return listOfLists; - } - - public void setListOfLists(List> listOfLists) { - this.listOfLists = listOfLists; - } - - public List[] getArrayOfLists() { - return arrayOfLists; - } - - public void setArrayOfLists(List[] arrayOfLists) { - this.arrayOfLists = arrayOfLists; - } - - public Map> getMapOfLists() { - return mapOfLists; - } - - public void setMapOfLists(Map> mapOfLists) { - this.mapOfLists = mapOfLists; - } - - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java deleted file mode 100644 index ca2df2ca23..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/UriTemplateServletAnnotationControllerTests.java +++ /dev/null @@ -1,713 +0,0 @@ -/* - * Copyright 2002-2014 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.servlet.mvc.annotation; - -import java.io.IOException; -import java.io.Writer; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Test; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.beans.propertyeditors.CustomDateEditor; -import org.springframework.mock.web.test.MockHttpServletRequest; -import org.springframework.mock.web.test.MockHttpServletResponse; -import org.springframework.mock.web.test.MockServletConfig; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.WebDataBinder; -import org.springframework.web.bind.annotation.InitBinder; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; -import org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping; - -import static org.junit.Assert.*; - -/** - * @author Arjen Poutsma - * @author Rossen Stoyanchev - */ -@SuppressWarnings("deprecation") -public class UriTemplateServletAnnotationControllerTests { - - private DispatcherServlet servlet; - - @Test - public void simple() throws Exception { - initServlet(SimpleUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42", response.getContentAsString()); - } - - @Test - public void multiple() throws Exception { - initServlet(MultipleUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21-other"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42-21-other", response.getContentAsString()); - } - - @Test - public void binding() throws Exception { - initServlet(BindingUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-11-18"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(200, response.getStatus()); - - request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-foo-bar"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(400, response.getStatus()); - - initServlet(NonBindingUriTemplateController.class); - request = new MockHttpServletRequest("GET", "/hotels/42/dates/2008-foo-bar"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(500, response.getStatus()); - } - - @Test - @SuppressWarnings("serial") - public void doubles() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(DoubleController.class)); - RootBeanDefinition mappingDef = new RootBeanDefinition(DefaultAnnotationHandlerMapping.class); - mappingDef.getPropertyValues().add("useDefaultSuffixPattern", false); - wac.registerBeanDefinition("handlerMapping", mappingDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/lat/1.2/long/3.4"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - - assertEquals("latitude-1.2-longitude-3.4", response.getContentAsString()); - } - - @Test - public void ambiguous() throws Exception { - initServlet(AmbiguousUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/new"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("specific", response.getContentAsString()); - } - - @Test - public void relative() throws Exception { - initServlet(RelativePathUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42-21", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/hotels/42/bookings/21.html"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42-21", response.getContentAsString()); - } - - @Test - public void extension() throws Exception { - initServlet(SimpleUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42.xml"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42", response.getContentAsString()); - - } - - @Test - public void typeConversionError() throws Exception { - initServlet(SimpleUriTemplateController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("Invalid response status code", HttpServletResponse.SC_BAD_REQUEST, response.getStatus()); - } - - @Test - public void explicitSubPath() throws Exception { - initServlet(ExplicitSubPathController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42", response.getContentAsString()); - } - - @Test - public void implicitSubPath() throws Exception { - initServlet(ImplicitSubPathController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/42"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42", response.getContentAsString()); - } - - @Test - public void crud() throws Exception { - initServlet(CrudController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("list", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/hotels/"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("list", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/hotels"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("create", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/hotels/42"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("show-42", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/hotels/42/"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("show-42", response.getContentAsString()); - - request = new MockHttpServletRequest("PUT", "/hotels/42"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("createOrUpdate-42", response.getContentAsString()); - - request = new MockHttpServletRequest("DELETE", "/hotels/42"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("remove-42", response.getContentAsString()); - } - - @Test - public void methodNotSupported() throws Exception { - initServlet(MethodNotAllowedController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/1"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(200, response.getStatus()); - - request = new MockHttpServletRequest("POST", "/hotels/1"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(405, response.getStatus()); - - request = new MockHttpServletRequest("GET", "/hotels"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(200, response.getStatus()); - - request = new MockHttpServletRequest("POST", "/hotels"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals(405, response.getStatus()); - - - } - - @Test - public void multiPaths() throws Exception { - initServlet(MultiPathController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/category/page/5"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle4-page-5", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/category/page/5.html"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("handle4-page-5", response.getContentAsString()); - } - - - @SuppressWarnings("serial") - private void initServlet(final Class controllerclass) throws ServletException { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerclass)); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - } - - @Test - @SuppressWarnings("serial") - public void noDefaultSuffixPattern() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(ImplicitSubPathController.class)); - RootBeanDefinition mappingDef = new RootBeanDefinition(DefaultAnnotationHandlerMapping.class); - mappingDef.getPropertyValues().add("useDefaultSuffixPattern", false); - wac.registerBeanDefinition("handlerMapping", mappingDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels/hotel.with.dot"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-hotel.with.dot", response.getContentAsString()); - } - - @Test - public void customRegex() throws Exception { - initServlet(CustomRegexController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/42"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("test-42", response.getContentAsString()); - } - - // SPR-6640 - @Test - public void menuTree() throws Exception { - initServlet(MenuTreeController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/book/menu/type/M5"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("M5", response.getContentAsString()); - } - - // SPR-6876 - @Test - public void variableNames() throws Exception { - initServlet(VariableNamesController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/foo"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("foo-foo", response.getContentAsString()); - - request = new MockHttpServletRequest("DELETE", "/test/bar"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("bar-bar", response.getContentAsString()); - } - - // SPR-8543 - @Test - public void variableNamesWithUrlExtension() throws Exception { - initServlet(VariableNamesController.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/foo.json"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("foo-foo", response.getContentAsString()); - } - - // SPR-9333 - @Test - @SuppressWarnings("serial") - public void suppressDefaultSuffixPattern() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(VariableNamesController.class)); - RootBeanDefinition mappingDef = new RootBeanDefinition(DefaultAnnotationHandlerMapping.class); - mappingDef.getPropertyValues().add("useDefaultSuffixPattern", false); - wac.registerBeanDefinition("handlerMapping", mappingDef); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test/jsmith@mail.com"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("foo-jsmith@mail.com", response.getContentAsString()); - } - - // SPR-6906 - @Test - @SuppressWarnings("serial") - public void controllerClassName() throws Exception { - servlet = new DispatcherServlet() { - @Override - protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) - throws BeansException { - GenericWebApplicationContext wac = new GenericWebApplicationContext(); - wac.registerBeanDefinition("controller", new RootBeanDefinition(ControllerClassNameController.class)); - RootBeanDefinition mapping = new RootBeanDefinition(ControllerClassNameHandlerMapping.class); - mapping.getPropertyValues().add("excludedPackages", null); - wac.registerBeanDefinition("handlerMapping", mapping); - wac.refresh(); - return wac; - } - }; - servlet.init(new MockServletConfig()); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/controllerclassname/bar"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("plain-bar", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/controllerclassname/bar.pdf"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("pdf-bar", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/controllerclassname/bar.do"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("plain-bar", response.getContentAsString()); - } - - // SPR-6978 - @Test - public void doIt() throws Exception { - initServlet(Spr6978Controller.class); - - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo/100"); - MockHttpServletResponse response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("loadEntity:foo:100", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/foo/100"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("publish:foo:100", response.getContentAsString()); - - request = new MockHttpServletRequest("GET", "/module/100"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("loadModule:100", response.getContentAsString()); - - request = new MockHttpServletRequest("POST", "/module/100"); - response = new MockHttpServletResponse(); - servlet.service(request, response); - assertEquals("publish:module:100", response.getContentAsString()); - - } - - - // Controllers - - @Controller - public static class SimpleUriTemplateController { - - @RequestMapping("/{root}") - public void handle(@PathVariable("root") int root, Writer writer) throws IOException { - assertEquals("Invalid path variable value", 42, root); - writer.write("test-" + root); - } - - } - - @Controller - public static class MultipleUriTemplateController { - - @RequestMapping("/hotels/{hotel}/bookings/{booking}-{other}") - public void handle(@PathVariable("hotel") String hotel, - @PathVariable int booking, - @PathVariable String other, - Writer writer) throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", 21, booking); - writer.write("test-" + hotel + "-" + booking + "-" + other); - } - - } - - @Controller - public static class BindingUriTemplateController { - - @InitBinder - public void initBinder(WebDataBinder binder, @PathVariable("hotel") String hotel) { - assertEquals("Invalid path variable value", "42", hotel); - binder.initBeanPropertyAccess(); - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - - @RequestMapping("/hotels/{hotel}/dates/{date}") - public void handle(@PathVariable("hotel") String hotel, @PathVariable Date date, Writer writer) - throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", new GregorianCalendar(2008, 10, 18).getTime(), date); - writer.write("test-" + hotel); - } - - } - - @Controller - public static class NonBindingUriTemplateController { - - @RequestMapping("/hotels/{hotel}/dates/{date}") - public void handle(@PathVariable("hotel") String hotel, @PathVariable Date date, Writer writer) - throws IOException { - } - - } - - @Controller - @RequestMapping("/hotels/{hotel}") - public static class RelativePathUriTemplateController { - - @RequestMapping("bookings/{booking}") - public void handle(@PathVariable("hotel") String hotel, @PathVariable int booking, Writer writer) - throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - assertEquals("Invalid path variable value", 21, booking); - writer.write("test-" + hotel + "-" + booking); - } - - } - - @Controller - @RequestMapping("/hotels") - public static class AmbiguousUriTemplateController { - - @RequestMapping("/{hotel}") - public void handleVars(@PathVariable("hotel") String hotel, Writer writer) throws IOException { - assertEquals("Invalid path variable value", "42", hotel); - writer.write("variables"); - } - - @RequestMapping("/new") - public void handleSpecific(Writer writer) throws IOException { - writer.write("specific"); - } - - @RequestMapping("/*") - public void handleWildCard(Writer writer) throws IOException { - writer.write("wildcard"); - } - - } - - @Controller - @RequestMapping("/hotels/*") - public static class ExplicitSubPathController { - - @RequestMapping("{hotel}") - public void handleHotel(@PathVariable String hotel, Writer writer) throws IOException { - writer.write("test-" + hotel); - } - - } - - @Controller - @RequestMapping("hotels") - public static class ImplicitSubPathController { - - @RequestMapping("{hotel}") - public void handleHotel(@PathVariable String hotel, Writer writer) throws IOException { - writer.write("test-" + hotel); - } - } - - @Controller - public static class CustomRegexController { - - @RequestMapping("/{root:\\d+}") - public void handle(@PathVariable("root") int root, Writer writer) throws IOException { - assertEquals("Invalid path variable value", 42, root); - writer.write("test-" + root); - } - - } - - @Controller - public static class DoubleController { - - @RequestMapping("/lat/{latitude}/long/{longitude}") - public void testLatLong(@PathVariable Double latitude, @PathVariable Double longitude, Writer writer) - throws IOException { - writer.write("latitude-" + latitude + "-longitude-" + longitude); - } - - } - - @Controller - @RequestMapping("hotels") - public static class CrudController { - - @RequestMapping(method = RequestMethod.GET) - public void list(Writer writer) throws IOException { - writer.write("list"); - } - - @RequestMapping(method = RequestMethod.POST) - public void create(Writer writer) throws IOException { - writer.write("create"); - } - - @RequestMapping(value = "/{hotel}", method = RequestMethod.GET) - public void show(@PathVariable String hotel, Writer writer) throws IOException { - writer.write("show-" + hotel); - } - - @RequestMapping(value = "{hotel}", method = RequestMethod.PUT) - public void createOrUpdate(@PathVariable String hotel, Writer writer) throws IOException { - writer.write("createOrUpdate-" + hotel); - } - - @RequestMapping(value = "{hotel}", method = RequestMethod.DELETE) - public void remove(@PathVariable String hotel, Writer writer) throws IOException { - writer.write("remove-" + hotel); - } - - } - - @Controller - @RequestMapping("/hotels") - public static class MethodNotAllowedController { - - @RequestMapping(method = RequestMethod.GET) - public void list(Writer writer) { - } - - @RequestMapping(method = RequestMethod.GET, value = "{hotelId}") - public void show(@PathVariable long hotelId, Writer writer) { - } - - @RequestMapping(method = RequestMethod.PUT, value = "{hotelId}") - public void createOrUpdate(@PathVariable long hotelId, Writer writer) { - } - - @RequestMapping(method = RequestMethod.DELETE, value = "/{hotelId}") - public void remove(@PathVariable long hotelId, Writer writer) { - } - } - - @Controller - @RequestMapping("/category") - public static class MultiPathController { - - @RequestMapping(value = {"/{category}/page/{page}", "/**/{category}/page/{page}"}) - public void category(@PathVariable String category, @PathVariable int page, Writer writer) throws IOException { - writer.write("handle1-"); - writer.write("category-" + category); - writer.write("page-" + page); - } - - @RequestMapping(value = {"/{category}", "/**/{category}"}) - public void category(@PathVariable String category, Writer writer) throws IOException { - writer.write("handle2-"); - writer.write("category-" + category); - } - - @RequestMapping(value = {""}) - public void category(Writer writer) throws IOException { - writer.write("handle3"); - } - - @RequestMapping(value = {"/page/{page}"}) - public void category(@PathVariable int page, Writer writer) throws IOException { - writer.write("handle4-"); - writer.write("page-" + page); - } - - } - - @RequestMapping("/*/menu/**") - public static class MenuTreeController { - - @RequestMapping("type/{var}") - public void getFirstLevelFunctionNodes(@PathVariable("var") String var, Writer writer) throws IOException { - writer.write(var); - } - } - - @Controller - @RequestMapping("/test") - public static class VariableNamesController { - - @RequestMapping(value = "/{foo}", method=RequestMethod.GET) - public void foo(@PathVariable String foo, Writer writer) throws IOException { - writer.write("foo-" + foo); - } - - @RequestMapping(value = "/{bar}", method=RequestMethod.DELETE) - public void bar(@PathVariable String bar, Writer writer) throws IOException { - writer.write("bar-" + bar); - } - } - - @Controller - public static class Spr6978Controller { - - @RequestMapping(value = "/{type}/{id}", method = RequestMethod.GET) - public void loadEntity(@PathVariable final String type, @PathVariable final long id, Writer writer) - throws IOException { - writer.write("loadEntity:" + type + ":" + id); - } - - @RequestMapping(value = "/module/{id}", method = RequestMethod.GET) - public void loadModule(@PathVariable final long id, Writer writer) throws IOException { - writer.write("loadModule:" + id); - } - - @RequestMapping(value = "/{type}/{id}", method = RequestMethod.POST) - public void publish(@PathVariable final String type, @PathVariable final long id, Writer writer) - throws IOException { - writer.write("publish:" + type + ":" + id); - } - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java index 0e20d4de81..26a0a19280 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/UriTemplateServletAnnotationControllerHandlerMethodTests.java @@ -49,14 +49,11 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.mvc.annotation.UriTemplateServletAnnotationControllerTests; import org.springframework.web.servlet.view.AbstractView; import static org.junit.Assert.*; /** - * The origin of this test class is {@link UriTemplateServletAnnotationControllerTests}. - * * Tests in this class run against the {@link HandlerMethod} infrastructure: *

            *
          • RequestMappingHandlerMapping diff --git a/src/asciidoc/core-beans.adoc b/src/asciidoc/core-beans.adoc index 7a76f3f1aa..44a1619038 100644 --- a/src/asciidoc/core-beans.adoc +++ b/src/asciidoc/core-beans.adoc @@ -2274,7 +2274,7 @@ the __scope__ of the objects created from a particular bean definition. This app powerful and flexible in that you can __choose__ the scope of the objects you create through configuration instead of having to bake in the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of -the box, the Spring Framework supports seven scopes, five of which are available only if +the box, the Spring Framework supports six scopes, five of which are available only if you use a web-aware `ApplicationContext`. The following scopes are supported out of the box. You can also create @@ -2301,11 +2301,6 @@ The following scopes are supported out of the box. You can also create | Scopes a single bean definition to the lifecycle of an HTTP `Session`. Only valid in the context of a web-aware Spring `ApplicationContext`. -| <> -| Scopes a single bean definition to the lifecycle of a global HTTP `Session`. Typically - only valid when used in a Portlet context. Only valid in the context of a web-aware - Spring `ApplicationContext`. - | <> | Scopes a single bean definition to the lifecycle of a `ServletContext`. Only valid in the context of a web-aware Spring `ApplicationContext`. @@ -2422,29 +2417,28 @@ runtime more than once, see <> [[beans-factory-scopes-other]] -=== Request, session, global session, application, and WebSocket scopes +=== Request, session, application, and WebSocket scopes -The `request`, `session`, `globalSession`, `application`, and `websocket` scopes are -__only__ available if you use a web-aware Spring `ApplicationContext` implementation -(such as `XmlWebApplicationContext`). If you use these scopes with regular Spring IoC -containers such as the `ClassPathXmlApplicationContext`, an `IllegalStateException` will -be thrown complaining about an unknown bean scope. +The `request`, `session`, `application`, and `websocket` scopes are __only__ available +if you use a web-aware Spring `ApplicationContext` implementation (such as +`XmlWebApplicationContext`). If you use these scopes with regular Spring IoC containers +such as the `ClassPathXmlApplicationContext`, an `IllegalStateException` will be thrown +complaining about an unknown bean scope. [[beans-factory-scopes-other-web-configuration]] ==== Initial web configuration -To support the scoping of beans at the `request`, `session`, `globalSession`, -`application`, and `websocket` levels (web-scoped beans), some minor initial -configuration is required before you define your beans. (This initial setup is __not__ -required for the standard scopes, `singleton` and `prototype`.) +To support the scoping of beans at the `request`, `session`, `application`, and +`websocket` levels (web-scoped beans), some minor initial configuration is +required before you define your beans. (This initial setup is __not__ required +for the standard scopes, `singleton` and `prototype`.) How you accomplish this initial setup depends on your particular Servlet environment. If you access scoped beans within Spring Web MVC, in effect, within a request that is -processed by the Spring `DispatcherServlet` or `DispatcherPortlet`, then no special -setup is necessary: `DispatcherServlet` and `DispatcherPortlet` already expose all -relevant state. +processed by the Spring `DispatcherServlet`, then no special setup is necessary: +`DispatcherServlet` already exposes all relevant state. If you use a Servlet 2.5 web container, with requests processed outside of Spring's `DispatcherServlet` (for example, when using JSF or Struts), you need to register the @@ -2562,29 +2556,6 @@ can be used to assign a component to the `session` scope. ---- -[[beans-factory-scopes-global-session]] -==== Global session scope - -Consider the following bean definition: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - ----- - -The `globalSession` scope is similar to the standard HTTP `Session` scope -(<>), and applies only in the context of -portlet-based web applications. The portlet specification defines the notion of a global -`Session` that is shared among all portlets that make up a single portlet web -application. Beans defined at the `globalSession` scope are scoped (or bound) to the -lifetime of the global portlet `Session`. - -If you write a standard Servlet-based web application and you define one or more beans -as having `globalSession` scope, the standard HTTP `Session` scope is used, and no -error is raised. - - [[beans-factory-scopes-application]] ==== Application scope @@ -2681,11 +2652,11 @@ understand the "why" as well as the "how" behind it. To create such a proxy, you insert a child `` element into a scoped bean definition (see <> and -<>). Why do definitions of beans scoped at the `request`, `session`, -`globalSession` and custom-scope levels require the `` element? -Let's examine the following singleton bean definition and contrast it with what you need -to define for the aforementioned scopes (note that the following `userPreferences` bean -definition as it stands is __incomplete__). +<>). Why do definitions of beans scoped at the `request`, `session` +and custom-scope levels require the `` element? Let's examine the +following singleton bean definition and contrast it with what you need to define for +the aforementioned scopes (note that the following `userPreferences` bean definition +as it stands is __incomplete__). [source,xml,indent=0] [subs="verbatim,quotes"] @@ -2721,7 +2692,7 @@ actually is invoking a method on the proxy. The proxy then fetches the real method invocation onto the retrieved real `UserPreferences` object. Thus you need the following, correct and complete, configuration when injecting -`request-`, `session-`, and `globalSession-scoped` beans into collaborating objects: +`request-` and `session-scoped` beans into collaborating objects: [source,xml,indent=0] [subs="verbatim,quotes"] @@ -3501,16 +3472,6 @@ dependency type: | Spring JMX notification publisher | <> -| `PortletConfigAware` -| Current `PortletConfig` the container runs in. Valid only in a web-aware Spring - `ApplicationContext` -| <> - -| `PortletContextAware` -| Current `PortletContext` the container runs in. Valid only in a web-aware Spring - `ApplicationContext` -| <> - | `ResourceLoaderAware` | Configured loader for low-level access to resources | <> @@ -7600,9 +7561,7 @@ is configured with two PropertySource objects -- one representing the set of JVM These default property sources are present for `StandardEnvironment`, for use in standalone applications. {api-spring-framework}/web/context/support/StandardServletEnvironment.html[`StandardServletEnvironment`] is populated with additional default property sources including servlet config and servlet -context parameters. {api-spring-framework}/web/portlet/context/StandardPortletEnvironment.html[`StandardPortletEnvironment`] -similarly has access to portlet config and portlet context parameters as property sources. -Both can optionally enable a {api-spring-framework}/jndi/JndiPropertySource.html[`JndiPropertySource`]. +context parameters. It can optionally enable a {api-spring-framework}/jndi/JndiPropertySource.html[`JndiPropertySource`]. See the javadocs for details. ==== diff --git a/src/asciidoc/web-portlet.adoc b/src/asciidoc/web-portlet.adoc deleted file mode 100644 index b93a642ed4..0000000000 --- a/src/asciidoc/web-portlet.adoc +++ /dev/null @@ -1,1521 +0,0 @@ -[[portlet]] -= Portlet MVC Framework - - -[[portlet-introduction]] -== Introduction - -.JSR-286 The Java Portlet Specification -**** -For more general information about portlet development, please review the -https://jcp.org/en/jsr/detail?id=286[JSR-286 Specification] itself. -**** - -In addition to supporting conventional (servlet-based) Web development, Spring also -supports JSR-286 Portlet development. As much as possible, the Portlet MVC framework is -a mirror image of the Web MVC framework, and also uses the same underlying view -abstractions and integration technology. So, be sure to review the chapters entitled -<> and <> before continuing with this chapter. - -[NOTE] -==== -Bear in mind that while the concepts of Spring MVC are the same in Spring Portlet MVC, -there are some notable differences created by the unique workflow of JSR-286 portlets. -==== - -The main way in which portlet workflow differs from servlet workflow is that the request -to the portlet can have two distinct phases: the action phase and the render phase. The -action phase is executed only once and is where any 'backend' changes or actions occur, -such as making changes in a database. The render phase then produces what is displayed -to the user each time the display is refreshed. The critical point here is that for a -single overall request, the action phase is executed only once, but the render phase may -be executed multiple times. This provides (and requires) a clean separation between the -activities that modify the persistent state of your system and the activities that -generate what is displayed to the user. - -.Spring Web Flow -**** -Spring Web Flow (SWF) aims to be the best solution for the management of web application -page flow. - -SWF integrates with existing frameworks like Spring MVC and JSF, in both Servlet and -Portlet environments. If you have a business process (or processes) that would benefit -from a conversational model as opposed to a purely request model, then SWF may be the -solution. - -SWF allows you to capture logical page flows as self-contained modules that are reusable -in different situations, and as such is ideal for building web application modules that -guide the user through controlled navigations that drive business processes. - -For more information about SWF, consult the Spring Web Flow website. -**** - -The dual phases of portlet requests are one of the real strengths of the JSR-286 -specification. For example, dynamic search results can be updated routinely on the -display without the user explicitly rerunning the search. Most other portlet MVC -frameworks attempt to completely hide the two phases from the developer and make it look -as much like traditional servlet development as possible - we think this approach -removes one of the main benefits of using portlets. So, the separation of the two phases -is preserved throughout the Spring Portlet MVC framework. The primary manifestation of -this approach is that where the servlet version of the MVC classes will have one method -that deals with the request, the portlet version of the MVC classes will have two -methods that deal with the request: one for the action phase and one for the render -phase. For example, where the servlet version of `AbstractController` has the -`handleRequestInternal(..)` method, the portlet version of `AbstractController` has -`handleActionRequestInternal(..)` and `handleRenderRequestInternal(..)` methods. - -The framework is designed around a `DispatcherPortlet` that dispatches requests to -handlers, with configurable handler mappings and view resolution, just as the -`DispatcherServlet` in the web framework does. File upload is also supported in the same -way. - -Locale resolution and theme resolution are not supported in Portlet MVC - these areas -are in the purview of the portal/portlet container and are not appropriate at the Spring -level. However, all mechanisms in Spring that depend on the locale (such as -internationalization of messages) will still function properly because -`DispatcherPortlet` exposes the current locale in the same way as `DispatcherServlet`. - - - -[[portlet-introduction-controller]] -=== Controllers - The C in MVC -The default handler is still a very simple `Controller` interface, offering just two -methods: - -* `void handleActionRequest(request,response)` -* `ModelAndView handleRenderRequest(request,response)` - -The framework also includes most of the same controller implementation hierarchy, such -as `AbstractController`, `SimpleFormController`, and so on. Data binding, command object -usage, model handling, and view resolution are all the same as in the servlet framework. - - - -[[portlet-introduction-view]] -=== Views - The V in MVC -All the view rendering capabilities of the servlet framework are used directly via a -special bridge servlet named `ViewRendererServlet`. By using this servlet, the portlet -request is converted into a servlet request and the view can be rendered using the -entire normal servlet infrastructure. This means all the existing renderers, such as -JSP, Velocity, etc., can still be used within the portlet. - - - -[[portlet-introduction-scope]] -=== Web-scoped beans -Spring Portlet MVC supports beans whose lifecycle is scoped to the current HTTP request -or HTTP `Session` (both normal and global). This is not a specific feature of Spring -Portlet MVC itself, but rather of the `WebApplicationContext` container(s) that Spring -Portlet MVC uses. These bean scopes are described in detail in -<> - - - - -[[portlet-dispatcher]] -== The DispatcherPortlet - -Portlet MVC is a request-driven web MVC framework, designed around a portlet that -dispatches requests to controllers and offers other functionality facilitating the -development of portlet applications. Spring's `DispatcherPortlet` however, does more -than just that. It is completely integrated with the Spring `ApplicationContext` and -allows you to use every other feature Spring has. - -Like ordinary portlets, the `DispatcherPortlet` is declared in the `portlet.xml` file of -your web application: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - sample - org.springframework.web.portlet.DispatcherPortlet - - text/html - view - - - Sample Portlet - - ----- - -The `DispatcherPortlet` now needs to be configured. - -In the Portlet MVC framework, each `DispatcherPortlet` has its own -`WebApplicationContext`, which inherits all the beans already defined in the Root -`WebApplicationContext`. These inherited beans can be overridden in the portlet-specific -scope, and new scope-specific beans can be defined local to a given portlet instance. - -The framework will, on initialization of a `DispatcherPortlet`, look for a file named -`[portlet-name]-portlet.xml` in the `WEB-INF` directory of your web application and -create the beans defined there (overriding the definitions of any beans defined with the -same name in the global scope). - -The config location used by the `DispatcherPortlet` can be modified through a portlet -initialization parameter (see below for details). - -The Spring `DispatcherPortlet` has a few special beans it uses, in order to be able to -process requests and render the appropriate views. These beans are included in the -Spring framework and can be configured in the `WebApplicationContext`, just as any other -bean would be configured. Each of those beans is described in more detail below. Right -now, we'll just mention them, just to let you know they exist and to enable us to go on -talking about the `DispatcherPortlet`. For most of the beans, defaults are provided so -you don't have to worry about configuring them. - -[[portlet-webappctx-special-beans-tbl]] -.Special beans in the WebApplicationContext -[cols="1,4"] -|=== -| Expression| Explanation - -| handler mapping(s) -| (<>) a list of pre- and post-processors and controllers that - will be executed if they match certain criteria (for instance a matching portlet mode - specified with the controller) - -| controller(s) -| (<>) the beans providing the actual functionality (or at least, - access to the functionality) as part of the MVC triad - -| view resolver -| (<>) capable of resolving view names to view definitions - -| multipart resolver -| (<>) offers functionality to process file uploads from HTML forms - -| handler exception resolver -| (<>) offers functionality to map exceptions to views or - implement other more complex exception handling code -|=== - -When a `DispatcherPortlet` is setup for use and a request comes in for that specific -`DispatcherPortlet`, it starts processing the request. The list below describes the -complete process a request goes through if handled by a `DispatcherPortlet`: - -. The locale returned by `PortletRequest.getLocale()` is bound to the request to let -elements in the process resolve the locale to use when processing the request (rendering -the view, preparing data, etc.). -. If a multipart resolver is specified and this is an `ActionRequest`, the request is -inspected for multiparts and if they are found, it is wrapped in a -`MultipartActionRequest` for further processing by other elements in the process. (See -<> for further information about multipart handling). -. An appropriate handler is searched for. If a handler is found, the execution chain -associated with the handler (pre-processors, post-processors, controllers) will be -executed in order to prepare a model. -. If a model is returned, the view is rendered, using the view resolver that has been -configured with the `WebApplicationContext`. If no model is returned (which could be due -to a pre- or post-processor intercepting the request, for example, for security -reasons), no view is rendered, since the request could already have been fulfilled. - -Exceptions that are thrown during processing of the request get picked up by any of the -handler exception resolvers that are declared in the `WebApplicationContext`. Using -these exception resolvers you can define custom behavior in case such exceptions get -thrown. - -You can customize Spring's `DispatcherPortlet` by adding context parameters in the -`portlet.xml` file or portlet init-parameters. The possibilities are listed below. - -[[portlet-dpp-init-params]] -.DispatcherPortlet initialization parameters -[cols="1,4"] -|=== -| Parameter| Explanation - -| `contextClass` -| Class that implements `WebApplicationContext`, which will be used to instantiate the - context used by this portlet. If this parameter isn't specified, the - `XmlPortletApplicationContext` will be used. - -| `contextConfigLocation` -| String which is passed to the context instance (specified by `contextClass`) to - indicate where context(s) can be found. The String is potentially split up into - multiple Strings (using a comma as a delimiter) to support multiple contexts (in case - of multiple context locations, for beans that are defined twice, the latest takes - precedence). - -| `namespace` -| The namespace of the `WebApplicationContext`. Defaults to `[portlet-name]-portlet`. - -| `viewRendererUrl` -| The URL at which `DispatcherPortlet` can access an instance of `ViewRendererServlet` - (see <>). -|=== - - - - -[[portlet-viewservlet]] -== The ViewRendererServlet - -The rendering process in Portlet MVC is a bit more complex than in Web MVC. In order to -reuse all the <> from Spring Web MVC, we must convert the -`PortletRequest` / `PortletResponse` to `HttpServletRequest` / `HttpServletResponse` and -then call the `render` method of the `View`. To do this, `DispatcherPortlet` uses a -special servlet that exists for just this purpose: the `ViewRendererServlet`. - -In order for `DispatcherPortlet` rendering to work, you must declare an instance of the -`ViewRendererServlet` in the `web.xml` file for your web application as follows: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - ViewRendererServlet - org.springframework.web.servlet.ViewRendererServlet - - - - ViewRendererServlet - /WEB-INF/servlet/view - ----- - -To perform the actual rendering, `DispatcherPortlet` does the following: - -. Binds the `WebApplicationContext` to the request as an attribute under the same -`WEB_APPLICATION_CONTEXT_ATTRIBUTE` key that `DispatcherServlet` uses. -. Binds the `Model` and `View` objects to the request to make them available to the -`ViewRendererServlet`. -. Constructs a `PortletRequestDispatcher` and performs an `include` using the `/WEB- -INF/servlet/view` URL that is mapped to the `ViewRendererServlet`. - -The `ViewRendererServlet` is then able to call the `render` method on the `View` with -the appropriate arguments. - -The actual URL for the `ViewRendererServlet` can be changed using `DispatcherPortlet`'s -`viewRendererUrl` configuration parameter. - - - - -[[portlet-controller]] -== Controllers -The controllers in Portlet MVC are very similar to the Web MVC Controllers, and porting -code from one to the other should be simple. - -The basis for the Portlet MVC controller architecture is the -`org.springframework.web.portlet.mvc.Controller` interface, which is listed below. - -[source,java,indent=0] ----- - public interface Controller { - - /** - * Process the render request and return a ModelAndView object which the - * DispatcherPortlet will render. - */ - ModelAndView handleRenderRequest(RenderRequest request, - RenderResponse response) throws Exception; - - /** - * Process the action request. There is nothing to return. - */ - void handleActionRequest(ActionRequest request, - ActionResponse response) throws Exception; - - } ----- - -As you can see, the Portlet `Controller` interface requires two methods that handle the -two phases of a portlet request: the action request and the render request. The action -phase should be capable of handling an action request, and the render phase should be -capable of handling a render request and returning an appropriate model and view. While -the `Controller` interface is quite abstract, Spring Portlet MVC offers several -controllers that already contain a lot of the functionality you might need; most of -these are very similar to controllers from Spring Web MVC. The `Controller` interface -just defines the most common functionality required of every controller: handling an -action request, handling a render request, and returning a model and a view. - - - -[[portlet-controller-abstractcontroller]] -=== AbstractController and PortletContentGenerator - -Of course, just a `Controller` interface isn't enough. To provide a basic -infrastructure, all of Spring Portlet MVC's ``Controller``s inherit from -`AbstractController`, a class offering access to Spring's `ApplicationContext` and -control over caching. - -[[portlet-ac-features]] -.Features offered by the AbstractController -[cols="1,4"] -|=== -| Parameter| Explanation - -| `requireSession` -| Indicates whether or not this `Controller` requires a session to do its work. This - feature is offered to all controllers. If a session is not present when such a - controller receives a request, the user is informed using a `SessionRequiredException`. - -| `synchronizeSession` -| Use this if you want handling by this controller to be synchronized on the user's - session. To be more specific, the extending controller will override the - `handleRenderRequestInternal(..)` and `handleActionRequestInternal(..)` methods, which - will be synchronized on the user's session if you specify this variable. - -| `renderWhenMinimized` -| If you want your controller to actually render the view when the portlet is in a - minimized state, set this to true. By default, this is set to false so that portlets - that are in a minimized state don't display any content. - -| `cacheSeconds` -| When you want a controller to override the default cache expiration defined for the - portlet, specify a positive integer here. By default it is set to `-1`, which does not - change the default caching. Setting it to `0` will ensure the result is never cached. -|=== - -The `requireSession` and `cacheSeconds` properties are declared on the -`PortletContentGenerator` class, which is the superclass of `AbstractController`) but -are included here for completeness. - -When using the `AbstractController` as a base class for your controllers (which is not -recommended since there are a lot of other controllers that might already do the job for -you) you only have to override either the `handleActionRequestInternal(ActionRequest, -ActionResponse)` method or the `handleRenderRequestInternal(RenderRequest, -RenderResponse)` method (or both), implement your logic, and return a `ModelAndView` -object (in the case of `handleRenderRequestInternal`). - -The default implementations of both `handleActionRequestInternal(..)` and -`handleRenderRequestInternal(..)` throw a `PortletException`. This is consistent with -the behavior of `GenericPortlet` from the JSR- 168 Specification API. So you only need -to override the method that your controller is intended to handle. - -Here is short example consisting of a class and a declaration in the web application -context. - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - package samples; - - import javax.portlet.RenderRequest; - import javax.portlet.RenderResponse; - - import org.springframework.web.portlet.mvc.AbstractController; - import org.springframework.web.portlet.ModelAndView; - - public class SampleController extends AbstractController { - - public ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) { - ModelAndView mav = new ModelAndView("foo"); - mav.addObject("message", "Hello World!"); - return mav; - } - - } ----- - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - ----- - -The class above and the declaration in the web application context is all you need -besides setting up a handler mapping (see <>) to get this very -simple controller working. - - - -[[portlet-controller-simple]] -=== Other simple controllers -Although you can extend `AbstractController`, Spring Portlet MVC provides a number of -concrete implementations which offer functionality that is commonly used in simple MVC -applications. - -The `ParameterizableViewController` is basically the same as the example above, except -for the fact that you can specify the view name that it will return in the web -application context (no need to hard-code the view name). - -The `PortletModeNameViewController` uses the current mode of the portlet as the view -name. So, if your portlet is in View mode (i.e. `PortletMode.VIEW`) then it uses "view" -as the view name. - - - -[[portlet-controller-command]] -=== Command Controllers -Spring Portlet MVC has the exact same hierarchy of __command controllers__ as Spring Web -MVC. They provide a way to interact with data objects and dynamically bind parameters -from the `PortletRequest` to the data object specified. Your data objects don't have to -implement a framework-specific interface, so you can directly manipulate your persistent -objects if you desire. Let's examine what command controllers are available, to get an -overview of what you can do with them: - -* `AbstractCommandController` - a command controller you can use to create your own - command controller, capable of binding request parameters to a data object you - specify. This class does not offer form functionality, it does however offer - validation features and lets you specify in the controller itself what to do with the - command object that has been filled with the parameters from the request. -* `AbstractFormController` - an abstract controller offering form submission support. - Using this controller you can model forms and populate them using a command object you - retrieve in the controller. After a user has filled the form, `AbstractFormController` - binds the fields, validates, and hands the object back to the controller to take - appropriate action. Supported features are: invalid form submission (resubmission), - validation, and normal form workflow. You implement methods to determine which views - are used for form presentation and success. Use this controller if you need forms, but - don't want to specify what views you're going to show the user in the application - context. -* `SimpleFormController` - a concrete `AbstractFormController` that provides even more - support when creating a form with a corresponding command object. The - `SimpleFormController` lets you specify a command object, a viewname for the form, a - viewname for the page you want to show the user when form submission has succeeded, - and more. -* `AbstractWizardFormController` -- a concrete `AbstractFormController` that provides a - wizard-style interface for editing the contents of a command object across multiple - display pages. Supports multiple user actions: finish, cancel, or page change, all of - which are easily specified in request parameters from the view. - -These command controllers are quite powerful, but they do require a detailed -understanding of how they operate in order to use them efficiently. Carefully review the -javadocs for this entire hierarchy and then look at some sample implementations before -you start using them. - - - -[[portlet-controller-wrapping]] -=== PortletWrappingController - -Instead of developing new controllers, it is possible to use existing portlets and map -requests to them from a `DispatcherPortlet`. Using the `PortletWrappingController`, you -can instantiate an existing `Portlet` as a `Controller` as follows: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - config=/WEB-INF/my-portlet-config.xml - - ----- - -This can be very valuable since you can then use interceptors to pre-process and -post-process requests going to these portlets. Since JSR-286 does not support any kind -of filter mechanism, this is quite handy. For example, this can be used to wrap the -Hibernate `OpenSessionInViewInterceptor` around a MyFaces JSF Portlet. - - - - -[[portlet-handlermapping]] -== Handler mappings -Using a handler mapping you can map incoming portlet requests to appropriate handlers. -There are some handler mappings you can use out of the box, for example, the -`PortletModeHandlerMapping`, but let's first examine the general concept of a -`HandlerMapping`. - -Note: We are intentionally using the term "Handler" here instead of "Controller". -`DispatcherPortlet` is designed to be used with other ways to process requests than just -Spring Portlet MVC's own Controllers. A Handler is any Object that can handle portlet -requests. Controllers are an example of Handlers, and they are of course the default. To -use some other framework with `DispatcherPortlet`, a corresponding implementation of -`HandlerAdapter` is all that is needed. - -The functionality a basic `HandlerMapping` provides is the delivering of a -`HandlerExecutionChain`, which must contain the handler that matches the incoming -request, and may also contain a list of handler interceptors that are applied to the -request. When a request comes in, the `DispatcherPortlet` will hand it over to the -handler mapping to let it inspect the request and come up with an appropriate -`HandlerExecutionChain`. Then the `DispatcherPortlet` will execute the handler and -interceptors in the chain (if any). These concepts are all exactly the same as in Spring -Web MVC. - -The concept of configurable handler mappings that can optionally contain interceptors -(executed before or after the actual handler was executed, or both) is extremely -powerful. A lot of supporting functionality can be built into a custom `HandlerMapping`. -Think of a custom handler mapping that chooses a handler not only based on the portlet -mode of the request coming in, but also on a specific state of the session associated -with the request. - -In Spring Web MVC, handler mappings are commonly based on URLs. Since there is really no -such thing as a URL within a Portlet, we must use other mechanisms to control mappings. -The two most common are the portlet mode and a request parameter, but anything available -to the portlet request can be used in a custom handler mapping. - -The rest of this section describes three of Spring Portlet MVC's most commonly used -handler mappings. They all extend `AbstractHandlerMapping` and share the following -properties: - -* `interceptors`: The list of interceptors to use. ``HandlerInterceptor``s are discussed - in <>. -* `defaultHandler`: The default handler to use, when this handler mapping does not - result in a matching handler. -* `order`: Based on the value of the order property (see the - `org.springframework.core.Ordered` interface), Spring will sort all handler mappings - available in the context and apply the first matching handler. -* `lazyInitHandlers`: Allows for lazy initialization of singleton handlers (prototype - handlers are always lazily initialized). Default value is false. This property is - directly implemented in the three concrete Handlers. - - - -[[portlet-handlermapping-portletmode]] -=== PortletModeHandlerMapping - -This is a simple handler mapping that maps incoming requests based on the current mode -of the portlet (e.g. 'view', 'edit', 'help'). An example: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - - - - ----- - - - -[[portlet-handlermapping-parameter]] -=== ParameterHandlerMapping - -If we need to navigate around to multiple controllers without changing portlet mode, the -simplest way to do this is with a request parameter that is used as the key to control -the mapping. - -`ParameterHandlerMapping` uses the value of a specific request parameter to control the -mapping. The default name of the parameter is `'action'`, but can be changed using the -`'parameterName'` property. - -The bean configuration for this mapping will look something like this: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - - - - ----- - - - -[[portlet-handlermapping-portletmodeparameter]] -=== PortletModeParameterHandlerMapping - -The most powerful built-in handler mapping, `PortletModeParameterHandlerMapping` -combines the capabilities of the two previous ones to allow different navigation within -each portlet mode. - -Again the default name of the parameter is "action", but can be changed using the -`parameterName` property. - -By default, the same parameter value may not be used in two different portlet modes. -This is so that if the portal itself changes the portlet mode, the request will no -longer be valid in the mapping. This behavior can be changed by setting the -`allowDupParameters` property to true. However, this is not recommended. - -The bean configuration for this mapping will look something like this: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - - - - - - - - - - - - - - ----- - -This mapping can be chained ahead of a `PortletModeHandlerMapping`, which can then -provide defaults for each mode and an overall default as well. - - - -[[portlet-handlermapping-interceptor]] -=== Adding HandlerInterceptors - -Spring's handler mapping mechanism has a notion of handler interceptors, which can be -extremely useful when you want to apply specific functionality to certain requests, for -example, checking for a principal. Again Spring Portlet MVC implements these concepts in -the same way as Web MVC. - -Interceptors located in the handler mapping must implement `HandlerInterceptor` from the -`org.springframework.web.portlet` package. Just like the servlet version, this interface -defines three methods: one that will be called before the actual handler will be -executed ( `preHandle`), one that will be called after the handler is executed ( -`postHandle`), and one that is called after the complete request has finished ( -`afterCompletion`). These three methods should provide enough flexibility to do all -kinds of pre- and post- processing. - -The `preHandle` method returns a boolean value. You can use this method to break or -continue the processing of the execution chain. When this method returns `true`, the -handler execution chain will continue. When it returns `false`, the `DispatcherPortlet` -assumes the interceptor itself has taken care of requests (and, for example, rendered an -appropriate view) and does not continue executing the other interceptors and the actual -handler in the execution chain. - -The `postHandle` method is only called on a `RenderRequest`. The `preHandle` and -`afterCompletion` methods are called on both an `ActionRequest` and a `RenderRequest`. -If you need to execute logic in these methods for just one type of request, be sure to -check what kind of request it is before processing it. - - - -[[portlet-handlermapping-interceptoradapter]] -=== HandlerInterceptorAdapter - -As with the servlet package, the portlet package has a concrete implementation of -`HandlerInterceptor` called `HandlerInterceptorAdapter`. This class has empty versions -of all the methods so that you can inherit from this class and implement just one or two -methods when that is all you need. - - - -[[portlet-handlermapping-parameterinterceptor]] -=== ParameterMappingInterceptor - -The portlet package also has a concrete interceptor named `ParameterMappingInterceptor` -that is meant to be used directly with `ParameterHandlerMapping` and -`PortletModeParameterHandlerMapping`. This interceptor will cause the parameter that is -being used to control the mapping to be forwarded from an `ActionRequest` to the -subsequent `RenderRequest`. This will help ensure that the `RenderRequest` is mapped to -the same Handler as the `ActionRequest`. This is done in the `preHandle` method of the -interceptor, so you can still modify the parameter value in your handler to change where -the `RenderRequest` will be mapped. - -Be aware that this interceptor is calling `setRenderParameter` on the `ActionResponse`, -which means that you cannot call `sendRedirect` in your handler when using this -interceptor. If you need to do external redirects then you will either need to forward -the mapping parameter manually or write a different interceptor to handle this for you. - - - - -[[portlet-viewresolver]] -== Views and resolving them -As mentioned previously, Spring Portlet MVC directly reuses all the view technologies -from Spring Web MVC. This includes not only the various `View` implementations -themselves, but also the `ViewResolver` implementations. For more information, refer to -<> and <> respectively. - -A few items on using the existing `View` and `ViewResolver` implementations are worth -mentioning: - -* Most portals expect the result of rendering a portlet to be an HTML fragment. So, - things like JSP/JSTL, Velocity, FreeMarker, and XSLT all make sense. But it is - unlikely that views that return other document types will make any sense in a portlet - context. -* There is no such thing as an HTTP redirect from within a portlet (the - `sendRedirect(..)` method of `ActionResponse` cannot be used to stay within the - portal). So, `RedirectView` and use of the `'redirect:'` prefix will __not__ work - correctly from within Portlet MVC. -* It may be possible to use the `'forward:'` prefix from within Portlet MVC. However, - remember that since you are in a portlet, you have no idea what the current URL looks - like. This means you cannot use a relative URL to access other resources in your web - application and that you will have to use an absolute URL. - -Also, for JSP development, the new Spring Taglib and the new Spring Form Taglib both -work in portlet views in exactly the same way that they work in servlet views. - - - - -[[portlet-multipart]] -== Multipart (file upload) support -Spring Portlet MVC has built-in multipart support to handle file uploads in portlet -applications, just like Web MVC does. The design for the multipart support is done with -pluggable `PortletMultipartResolver` objects, defined in the -`org.springframework.web.portlet.multipart` package. Spring provides a -`PortletMultipartResolver` for use with -http://jakarta.apache.org/commons/fileupload[Commons FileUpload]. How uploading files is -supported will be described in the rest of this section. - -By default, no multipart handling will be done by Spring Portlet MVC, as some developers -will want to handle multiparts themselves. You will have to enable it yourself by adding -a multipart resolver to the web application's context. After you have done that, -`DispatcherPortlet` will inspect each request to see if it contains a multipart. If no -multipart is found, the request will continue as expected. However, if a multipart is -found in the request, the `PortletMultipartResolver` that has been declared in your -context will be used. After that, the multipart attribute in your request will be -treated like any other attribute. - -[NOTE] -==== -Any configured `PortletMultipartResolver` bean __must__ have the following id (or name): -" `portletMultipartResolver`". If you have defined your `PortletMultipartResolver` with -any other name, then the `DispatcherPortlet` will __not__ find your -`PortletMultipartResolver`, and consequently no multipart support will be in effect. -==== - - - -[[portlet-multipart-resolver]] -=== Using the PortletMultipartResolver - -The following example shows how to use the `CommonsPortletMultipartResolver`: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - ----- - -Of course you also need to put the appropriate jars in your classpath for the multipart -resolver to work. In the case of the `CommonsMultipartResolver`, you need to use -`commons-fileupload.jar`. Be sure to use at least version 1.1 of Commons FileUpload as -previous versions do not support JSR-286 Portlet applications. - -Now that you have seen how to set Portlet MVC up to handle multipart requests, let's -talk about how to actually use it. When `DispatcherPortlet` detects a multipart request, -it activates the resolver that has been declared in your context and hands over the -request. What the resolver then does is wrap the current `ActionRequest` in a -`MultipartActionRequest` that has support for multipart file uploads. Using the -`MultipartActionRequest` you can get information about the multiparts contained by this -request and actually get access to the multipart files themselves in your controllers. - -Note that you can only receive multipart file uploads as part of an `ActionRequest`, not -as part of a `RenderRequest`. - - - -[[portlet-multipart-forms]] -=== Handling a file upload in a form -After the `PortletMultipartResolver` has finished doing its job, the request will be -processed like any other. To use the `PortletMultipartResolver`, create a form with an -upload field (see example below), then let Spring bind the file onto your form (backing -object). To actually let the user upload a file, we have to create a (JSP/HTML) form: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- -

            Please upload a file

            -
            - - -
            ----- - -As you can see, we've created a field named "file" that matches the property of the bean -that holds the `byte[]` array. Furthermore we've added the encoding attribute ( -`enctype="multipart/form-data"`), which is necessary to let the browser know how to -encode the multipart fields (do not forget this!). - -Just as with any other property that's not automagically convertible to a string or -primitive type, to be able to put binary data in your objects you have to register a -custom editor with the `PortletRequestDataBinder`. There are a couple of editors -available for handling files and setting the results on an object. There's a -`StringMultipartFileEditor` capable of converting files to Strings (using a user-defined -character set), and there is a `ByteArrayMultipartFileEditor` which converts files to -byte arrays. They function analogous to the `CustomDateEditor`. - -So, to be able to upload files using a form, declare the resolver, a mapping to a -controller that will process the bean, and the controller itself. - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - - - - - - - - - - ----- - -After that, create the controller and the actual class to hold the file property. - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - public class FileUploadController extends SimpleFormController { - - public void onSubmitAction(ActionRequest request, ActionResponse response, - Object command, BindException errors) throws Exception { - - // cast the bean - FileUploadBean bean = (FileUploadBean) command; - - // let's see if there's content there - byte[] file = bean.getFile(); - if (file == null) { - // hmm, that's strange, the user did not upload anything - } - - // do something with the file here - } - - protected void initBinder(PortletRequest request, - PortletRequestDataBinder binder) throws Exception { - // to actually be able to convert Multipart instance to byte[] - // we have to register a custom editor - binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor()); - // now Spring knows how to handle multipart object and convert - } - - } - - public class FileUploadBean { - - private byte[] file; - - public void setFile(byte[] file) { - this.file = file; - } - - public byte[] getFile() { - return file; - } - - } ----- - -As you can see, the `FileUploadBean` has a property of type `byte[]` that holds the -file. The controller registers a custom editor to let Spring know how to actually -convert the multipart objects the resolver has found to properties specified by the -bean. In this example, nothing is done with the `byte[]` property of the bean itself, -but in practice you can do whatever you want (save it in a database, mail it to -somebody, etc). - -An equivalent example in which a file is bound straight to a String-typed property on a -form backing object might look like this: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - public class FileUploadController extends SimpleFormController { - - public void onSubmitAction(ActionRequest request, ActionResponse response, - Object command, BindException errors) throws Exception { - - // cast the bean - FileUploadBean bean = (FileUploadBean) command; - - // let's see if there's content there - String file = bean.getFile(); - if (file == null) { - // hmm, that's strange, the user did not upload anything - } - - // do something with the file here - } - - protected void initBinder(PortletRequest request, - PortletRequestDataBinder binder) throws Exception { - - // to actually be able to convert Multipart instance to a String - // we have to register a custom editor - binder.registerCustomEditor(String.class, new StringMultipartFileEditor()); - // now Spring knows how to handle multipart objects and convert - } - } - - public class FileUploadBean { - - private String file; - - public void setFile(String file) { - this.file = file; - } - - public String getFile() { - return file; - } - } ----- - -Of course, this last example only makes (logical) sense in the context of uploading a -plain text file (it wouldn't work so well in the case of uploading an image file). - -The third (and final) option is where one binds directly to a `MultipartFile` property -declared on the (form backing) object's class. In this case one does not need to -register any custom property editor because there is no type conversion to be performed. - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - public class FileUploadController extends SimpleFormController { - - public void onSubmitAction(ActionRequest request, ActionResponse response, - Object command, BindException errors) throws Exception { - - // cast the bean - FileUploadBean bean = (FileUploadBean) command; - - // let's see if there's content there - MultipartFile file = bean.getFile(); - if (file == null) { - // hmm, that's strange, the user did not upload anything - } - - // do something with the file here - } - } - - public class FileUploadBean { - - private MultipartFile file; - - public void setFile(MultipartFile file) { - this.file = file; - } - - public MultipartFile getFile() { - return file; - } - - } ----- - - - - -[[portlet-exceptionresolver]] -== Handling exceptions -Just like Servlet MVC, Portlet MVC provides ``HandlerExceptionResolver``s to ease the -pain of unexpected exceptions that occur while your request is being processed by a -handler that matched the request. Portlet MVC also provides a portlet-specific, concrete -`SimpleMappingExceptionResolver` that enables you to take the class name of any -exception that might be thrown and map it to a view name. - - - - -[[portlet-annotation]] -== Annotation-based controller configuration -Spring 2.5 introduced an annotation-based programming model for MVC controllers, using -annotations such as `@RequestMapping`, `@RequestParam`, `@ModelAttribute`, etc. This -annotation support is available for both Servlet MVC and Portlet MVC. Controllers -implemented in this style do not have to extend specific base classes or implement -specific interfaces. Furthermore, they do not usually have direct dependencies on -Servlet or Portlet API's, although they can easily get access to Servlet or Portlet -facilities if desired. - -The following sections document these annotations and how they are most commonly used in -a Portlet environment. - - - -[[portlet-ann-setup]] -=== Setting up the dispatcher for annotation support -__`@RequestMapping` will only be processed if a corresponding `HandlerMapping` (for -type level annotations) and/or `HandlerAdapter` (for method level annotations) is -present in the dispatcher.__ This is the case by default in both `DispatcherServlet` and -`DispatcherPortlet`. - -However, if you are defining custom `HandlerMappings` or `HandlerAdapters`, then you -need to make sure that a corresponding custom `DefaultAnnotationHandlerMapping` and/or -`AnnotationMethodHandlerAdapter` is defined as well - provided that you intend to use -`@RequestMapping`. - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - - - // ... (controller bean definitions) ... - - ----- - -Defining a `DefaultAnnotationHandlerMapping` and/or `AnnotationMethodHandlerAdapter` -explicitly also makes sense if you would like to customize the mapping strategy, e.g. -specifying a custom `WebBindingInitializer` (see below). - - - -[[portlet-ann-controller]] -=== Defining a controller with @Controller - -The `@Controller` annotation indicates that a particular class serves the role of a -__controller__. There is no need to extend any controller base class or reference the -Portlet API. You are of course still able to reference Portlet-specific features if you -need to. - -The basic purpose of the `@Controller` annotation is to act as a stereotype for the -annotated class, indicating its role. The dispatcher will scan such annotated classes -for mapped methods, detecting `@RequestMapping` annotations (see the next section). - -Annotated controller beans may be defined explicitly, using a standard Spring bean -definition in the dispatcher's context. However, the `@Controller` stereotype also -allows for autodetection, aligned with Spring 2.5's general support for detecting -component classes in the classpath and auto-registering bean definitions for them. - -To enable autodetection of such annotated controllers, you have to add component -scanning to your configuration. This is easily achieved by using the __spring-context__ -schema as shown in the following XML snippet: - -[source,xml,indent=0] -[subs="verbatim,quotes"] ----- - - - - - - // ... - - ----- - - - -[[portlet-ann-requestmapping]] -=== Mapping requests with @RequestMapping - -The `@RequestMapping` annotation is used to map portlet modes like 'VIEW'/'EDIT' onto an -entire class or a particular handler method. Typically the type-level annotation maps a -specific mode (or mode plus parameter condition) onto a form controller, with additional -method-level annotations 'narrowing' the primary mapping for specific portlet request -parameters. - -[TIP] -==== - -`@RequestMapping` at the type level may be used for plain implementations of the -`Controller` interface as well. In this case, the request processing code would follow -the traditional `handle(Action|Render)Request` signature, while the controller's mapping -would be expressed through an `@RequestMapping` annotation. This works for pre-built -`Controller` base classes, such as `SimpleFormController`, too. - -In the following discussion, we'll focus on controllers that are based on annotated -handler methods. -==== - -The following is an example of a form controller from the PetPortal sample application -using this annotation: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Controller - @RequestMapping("EDIT") - @SessionAttributes("site") - public class PetSitesEditController { - - private Properties petSites; - - public void setPetSites(Properties petSites) { - this.petSites = petSites; - } - - @ModelAttribute("petSites") - public Properties getPetSites() { - return this.petSites; - } - - @RequestMapping // default (action=list) - public String showPetSites() { - return "petSitesEdit"; - } - - @RequestMapping(params = "action=add") // render phase - public String showSiteForm(Model model) { - // Used for the initial form as well as for redisplaying with errors. - if (!model.containsAttribute("site")) { - model.addAttribute("site", new PetSite()); - } - - return "petSitesAdd"; - } - - @RequestMapping(params = "action=add") // action phase - public void populateSite(@ModelAttribute("site") PetSite petSite, - BindingResult result, SessionStatus status, ActionResponse response) { - new PetSiteValidator().validate(petSite, result); - if (!result.hasErrors()) { - this.petSites.put(petSite.getName(), petSite.getUrl()); - status.setComplete(); - response.setRenderParameter("action", "list"); - } - } - - @RequestMapping(params = "action=delete") - public void removeSite(@RequestParam("site") String site, ActionResponse response) { - this.petSites.remove(site); - response.setRenderParameter("action", "list"); - } - } ----- - -As of Spring 3.0, there are dedicated `@ActionMapping` and `@RenderMapping` (as well as -`@ResourceMapping` and `@EventMapping`) annotations which can be used instead: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Controller - @RequestMapping("EDIT") - @SessionAttributes("site") - public class PetSitesEditController { - - private Properties petSites; - - public void setPetSites(Properties petSites) { - this.petSites = petSites; - } - - @ModelAttribute("petSites") - public Properties getPetSites() { - return this.petSites; - } - - @RenderMapping // default (action=list) - public String showPetSites() { - return "petSitesEdit"; - } - - @RenderMapping(params = "action=add") - public String showSiteForm(Model model) { - // Used for the initial form as well as for redisplaying with errors. - if (!model.containsAttribute("site")) { - model.addAttribute("site", new PetSite()); - } - - return "petSitesAdd"; - } - - @ActionMapping(params = "action=add") - public void populateSite(@ModelAttribute("site") PetSite petSite, - BindingResult result, SessionStatus status, ActionResponse response) { - new PetSiteValidator().validate(petSite, result); - if (!result.hasErrors()) { - this.petSites.put(petSite.getName(), petSite.getUrl()); - status.setComplete(); - response.setRenderParameter("action", "list"); - } - } - - @ActionMapping(params = "action=delete") - public void removeSite(@RequestParam("site") String site, ActionResponse response) { - this.petSites.remove(site); - response.setRenderParameter("action", "list"); - } - } ----- - - - -[[portlet-ann-requestmapping-arguments]] -=== Supported handler method arguments -Handler methods which are annotated with `@RequestMapping` are allowed to have very -flexible signatures. They may have arguments of the following types, in arbitrary order -(except for validation results, which need to follow right after the corresponding -command object, if desired): - -* Request and/or response objects (Portlet API). You may choose any specific - request/response type, e.g. PortletRequest / ActionRequest / RenderRequest. An - explicitly declared action/render argument is also used for mapping specific request - types onto a handler method (in case of no other information given that differentiates - between action and render requests). -* Session object (Portlet API): of type PortletSession. An argument of this type will - enforce the presence of a corresponding session. As a consequence, such an argument - will never be `null`. -* `org.springframework.web.context.request.WebRequest` or - `org.springframework.web.context.request.NativeWebRequest`. Allows for generic request - parameter access as well as request/session attribute access, without ties to the - native Servlet/Portlet API. -* `java.util.Locale` for the current request locale (the portal locale in a Portlet - environment). -* `java.util.TimeZone` / `java.time.ZoneId` for the current request time zone. -* `java.io.InputStream` / `java.io.Reader` for access to the request's content. This - will be the raw InputStream/Reader as exposed by the Portlet API. -* `java.io.OutputStream` / `java.io.Writer` for generating the response's content. This - will be the raw OutputStream/Writer as exposed by the Portlet API. -* `@RequestParam` annotated parameters for access to specific Portlet request - parameters. Parameter values will be converted to the declared method argument type. -* `java.util.Map` / `org.springframework.ui.Model` / `org.springframework.ui.ModelMap` - for enriching the implicit model that will be exposed to the web view. -* Command/form objects to bind parameters to: as bean properties or fields, with - customizable type conversion, depending on `@InitBinder` methods and/or the - HandlerAdapter configuration - see the " `webBindingInitializer`" property on - `AnnotationMethodHandlerAdapter`. Such command objects along with their validation - results will be exposed as model attributes, by default using the non-qualified - command class name in property notation (e.g. "orderAddress" for type - "mypackage.OrderAddress"). Specify a parameter-level `ModelAttribute` annotation for - declaring a specific model attribute name. -* `org.springframework.validation.Errors` / - `org.springframework.validation.BindingResult` validation results for a preceding - command/form object (the immediate preceding argument). -* `org.springframework.web.bind.support.SessionStatus` status handle for marking form - processing as complete (triggering the cleanup of session attributes that have been - indicated by the `@SessionAttributes` annotation at the handler type level). - -The following return types are supported for handler methods: - -* A `ModelAndView` object, with the model implicitly enriched with command objects and - the results of `@ModelAttribute` annotated reference data accessor methods. -* A `Model` object, with the view name implicitly determined through a - `RequestToViewNameTranslator` and the model implicitly enriched with command objects - and the results of `@ModelAttribute` annotated reference data accessor methods. -* A `Map` object for exposing a model, with the view name implicitly determined through - a `RequestToViewNameTranslator` and the model implicitly enriched with command objects - and the results of `@ModelAttribute` annotated reference data accessor methods. -* A `View` object, with the model implicitly determined through command objects and - `@ModelAttribute` annotated reference data accessor methods. The handler method may - also programmatically enrich the model by declaring a `Model` argument (see above). -* A `String` value which is interpreted as view name, with the model implicitly - determined through command objects and `@ModelAttribute` annotated reference data - accessor methods. The handler method may also programmatically enrich the model by - declaring a `Model` argument (see above). -* `void` if the method handles the response itself (e.g. by writing the response content - directly). -* Any other return type will be considered a single model attribute to be exposed to the - view, using the attribute name specified through `@ModelAttribute` at the method level - (or the default attribute name based on the return type's class name otherwise). The - model will be implicitly enriched with command objects and the results of - `@ModelAttribute` annotated reference data accessor methods. - - - -[[portlet-ann-requestparam]] -=== Binding request parameters to method parameters with @RequestParam - -The `@RequestParam` annotation is used to bind request parameters to a method parameter -in your controller. - -The following code snippet from the PetPortal sample application shows the usage: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Controller - @RequestMapping("EDIT") - @SessionAttributes("site") - public class PetSitesEditController { - - // ... - - public void removeSite(@RequestParam("site") String site, ActionResponse response) { - this.petSites.remove(site); - response.setRenderParameter("action", "list"); - } - - // ... - - } ----- - -Parameters using this annotation are required by default, but you can specify that a -parameter is optional by setting `@RequestParam`'s `required` attribute to `false` -(e.g., `@RequestParam(name="id", required=false)`). - - - -[[portlet-ann-modelattrib]] -=== Providing a link to data from the model with @ModelAttribute - -`@ModelAttribute` has two usage scenarios in controllers. When placed on a method -parameter, `@ModelAttribute` is used to map a model attribute to the specific, annotated -method parameter (see the `populateSite()` method below). This is how the controller -gets a reference to the object holding the data entered in the form. In addition, the -parameter can be declared as the specific type of the form backing object rather than as -a generic `java.lang.Object`, thus increasing type safety. - -`@ModelAttribute` is also used at the method level to provide __reference data__ for the -model (see the `getPetSites()` method below). For this usage the method signature can -contain the same types as documented above for the `@RequestMapping` annotation. - -[NOTE] -==== -`@ModelAttribute` annotated methods will be executed __before__ the chosen -`@RequestMapping` annotated handler method. They effectively pre-populate the implicit -model with specific attributes, often loaded from a database. Such an attribute can then -already be accessed through `@ModelAttribute` annotated handler method parameters in the -chosen handler method, potentially with binding and validation applied to it. -==== - -The following code snippet shows these two usages of this annotation: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Controller - @RequestMapping("EDIT") - @SessionAttributes("site") - public class PetSitesEditController { - - // ... - - @ModelAttribute("petSites") - public Properties getPetSites() { - return this.petSites; - } - - @RequestMapping(params = "action=add") // action phase - public void populateSite( @ModelAttribute("site") PetSite petSite, BindingResult result, SessionStatus status, ActionResponse response) { - new PetSiteValidator().validate(petSite, result); - if (!result.hasErrors()) { - this.petSites.put(petSite.getName(), petSite.getUrl()); - status.setComplete(); - response.setRenderParameter("action", "list"); - } - } - } ----- - - - -[[portlet-ann-sessionattrib]] -=== Specifying attributes to store in a Session with @SessionAttributes - -The type-level `@SessionAttributes` annotation declares session attributes used by a -specific handler. This will typically list the names of model attributes or types of -model attributes which should be transparently stored in the session or some -conversational storage, serving as form-backing beans between subsequent requests. - -The following code snippet shows the usage of this annotation: - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Controller - @RequestMapping("EDIT") - @SessionAttributes("site") - public class PetSitesEditController { - // ... - } ----- - - - -[[portlet-ann-webdatabinder]] -=== Customizing WebDataBinder initialization - -To customize request parameter binding with PropertyEditors, etc. via Spring's -`WebDataBinder`, you can either use `@InitBinder`-annotated methods within your -controller or externalize your configuration by providing a custom -`WebBindingInitializer`. - - -[[portlet-ann-initbinder]] -==== Customizing data binding with @InitBinder - -Annotating controller methods with `@InitBinder` allows you to configure web data -binding directly within your controller class. `@InitBinder` identifies methods which -initialize the `WebDataBinder` which will be used for populating command and form object -arguments of annotated handler methods. - -Such init-binder methods support all arguments that `@RequestMapping` supports, except -for command/form objects and corresponding validation result objects. Init-binder -methods must not have a return value. Thus, they are usually declared as `void`. Typical -arguments include `WebDataBinder` in combination with `WebRequest` or -`java.util.Locale`, allowing code to register context-specific editors. - -The following example demonstrates the use of `@InitBinder` for configuring a -`CustomDateEditor` for all `java.util.Date` form properties. - -[source,java,indent=0] -[subs="verbatim,quotes"] ----- - @Controller - public class MyFormController { - - @InitBinder - protected void initBinder(WebDataBinder binder) { - SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); - dateFormat.setLenient(false); - binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); - } - - // ... - - } ----- - - -[[portlet-ann-webbindinginitializer]] -==== Configuring a custom WebBindingInitializer - -To externalize data binding initialization, you can provide a custom implementation of -the `WebBindingInitializer` interface, which you then enable by supplying a custom bean -configuration for an `AnnotationMethodHandlerAdapter`, thus overriding the default -configuration. - - - - -[[portlet-deployment]] -== Portlet application deployment -The process of deploying a Spring Portlet MVC application is no different than deploying -any JSR-286 Portlet application. However, this area is confusing enough in general that -it is worth talking about here briefly. - -Generally, the portal/portlet container runs in one webapp in your servlet container and -your portlets run in another webapp in your servlet container. In order for the portlet -container webapp to make calls into your portlet webapp it must make cross-context calls -to a well-known servlet that provides access to the portlet services defined in your -`portlet.xml` file. - -The JSR-286 specification does not specify exactly how this should happen, so each -portlet container has its own mechanism for this, which usually involves some kind of -"deployment process" that makes changes to the portlet webapp itself and then registers -the portlets within the portlet container. - -At a minimum, the `web.xml` file in your portlet webapp is modified to inject the -well-known servlet that the portlet container will call. In some cases a single servlet -will service all portlets in the webapp, in other cases there will be an instance of the -servlet for each portlet. - -Some portlet containers will also inject libraries and/or configuration files into the -webapp as well. The portlet container must also make its implementation of the Portlet -JSP Tag Library available to your webapp. - -The bottom line is that it is important to understand the deployment needs of your -target portal and make sure they are met (usually by following the automated deployment -process it provides). Be sure to carefully review the documentation from your portal for -this process. - -Once you have deployed your portlet, review the resulting `web.xml` file for sanity. -Some older portals have been known to corrupt the definition of the -`ViewRendererServlet`, thus breaking the rendering of your portlets. diff --git a/src/asciidoc/web.adoc b/src/asciidoc/web.adoc index e6388258e7..9b88356a02 100644 --- a/src/asciidoc/web.adoc +++ b/src/asciidoc/web.adoc @@ -11,15 +11,12 @@ Spring Framework's own web framework, <>, is covered in the first couple of chapters. Subsequent chapters are concerned with Spring Framework's integration with other web technologies, such as <>. -Following that is coverage of Spring Framework's MVC <>. - The section then concludes with comprehensive coverage of the Spring Framework <> (including <>). * <> * <> * <> -* <> * <> -- @@ -29,8 +26,6 @@ include::web-view.adoc[leveloffset=+1] include::web-integration.adoc[leveloffset=+1] -include::web-portlet.adoc[leveloffset=+1] - include::web-websocket.adoc[leveloffset=+1] include::web-cors.adoc[leveloffset=+1] diff --git a/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java b/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java index f55fab3c1c..5abd7693bd 100644 --- a/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java +++ b/src/test/java/org/springframework/core/env/EnvironmentSystemIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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,7 +16,6 @@ package org.springframework.core.env; - import java.io.File; import java.io.IOException; @@ -57,10 +56,6 @@ import org.springframework.web.context.support.GenericWebApplicationContext; import org.springframework.web.context.support.StandardServletEnvironment; import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.context.support.XmlWebApplicationContext; -import org.springframework.web.portlet.context.AbstractRefreshablePortletApplicationContext; -import org.springframework.web.portlet.context.StandardPortletEnvironment; -import org.springframework.web.portlet.context.StaticPortletApplicationContext; -import org.springframework.web.portlet.context.XmlPortletApplicationContext; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @@ -518,36 +513,6 @@ public class EnvironmentSystemIntegrationTests { assertEnvironmentAwareInvoked(ctx, prodEnv); } - @Test - public void staticPortletApplicationContext() { - StaticPortletApplicationContext ctx = new StaticPortletApplicationContext(); - - assertHasStandardPortletEnvironment(ctx); - - registerEnvironmentBeanDefinition(ctx); - - ctx.setEnvironment(prodEnv); - ctx.refresh(); - - assertHasEnvironment(ctx, prodEnv); - assertEnvironmentBeanRegistered(ctx); - assertEnvironmentAwareInvoked(ctx, prodEnv); - } - - @Test - public void xmlPortletApplicationContext() { - AbstractRefreshablePortletApplicationContext ctx = new XmlPortletApplicationContext(); - ctx.setEnvironment(prodEnv); - ctx.setConfigLocation("classpath:" + XML_PATH); - ctx.refresh(); - - assertHasEnvironment(ctx, prodEnv); - assertEnvironmentBeanRegistered(ctx); - assertEnvironmentAwareInvoked(ctx, prodEnv); - assertThat(ctx.containsBean(DEV_BEAN_NAME), is(false)); - assertThat(ctx.containsBean(PROD_BEAN_NAME), is(true)); - } - @Test public void abstractApplicationContextValidatesRequiredPropertiesOnRefresh() { { @@ -605,13 +570,6 @@ public class EnvironmentSystemIntegrationTests { assertThat(defaultEnv, instanceOf(StandardServletEnvironment.class)); } - private void assertHasStandardPortletEnvironment(WebApplicationContext ctx) { - // ensure a default portlet environment exists - Environment defaultEnv = ctx.getEnvironment(); - assertThat(defaultEnv, notNullValue()); - assertThat(defaultEnv, instanceOf(StandardPortletEnvironment.class)); - } - private void assertHasEnvironment(ApplicationContext ctx, Environment expectedEnv) { // ensure the custom environment took Environment actualEnv = ctx.getEnvironment();