language
stringclasses
1 value
owner
stringlengths
2
15
repo
stringlengths
2
21
sha
stringlengths
45
45
message
stringlengths
7
36.3k
path
stringlengths
1
199
patch
stringlengths
15
102k
is_multipart
bool
2 classes
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/resources/org/springframework/test/web/mock/client/samples/ludwig.json
@@ -0,0 +1,5 @@ +{ + "name" : "Ludwig van Beethoven", + "someDouble" : "1.6035", + "someBoolean" : "true" +} \ No newline at end of file
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/resources/org/springframework/test/web/mock/servlet/samples/context/TestContextTests-context.xml
@@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans:beans xmlns="http://www.springframework.org/schema/mvc" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:beans="http://www.springframework.org/schema/beans" + xsi:schemaLocation=" + http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> + + <annotation-driven /> + + <beans:bean id="testController" + class="org.springframework.test.web.server.samples.context.XmlTestContextTests$TestController"/> + +</beans:beans> \ No newline at end of file
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/resources/org/springframework/test/web/mock/servlet/samples/context/security.xml
@@ -0,0 +1,18 @@ +<b:beans xmlns:b="http://www.springframework.org/schema/beans" + xmlns="http://www.springframework.org/schema/security" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> + + <http auto-config="true" use-expressions="true"> + <intercept-url pattern="/**" access="hasRole('ROLE_USER')" /> + </http> + + <authentication-manager> + <authentication-provider> + <user-service> + <user name="user" password="password" authorities="ROLE_USER" /> + </user-service> + </authentication-provider> + </authentication-manager> +</b:beans>
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/resources/org/springframework/test/web/mock/servlet/samples/servlet-context.xml
@@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" + xsi:schemaLocation=" + http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> + + <mvc:annotation-driven /> + + <mvc:view-controller path="/" view-name="home" /> + + <mvc:resources mapping="/resources/**" location="/resources/" /> + + <mvc:default-servlet-handler /> + + <bean id="viewResolver" + class="org.springframework.web.servlet.view.UrlBasedViewResolver"> + <property name="viewClass" + value="org.springframework.web.servlet.view.tiles2.TilesView" /> + </bean> + + <bean id="tilesConfigurer" + class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"> + <property name="definitions"> + <value> + /WEB-INF/**/tiles.xml + </value> + </property> + </bean> + +</beans> \ No newline at end of file
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/webapp/WEB-INF/layouts/main.jsp
@@ -0,0 +1,12 @@ +<%@ page language="java" contentType="text/html; charset=UTF-8" + pageEncoding="UTF-8"%> +<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> +<html> +<head> +<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> +<title>Fake Layout</title> +</head> +<body> + +</body> +</html> \ No newline at end of file
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/webapp/WEB-INF/layouts/tiles.xml
@@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN" "http://tiles.apache.org/dtds/tiles-config_2_1.dtd"> + +<tiles-definitions> + + <definition name="mainLayout" templateExpression="/WEB-INF/layouts/main.jsp"/> + +</tiles-definitions>
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/webapp/WEB-INF/readme.txt
@@ -0,0 +1,2 @@ + +Dummy web application for testing purposes. \ No newline at end of file
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/webapp/WEB-INF/views/tiles.xml
@@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.1//EN" "http://tiles.apache.org/dtds/tiles-config_2_1.dtd"> + +<tiles-definitions> + + <definition name="form" extends="mainLayout"/> + +</tiles-definitions>
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/src/test/webapp/resources/Spring.js
@@ -0,0 +1,16 @@ +/* + * Copyright 2004-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. + */ +Spring={};Spring.debug=true;Spring.decorations={};Spring.decorations.applied=false;Spring.initialize=function(){Spring.applyDecorations();Spring.remoting=new Spring.RemotingHandler();};Spring.addDecoration=function(_1){if(!Spring.decorations[_1.elementId]){Spring.decorations[_1.elementId]=[];Spring.decorations[_1.elementId].push(_1);}else{var _2=false;for(var i=0;i<Spring.decorations[_1.elementId].length;i++){var _4=Spring.decorations[_1.elementId][i];if(_4.equals(_1)){if(_4.cleanup!=undefined){_4.cleanup();}Spring.decorations[_1.elementId][i]=_1;_2=true;break;}}if(!_2){Spring.decorations[_1.elementId].push(_1);}}if(Spring.decorations.applied){_1.apply();}};Spring.applyDecorations=function(){if(!Spring.decorations.applied){for(var _5 in Spring.decorations){for(var x=0;x<Spring.decorations[_5].length;x++){Spring.decorations[_5][x].apply();}}Spring.decorations.applied=true;}};Spring.validateAll=function(){var _7=true;for(var _8 in Spring.decorations){for(var x=0;x<Spring.decorations[_8].length;x++){if(Spring.decorations[_8][x].widget&&!Spring.decorations[_8][x].validate()){_7=false;}}}return _7;};Spring.validateRequired=function(){var _a=true;for(var _b in Spring.decorations){for(var x=0;x<Spring.decorations[_b].length;x++){if(Spring.decorations[_b][x].widget&&Spring.decorations[_b][x].isRequired()&&!Spring.decorations[_b][x].validate()){_a=false;}}}return _a;};Spring.AbstractElementDecoration=function(){};Spring.AbstractElementDecoration.prototype={elementId:"",widgetType:"",widgetModule:"",widget:null,widgetAttrs:{},apply:function(){},validate:function(){},isRequired:function(){},equals:function(_d){}};Spring.AbstractValidateAllDecoration=function(){};Spring.AbstractValidateAllDecoration.prototype={event:"",elementId:"",apply:function(){},cleanup:function(){},handleEvent:function(_e){},equals:function(_f){}};Spring.AbstractCommandLinkDecoration=function(){};Spring.AbstractCommandLinkDecoration.prototype={elementId:"",linkHtml:"",apply:function(){},submitFormFromLink:function(_10,_11,_12){},equals:function(_13){}};Spring.AbstractAjaxEventDecoration=function(){};Spring.AbstractAjaxEventDecoration.prototype={event:"",elementId:"",sourceId:"",formId:"",popup:false,params:{},apply:function(){},cleanup:function(){},submit:function(_14){},equals:function(_15){}};Spring.AbstractRemotingHandler=function(){};Spring.AbstractRemotingHandler.prototype={submitForm:function(_16,_17,_18){},getLinkedResource:function(_19,_1a,_1b){},getResource:function(_1c,_1d,_1e){},handleResponse:function(){},handleError:function(){}}; \ No newline at end of file
true
Other
spring-projects
spring-framework
22bcb54ab66c952d1c122526729b64d77a77280b.json
Add Spring MVC Test framework This commit adds the spring-test-mvc project [1] to the Spring Framework as part of the spring-test module. The sources are added as a root-level project called "spring-test-mvc" instead of under "spring-test" because the new sources need to be compiled with Servlet 3 while the current "spring-test" sources require Servlet 2.5 and the Eclipse IDE does not support having different classpaths for the same project. The Gradle build produces a single spring-test jar that contains sources from both "spring-test" and "spring-test-mvc". This merge is made possible through merge-dist.gradle as follows: - jar tasks of the "from" project execute tasks of the "to" project - "to" project is added to the classpath of the "from" project - "to" project pom is updated with entries from the "from" project For further details see documentation in merge-dist.gradle. Special thanks to everyone who contributed to the initial development of the Spring MVC Test framework: Arjen Poutsma <poutsma@mac.com> Craig Walls <cwalls@vmware.com> Frans Flippo <fransflippo@utopia.orange11.nl> Harry Lascelles <harry@firstbanco.com> Irfan <mail.urfi@gmail.com> Jörg Rathlev <joerg.rathlev@s24.com> Keesun Baik <whiteship2000@gmail.com> Keesun Baik <whiteship@epril.com> Matthew Reid <matthew.reid@nakedwines.com> Nils-Helge Garli Hegvik <Nils-Helge.Hegvik@telenor.com> Rob Winch <rwinch@vmware.com> Scott Frederick <sfrederick@vmware.com> Sven Filatov <sven.filatov@gmail.com> Thomas Bruyelle <thomas.bruyelle@gmail.com> youngm <youngm@gmail.com> [1]: https://github.com/SpringSource/spring-test-mvc Issue: SPR-9859, SPR-7951
spring-test-mvc/test-mvc.gradle
@@ -0,0 +1,2 @@ +ext.mergeIntoProject = project(':spring-test') +apply from: "${rootProject.projectDir}/merge-dist.gradle"
true
Other
spring-projects
spring-framework
ef9d35c473f046c66b6a7780ea3d38430bc0c58c.json
Add PATCH to "Allow" header for OPTIONS requests
spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java
@@ -785,7 +785,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response) String method = request.getMethod(); if (method.equalsIgnoreCase(RequestMethod.PATCH.name())) { - doPatch(request, response); + processRequest(request, response); } else { super.service(request, response); @@ -828,16 +828,6 @@ protected final void doPut(HttpServletRequest request, HttpServletResponse respo processRequest(request, response); } - /** - * Delegate PATCH requests to {@link #processRequest}. - * @see #doService - */ - protected final void doPatch(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - - processRequest(request, response); - } - /** * Delegate DELETE requests to {@link #processRequest}. * @see #doService @@ -867,6 +857,9 @@ protected void doOptions(HttpServletRequest request, HttpServletResponse respons } } super.doOptions(request, response); + String allowedMethods = response.getHeader("Allow"); + allowedMethods += ", " + RequestMethod.PATCH.name(); + response.setHeader("Allow", allowedMethods); } /**
true
Other
spring-projects
spring-framework
ef9d35c473f046c66b6a7780ea3d38430bc0c58c.json
Add PATCH to "Allow" header for OPTIONS requests
spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java
@@ -16,6 +16,12 @@ package org.springframework.web.servlet; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.sameInstance; +import static org.junit.Assert.assertThat; + import java.io.IOException; import java.util.Locale; @@ -60,9 +66,6 @@ import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.util.WebUtils; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - /** * @author Rod Johnson * @author Juergen Hoeller @@ -855,6 +858,14 @@ protected ConfigurableWebEnvironment createEnvironment() { assertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.class)); } + public void testAllowedOptionsIncludesPatchMethod() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "OPTIONS", "/foo"); + MockHttpServletResponse response = new MockHttpServletResponse(); + DispatcherServlet servlet = new DispatcherServlet(); + servlet.service(request, response); + assertThat(response.getHeader("Allow"), equalTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH")); + } + public static class ControllerFromParent implements Controller {
true
Other
spring-projects
spring-framework
0baa1a56c2f200d0cbd21a1318346670a4fa14d6.json
Add URI and method name on ResourceAccess Issue: SPR-9325
spring-web/src/main/java/org/springframework/web/client/RestTemplate.java
@@ -495,7 +495,8 @@ protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCal } } catch (IOException ex) { - throw new ResourceAccessException("I/O error: " + ex.getMessage(), ex); + throw new ResourceAccessException("I/O error on " + method.name() + + " request for \"" + url + "\":" + ex.getMessage(), ex); } finally { if (response != null) {
false
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewFilter.java
@@ -17,6 +17,7 @@ package org.springframework.orm.hibernate3.support; import java.io.IOException; +import java.util.concurrent.Callable; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -32,9 +33,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -195,14 +197,14 @@ protected void doFilterInternal( participate = true; } else { - if (isFirstRequest || !asyncManager.initializeAsyncThread(key)) { + if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) { logger.debug("Opening single Hibernate Session in OpenSessionInViewFilter"); Session session = getSession(sessionFactory); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - WebAsyncThreadInitializer initializer = createAsyncThreadInitializer(sessionFactory, sessionHolder); - asyncManager.registerAsyncThreadInitializer(key, initializer); + asyncManager.registerCallableInterceptor(key, + new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); } } } @@ -304,17 +306,40 @@ protected void closeSession(Session session, SessionFactory sessionFactory) { SessionFactoryUtils.closeSession(session); } - private WebAsyncThreadInitializer createAsyncThreadInitializer(final SessionFactory sessionFactory, - final SessionHolder sessionHolder) { + private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { + if (asyncManager.getCallableInterceptor(key) == null) { + return false; + } + ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + return true; + } + - return new WebAsyncThreadInitializer() { - public void initialize() { - TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - } - public void reset() { - TransactionSynchronizationManager.unbindResource(sessionFactory); - } - }; + /** + * Bind and unbind the Hibernate {@code Session} to the current thread. + */ + private static class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { + + private final SessionFactory sessionFactory; + + private final SessionHolder sessionHolder; + + public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { + this.sessionFactory = sessionFactory; + this.sessionHolder = sessionHolder; + } + + public void preProcess(NativeWebRequest request, Callable<?> task) { + initializeThread(); + } + + private void initializeThread() { + TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); + } + + public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.sessionFactory); + } } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/main/java/org/springframework/orm/hibernate3/support/OpenSessionInViewInterceptor.java
@@ -16,6 +16,8 @@ package org.springframework.orm.hibernate3.support; +import java.util.concurrent.Callable; + import org.hibernate.HibernateException; import org.hibernate.Session; import org.springframework.dao.DataAccessException; @@ -25,10 +27,11 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.ui.ModelMap; import org.springframework.web.context.request.AsyncWebRequestInterceptor; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; /** * Spring web request interceptor that binds a Hibernate <code>Session</code> to the @@ -147,7 +150,7 @@ public void preHandle(WebRequest request) throws DataAccessException { String participateAttributeName = getParticipateAttributeName(); if (asyncManager.hasConcurrentResult()) { - if (asyncManager.initializeAsyncThread(participateAttributeName)) { + if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { return; } } @@ -169,8 +172,8 @@ public void preHandle(WebRequest request) throws DataAccessException { SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - WebAsyncThreadInitializer asyncThreadInitializer = createThreadInitializer(sessionHolder); - asyncManager.registerAsyncThreadInitializer(participateAttributeName, asyncThreadInitializer); + asyncManager.registerCallableInterceptor(participateAttributeName, + new SessionBindingCallableInterceptor(sessionHolder)); } else { // deferred close mode @@ -261,15 +264,36 @@ protected String getParticipateAttributeName() { return getSessionFactory().toString() + PARTICIPATE_SUFFIX; } - private WebAsyncThreadInitializer createThreadInitializer(final SessionHolder sessionHolder) { - return new WebAsyncThreadInitializer() { - public void initialize() { - TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - } - public void reset() { - TransactionSynchronizationManager.unbindResource(getSessionFactory()); - } - }; + private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { + if (asyncManager.getCallableInterceptor(key) == null) { + return false; + } + ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + return true; } + + /** + * Bind and unbind the Hibernate {@code Session} to the current thread. + */ + private class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { + + private final SessionHolder sessionHolder; + + public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { + this.sessionHolder = sessionHolder; + } + + public void preProcess(NativeWebRequest request, Callable<?> task) { + initializeThread(); + } + + private void initializeThread() { + TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); + } + + public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(getSessionFactory()); + } + } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewFilter.java
@@ -17,6 +17,7 @@ package org.springframework.orm.hibernate4.support; import java.io.IOException; +import java.util.concurrent.Callable; import javax.servlet.FilterChain; import javax.servlet.ServletException; @@ -32,9 +33,10 @@ import org.springframework.orm.hibernate4.SessionHolder; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -126,14 +128,14 @@ protected void doFilterInternal( participate = true; } else { - if (isFirstRequest || !asyncManager.initializeAsyncThread(key)) { + if (isFirstRequest || !applySessionBindingInterceptor(asyncManager, key)) { logger.debug("Opening Hibernate Session in OpenSessionInViewFilter"); Session session = openSession(sessionFactory); SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - WebAsyncThreadInitializer initializer = createAsyncThreadInitializer(sessionFactory, sessionHolder); - asyncManager.registerAsyncThreadInitializer(key, initializer); + asyncManager.registerCallableInterceptor(key, + new SessionBindingCallableInterceptor(sessionFactory, sessionHolder)); } } @@ -201,17 +203,39 @@ protected Session openSession(SessionFactory sessionFactory) throws DataAccessRe } } - private WebAsyncThreadInitializer createAsyncThreadInitializer(final SessionFactory sessionFactory, - final SessionHolder sessionHolder) { - - return new WebAsyncThreadInitializer() { - public void initialize() { - TransactionSynchronizationManager.bindResource(sessionFactory, sessionHolder); - } - public void reset() { - TransactionSynchronizationManager.unbindResource(sessionFactory); - } - }; + private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { + if (asyncManager.getCallableInterceptor(key) == null) { + return false; + } + ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + return true; } + + /** + * Bind and unbind the Hibernate {@code Session} to the current thread. + */ + private static class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { + + private final SessionFactory sessionFactory; + + private final SessionHolder sessionHolder; + + public SessionBindingCallableInterceptor(SessionFactory sessionFactory, SessionHolder sessionHolder) { + this.sessionFactory = sessionFactory; + this.sessionHolder = sessionHolder; + } + + public void preProcess(NativeWebRequest request, Callable<?> task) { + initializeThread(); + } + + private void initializeThread() { + TransactionSynchronizationManager.bindResource(this.sessionFactory, this.sessionHolder); + } + + public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.sessionFactory); + } + } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/main/java/org/springframework/orm/hibernate4/support/OpenSessionInViewInterceptor.java
@@ -16,6 +16,8 @@ package org.springframework.orm.hibernate4.support; +import java.util.concurrent.Callable; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.FlushMode; @@ -29,10 +31,11 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.ui.ModelMap; import org.springframework.web.context.request.AsyncWebRequestInterceptor; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; /** * Spring web request interceptor that binds a Hibernate <code>Session</code> to the @@ -109,7 +112,7 @@ public void preHandle(WebRequest request) throws DataAccessException { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult()) { - if (asyncManager.initializeAsyncThread(participateAttributeName)) { + if (applySessionBindingInterceptor(asyncManager, participateAttributeName)) { return; } } @@ -126,8 +129,8 @@ public void preHandle(WebRequest request) throws DataAccessException { SessionHolder sessionHolder = new SessionHolder(session); TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - WebAsyncThreadInitializer asyncThreadInitializer = createThreadInitializer(sessionHolder); - asyncManager.registerAsyncThreadInitializer(participateAttributeName, asyncThreadInitializer); + asyncManager.registerCallableInterceptor(participateAttributeName, + new SessionBindingCallableInterceptor(sessionHolder)); } } @@ -200,15 +203,37 @@ protected String getParticipateAttributeName() { return getSessionFactory().toString() + PARTICIPATE_SUFFIX; } - private WebAsyncThreadInitializer createThreadInitializer(final SessionHolder sessionHolder) { - return new WebAsyncThreadInitializer() { - public void initialize() { - TransactionSynchronizationManager.bindResource(getSessionFactory(), sessionHolder); - } - public void reset() { - TransactionSynchronizationManager.unbindResource(getSessionFactory()); - } - }; + private boolean applySessionBindingInterceptor(WebAsyncManager asyncManager, String key) { + if (asyncManager.getCallableInterceptor(key) == null) { + return false; + } + ((SessionBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + return true; + } + + + /** + * Bind and unbind the Hibernate {@code Session} to the current thread. + */ + private class SessionBindingCallableInterceptor implements CallableProcessingInterceptor { + + private final SessionHolder sessionHolder; + + public SessionBindingCallableInterceptor(SessionHolder sessionHolder) { + this.sessionHolder = sessionHolder; + } + + public void preProcess(NativeWebRequest request, Callable<?> task) { + initializeThread(); + } + + private void initializeThread() { + TransactionSynchronizationManager.bindResource(getSessionFactory(), this.sessionHolder); + } + + public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(getSessionFactory()); + } } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewFilter.java
@@ -17,6 +17,7 @@ package org.springframework.orm.jpa.support; import java.io.IOException; +import java.util.concurrent.Callable; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -32,9 +33,10 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.StringUtils; import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; @@ -150,15 +152,14 @@ protected void doFilterInternal( participate = true; } else { - if (isFirstRequest || !asyncManager.initializeAsyncThread(key)) { + if (isFirstRequest || !applyEntityManagerBindingInterceptor(asyncManager, key)) { logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewFilter"); try { EntityManager em = createEntityManager(emf); EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(emf, emHolder); - WebAsyncThreadInitializer initializer = createAsyncThreadInitializer(emf, emHolder); - asyncManager.registerAsyncThreadInitializer(key, initializer); + asyncManager.registerCallableInterceptor(key, new EntityManagerBindingCallableInterceptor(emf, emHolder)); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); @@ -230,17 +231,40 @@ protected EntityManager createEntityManager(EntityManagerFactory emf) { return emf.createEntityManager(); } - private WebAsyncThreadInitializer createAsyncThreadInitializer(final EntityManagerFactory emFactory, - final EntityManagerHolder emHolder) { + private boolean applyEntityManagerBindingInterceptor(WebAsyncManager asyncManager, String key) { + if (asyncManager.getCallableInterceptor(key) == null) { + return false; + } + ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + return true; + } + + /** + * Bind and unbind the {@code EntityManager} to the current thread. + */ + private static class EntityManagerBindingCallableInterceptor implements CallableProcessingInterceptor { - return new WebAsyncThreadInitializer() { - public void initialize() { - TransactionSynchronizationManager.bindResource(emFactory, emHolder); - } - public void reset() { - TransactionSynchronizationManager.unbindResource(emFactory); - } - }; + private final EntityManagerFactory emFactory; + + private final EntityManagerHolder emHolder; + + + public EntityManagerBindingCallableInterceptor(EntityManagerFactory emFactory, EntityManagerHolder emHolder) { + this.emFactory = emFactory; + this.emHolder = emHolder; + } + + public void preProcess(NativeWebRequest request, Callable<?> task) { + initializeThread(); + } + + private void initializeThread() { + TransactionSynchronizationManager.bindResource(this.emFactory, this.emHolder); + } + + public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(this.emFactory); + } } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/main/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewInterceptor.java
@@ -16,6 +16,8 @@ package org.springframework.orm.jpa.support; +import java.util.concurrent.Callable; + import javax.persistence.EntityManager; import javax.persistence.PersistenceException; @@ -27,10 +29,11 @@ import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.ui.ModelMap; import org.springframework.web.context.request.AsyncWebRequestInterceptor; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.WebRequest; -import org.springframework.web.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; /** * Spring web request interceptor that binds a JPA EntityManager to the @@ -76,7 +79,7 @@ public void preHandle(WebRequest request) throws DataAccessException { WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); if (asyncManager.hasConcurrentResult()) { - if (asyncManager.initializeAsyncThread(participateAttributeName)) { + if (applyCallableInterceptor(asyncManager, participateAttributeName)) { return; } } @@ -94,8 +97,8 @@ public void preHandle(WebRequest request) throws DataAccessException { EntityManagerHolder emHolder = new EntityManagerHolder(em); TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); - WebAsyncThreadInitializer asyncThreadInitializer = createThreadInitializer(emHolder); - asyncManager.registerAsyncThreadInitializer(participateAttributeName, asyncThreadInitializer); + asyncManager.registerCallableInterceptor(participateAttributeName, + new EntityManagerBindingCallableInterceptor(emHolder)); } catch (PersistenceException ex) { throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex); @@ -147,15 +150,39 @@ protected String getParticipateAttributeName() { return getEntityManagerFactory().toString() + PARTICIPATE_SUFFIX; } - private WebAsyncThreadInitializer createThreadInitializer(final EntityManagerHolder emHolder) { - return new WebAsyncThreadInitializer() { - public void initialize() { - TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), emHolder); - } - public void reset() { - TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); - } - }; + + private boolean applyCallableInterceptor(WebAsyncManager asyncManager, String key) { + if (asyncManager.getCallableInterceptor(key) == null) { + return false; + } + ((EntityManagerBindingCallableInterceptor) asyncManager.getCallableInterceptor(key)).initializeThread(); + return true; + } + + + /** + * Bind and unbind the Hibernate {@code Session} to the current thread. + */ + private class EntityManagerBindingCallableInterceptor implements CallableProcessingInterceptor { + + private final EntityManagerHolder emHolder; + + + public EntityManagerBindingCallableInterceptor(EntityManagerHolder emHolder) { + this.emHolder = emHolder; + } + + public void preProcess(NativeWebRequest request, Callable<?> task) { + initializeThread(); + } + + private void initializeThread() { + TransactionSynchronizationManager.bindResource(getEntityManagerFactory(), this.emHolder); + } + + public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + TransactionSynchronizationManager.unbindResource(getEntityManagerFactory()); + } } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java
@@ -181,6 +181,7 @@ public void testOpenSessionInViewInterceptorAsyncScenario() throws Exception { replay(asyncWebRequest); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { @@ -196,10 +197,6 @@ public String call() throws Exception { // Async dispatch thread - reset(asyncWebRequest); - expect(asyncWebRequest.isDispatched()).andReturn(true); - replay(asyncWebRequest); - interceptor.preHandle(this.webRequest); assertTrue("Session not bound to async thread", TransactionSynchronizationManager.hasResource(sf)); @@ -496,10 +493,10 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo asyncWebRequest.addCompletionHandler((Runnable) anyObject()); asyncWebRequest.startAsync(); expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes(); - expect(asyncWebRequest.isDispatched()).andReturn(false).anyTimes(); replay(asyncWebRequest); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { public String call() throws Exception { @@ -524,7 +521,6 @@ public String call() throws Exception { expect(session.close()).andReturn(null); expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes(); - expect(asyncWebRequest.isDispatched()).andReturn(true).anyTimes(); replay(sf); replay(session);
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java
@@ -38,6 +38,7 @@ import junit.framework.TestCase; +import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.MockFilterConfig; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; @@ -158,6 +159,7 @@ public void testOpenEntityManagerInViewInterceptorAsyncScenario() throws Excepti replay(asyncWebRequest); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(webRequest); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { public String call() throws Exception { @@ -172,10 +174,6 @@ public String call() throws Exception { // Async dispatch thread - reset(asyncWebRequest); - expect(asyncWebRequest.isDispatched()).andReturn(true); - replay(asyncWebRequest); - reset(manager, factory); replay(manager, factory); @@ -348,10 +346,10 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo asyncWebRequest.addCompletionHandler((Runnable) anyObject()); asyncWebRequest.startAsync(); expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes(); - expect(asyncWebRequest.isDispatched()).andReturn(false).anyTimes(); replay(asyncWebRequest); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + asyncManager.setTaskExecutor(new SyncTaskExecutor()); asyncManager.setAsyncWebRequest(asyncWebRequest); asyncManager.startCallableProcessing(new Callable<String>() { public String call() throws Exception { @@ -372,7 +370,6 @@ public String call() throws Exception { reset(asyncWebRequest); expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes(); - expect(asyncWebRequest.isDispatched()).andReturn(true).anyTimes(); replay(asyncWebRequest); assertFalse(TransactionSynchronizationManager.hasResource(factory)); @@ -389,4 +386,12 @@ public String call() throws Exception { wac.close(); } + @SuppressWarnings("serial") + private static class SyncTaskExecutor extends SimpleAsyncTaskExecutor { + + @Override + public void execute(Runnable task, long startTimeout) { + task.run(); + } + } }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/AsyncWebRequest.java
@@ -41,6 +41,11 @@ public interface AsyncWebRequest extends NativeWebRequest { */ void setTimeoutHandler(Runnable runnable); + /** + * Add a Runnable to be invoked when request processing completes. + */ + void addCompletionHandler(Runnable runnable); + /** * Mark the start of asynchronous request processing so that when the main * processing thread exits, the response remains open for further processing @@ -62,17 +67,6 @@ public interface AsyncWebRequest extends NativeWebRequest { */ void dispatch(); - /** - * Whether the request was dispatched to the container in order to resume - * processing after concurrent execution in an application thread. - */ - boolean isDispatched(); - - /** - * Add a Runnable to be invoked when request processing completes. - */ - void addCompletionHandler(Runnable runnable); - /** * Whether asynchronous processing has completed. */
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/CallableInterceptorChain.java
@@ -0,0 +1,64 @@ +/* + * 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.context.request.async; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.web.context.request.NativeWebRequest; + +/** + * Assists with the invocation of {@link CallableProcessingInterceptor}'s. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +class CallableInterceptorChain { + + private static Log logger = LogFactory.getLog(CallableInterceptorChain.class); + + private final List<CallableProcessingInterceptor> interceptors; + + private int interceptorIndex = -1; + + + public CallableInterceptorChain(Collection<CallableProcessingInterceptor> interceptors) { + this.interceptors = new ArrayList<CallableProcessingInterceptor>(interceptors); + } + + public void applyPreProcess(NativeWebRequest request, Callable<?> task) throws Exception { + for (int i = 0; i < this.interceptors.size(); i++) { + this.interceptors.get(i).preProcess(request, task); + this.interceptorIndex = i; + } + } + + public void applyPostProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { + for (int i = this.interceptorIndex; i >= 0; i--) { + try { + this.interceptors.get(i).postProcess(request, task, concurrentResult); + } + catch (Exception ex) { + logger.error("CallableProcessingInterceptor.postProcess threw exception", ex); + } + } + } + +}
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptor.java
@@ -0,0 +1,67 @@ +/* + * 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.context.request.async; + +import java.util.concurrent.Callable; + +import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.WebRequestInterceptor; + +/** + * Intercepts concurrent request handling, where the concurrent result is + * obtained by executing a {@link Callable} on behalf of the application with an + * {@link AsyncTaskExecutor}. + * <p> + * A {@code CallableProcessingInterceptor} is invoked before and after the + * invocation of the {@code Callable} task in the asynchronous thread. + * + * <p>A {@code CallableProcessingInterceptor} may be registered as follows: + * <pre> + * CallableProcessingInterceptor interceptor = ... ; + * WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + * asyncManager.registerCallableInterceptor("key", interceptor); + * </pre> + * + * <p>To register an interceptor for every request, the above can be done through + * a {@link WebRequestInterceptor} during pre-handling. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public interface CallableProcessingInterceptor { + + /** + * Invoked from the asynchronous thread in which the {@code Callable} is + * executed, before the {@code Callable} is invoked. + * + * @param request the current request + * @param task the task that will produce a result + */ + void preProcess(NativeWebRequest request, Callable<?> task) throws Exception; + + /** + * Invoked from the asynchronous thread in which the {@code Callable} is + * executed, after the {@code Callable} returned a result. + * + * @param request the current request + * @param task the task that produced the result + * @param concurrentResult the result of concurrent processing, which could + * be a {@link Throwable} if the {@code Callable} raised an exception + */ + void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) throws Exception; + +}
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java
@@ -25,9 +25,9 @@ /** * {@code DeferredResult} provides an alternative to using a {@link Callable} - * for asynchronous request processing. While a Callable is executed concurrently - * on behalf of the application, with a DeferredResult the application can produce - * the result from a thread of its choice. + * for asynchronous request processing. While a {@code Callable} is executed + * concurrently on behalf of the application, with a {@code DeferredResult} the + * application can produce the result from a thread of its choice. * * @author Rossen Stoyanchev * @since 3.2 @@ -45,8 +45,6 @@ private DeferredResultHandler resultHandler; - private Object result = RESULT_NONE; - private final AtomicBoolean expired = new AtomicBoolean(false); private final Object lock = new Object(); @@ -79,7 +77,6 @@ public DeferredResult(Long timeout, Object timeoutResult) { this.timeout = timeout; } - /** * Return the configured timeout value in milliseconds. */ @@ -88,8 +85,12 @@ public Long getTimeoutMilliseconds() { } /** - * Set a handler to handle the result when set. Normally applications do not - * use this method at runtime but may do so during testing. + * Set a handler to handle the result when set. There can be only handler + * for a {@code DeferredResult}. At runtime it will be set by the framework. + * However applications may set it when unit testing. + * + * <p>If you need to be called back when a {@code DeferredResult} is set or + * expires, register a {@link DeferredResultProcessingInterceptor} instead. */ public void setResultHandler(DeferredResultHandler resultHandler) { this.resultHandler = resultHandler; @@ -122,14 +123,14 @@ public boolean setErrorResult(Object result) { } private boolean processResult(Object result) { + synchronized (this.lock) { - if (isSetOrExpired()) { + boolean wasExpired = getAndSetExpired(); + if (wasExpired) { return false; } - this.result = result; - if (!awaitResultHandler()) { throw new IllegalStateException("DeferredResultHandler not set"); } @@ -156,15 +157,24 @@ private boolean awaitResultHandler() { } /** - * Whether the DeferredResult can no longer be set either because the async - * request expired or because it was already set. + * Return {@code true} if this DeferredResult is no longer usable either + * because it was previously set or because the underlying request ended + * before it could be set. + * <p> + * The result may have been set with a call to {@link #setResult(Object)}, + * or {@link #setErrorResult(Object)}, or following a timeout, assuming a + * timeout result was provided to the constructor. The request may before + * the result set due to a timeout or network error. */ public boolean isSetOrExpired() { - return (this.expired.get() || (this.result != RESULT_NONE)); + return this.expired.get(); } - void setExpired() { - this.expired.set(true); + /** + * Atomically set the expired flag and return its previous value. + */ + boolean getAndSetExpired() { + return this.expired.getAndSet(true); } boolean hasTimeoutResult() {
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultInterceptorChain.java
@@ -0,0 +1,71 @@ +/* + * 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.context.request.async; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.web.context.request.NativeWebRequest; + +/** + * Assists with the invocation of {@link DeferredResultProcessingInterceptor}'s. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +class DeferredResultInterceptorChain { + + private static Log logger = LogFactory.getLog(DeferredResultInterceptorChain.class); + + private final List<DeferredResultProcessingInterceptor> interceptors; + + + public DeferredResultInterceptorChain(Collection<DeferredResultProcessingInterceptor> interceptors) { + this.interceptors = new ArrayList<DeferredResultProcessingInterceptor>(interceptors); + } + + public void applyPreProcess(NativeWebRequest request, DeferredResult<?> task) throws Exception { + for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { + interceptor.preProcess(request, task); + } + } + + public void applyPostProcess(NativeWebRequest request, DeferredResult<?> task, Object concurrentResult) { + for (int i = this.interceptors.size()-1; i >= 0; i--) { + try { + this.interceptors.get(i).postProcess(request, task, concurrentResult); + } + catch (Exception ex) { + logger.error("DeferredResultProcessingInterceptor.postProcess threw exception", ex); + } + } + } + + public void triggerAfterExpiration(NativeWebRequest request, DeferredResult<?> task) { + for (int i = this.interceptors.size()-1; i >= 0; i--) { + try { + this.interceptors.get(i).afterExpiration(request, task); + } + catch (Exception ex) { + logger.error("DeferredResultProcessingInterceptor.afterExpiration threw exception", ex); + } + } + } + +}
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptor.java
@@ -0,0 +1,83 @@ +/* + * 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.context.request.async; + +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.context.request.WebRequestInterceptor; + +/** + * Intercepts concurrent request handling, where the concurrent result is + * obtained by waiting for a {@link DeferredResult} to be set from a thread + * chosen by the application (e.g. in response to some external event). + * + * <p>A {@code DeferredResultProcessingInterceptor} is invoked before the start of + * asynchronous processing and either when the {@code DeferredResult} is set or + * when when the underlying request ends, whichever comes fist. + * + * <p>A {@code DeferredResultProcessingInterceptor} may be registered as follows: + * <pre> + * DeferredResultProcessingInterceptor interceptor = ... ; + * WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); + * asyncManager.registerDeferredResultInterceptor("key", interceptor); + * </pre> + * + * <p>To register an interceptor for every request, the above can be done through + * a {@link WebRequestInterceptor} during pre-handling. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public interface DeferredResultProcessingInterceptor { + + /** + * Invoked before the start of concurrent handling using a + * {@link DeferredResult}. The invocation occurs in the thread that + * initiated concurrent handling. + * + * @param request the current request + * @param deferredResult the DeferredResult instance + */ + void preProcess(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception; + + /** + * Invoked when a {@link DeferredResult} is set either with a normal value + * or with a {@link DeferredResult#DeferredResult(Long, Object) timeout + * result}. The invocation occurs in the thread that set the result. + * <p> + * If the request ends before the {@code DeferredResult} is set, then + * {@link #afterExpiration(NativeWebRequest, DeferredResult)} is called. + * + * @param request the current request + * @param deferredResult the DeferredResult that has been set + * @param concurrentResult the result to which the {@code DeferredResult} + * was set + */ + void postProcess(NativeWebRequest request, DeferredResult<?> deferredResult, + Object concurrentResult) throws Exception; + + + /** + * Invoked when a {@link DeferredResult} expires before a result has been + * set possibly due to a timeout or a network error. This invocation occurs + * in the thread where the timeout or network error notification is + * processed. + * + * @param request the current request + * @param deferredResult the DeferredResult that has been set + */ + void afterExpiration(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception; + +}
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/NoSupportAsyncWebRequest.java
@@ -49,10 +49,6 @@ public boolean isAsyncStarted() { return false; } - public boolean isDispatched() { - return false; - } - // Not supported public void startAsync() {
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java
@@ -24,7 +24,6 @@ import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; -import javax.servlet.DispatcherType; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -94,10 +93,6 @@ public boolean isAsyncStarted() { return ((this.asyncContext != null) && getRequest().isAsyncStarted()); } - public boolean isDispatched() { - return (DispatcherType.ASYNC.equals(getRequest().getDispatcherType())); - } - /** * Whether async request processing has completed. * <p>It is important to avoid use of request and response objects after async
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
@@ -15,10 +15,7 @@ */ package org.springframework.web.context.request.async; -import java.util.ArrayList; -import java.util.Collections; import java.util.LinkedHashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.Callable; @@ -73,7 +70,11 @@ public final class WebAsyncManager { private Object[] concurrentResultContext; - private final Map<Object, WebAsyncThreadInitializer> threadInitializers = new LinkedHashMap<Object, WebAsyncThreadInitializer>(); + private final Map<Object, CallableProcessingInterceptor> callableInterceptors = + new LinkedHashMap<Object, CallableProcessingInterceptor>(); + + private final Map<Object, DeferredResultProcessingInterceptor> deferredResultInterceptors = + new LinkedHashMap<Object, DeferredResultProcessingInterceptor>(); private static final UrlPathHelper urlPathHelper = new UrlPathHelper(); @@ -87,11 +88,13 @@ public final class WebAsyncManager { } /** - * Configure the {@link AsyncWebRequest} to use. This property may be - * set more than once during a single request to accurately reflect the - * current state of the request (e.g. following a forward, request/response - * wrapping, etc). However, it should not be set while concurrent handling is - * in progress, i.e. while {@link #isConcurrentHandlingStarted()} is {@code true}. + * Configure the {@link AsyncWebRequest} to use. This property may be set + * more than once during a single request to accurately reflect the current + * state of the request (e.g. following a forward, request/response + * wrapping, etc). However, it should not be set while concurrent handling + * is in progress, i.e. while {@link #isConcurrentHandlingStarted()} is + * {@code true}. + * * @param asyncWebRequest the web request to use */ public void setAsyncWebRequest(final AsyncWebRequest asyncWebRequest) { @@ -127,17 +130,18 @@ public boolean isConcurrentHandlingStarted() { } /** - * Whether the request has been dispatched to process the result of - * concurrent handling. + * Whether a result value exists as a result of concurrent handling. */ public boolean hasConcurrentResult() { - return ((this.concurrentResult != RESULT_NONE) && this.asyncWebRequest.isDispatched()); + return (this.concurrentResult != RESULT_NONE); } /** * Provides access to the result from concurrent handling. + * * @return an Object, possibly an {@code Exception} or {@code Throwable} if - * concurrent handling raised one. + * concurrent handling raised one. + * @see #clearConcurrentResult() */ public Object getConcurrentResult() { return this.concurrentResult; @@ -146,11 +150,46 @@ public Object getConcurrentResult() { /** * Provides access to additional processing context saved at the start of * concurrent handling. + * + * @see #clearConcurrentResult() */ public Object[] getConcurrentResultContext() { return this.concurrentResultContext; } + public CallableProcessingInterceptor getCallableInterceptor(Object key) { + return this.callableInterceptors.get(key); + } + + public DeferredResultProcessingInterceptor getDeferredResultInterceptor(Object key) { + return this.deferredResultInterceptors.get(key); + } + + /** + * Register a {@link CallableProcessingInterceptor} that will be applied + * when concurrent request handling with a {@link Callable} starts. + * + * @param key a unique the key under which to register the interceptor + * @param interceptor the interceptor to register + */ + public void registerCallableInterceptor(Object key, CallableProcessingInterceptor interceptor) { + Assert.notNull(interceptor, "interceptor is required"); + this.callableInterceptors.put(key, interceptor); + } + + /** + * Register a {@link DeferredResultProcessingInterceptor} that will be + * applied when concurrent request handling with a {@link DeferredResult} + * starts. + * + * @param key a unique the key under which to register the interceptor + * @param interceptor the interceptor to register + */ + public void registerDeferredResultInterceptor(Object key, DeferredResultProcessingInterceptor interceptor) { + Assert.notNull(interceptor, "interceptor is required"); + this.deferredResultInterceptors.put(key, interceptor); + } + /** * Clear {@linkplain #getConcurrentResult() concurrentResult} and * {@linkplain #getConcurrentResultContext() concurrentResultContext}. @@ -169,7 +208,7 @@ public void clearConcurrentResult() { * * @param callable a unit of work to be executed asynchronously * @param processingContext additional context to save that can be accessed - * via {@link #getConcurrentResultContext()} + * via {@link #getConcurrentResultContext()} * * @see #getConcurrentResult() * @see #getConcurrentResultContext() @@ -182,23 +221,19 @@ public void startCallableProcessing(final Callable<?> callable, Object... proces this.taskExecutor.submit(new Runnable() { public void run() { - List<WebAsyncThreadInitializer> initializers = - new ArrayList<WebAsyncThreadInitializer>(threadInitializers.values()); + + CallableInterceptorChain chain = + new CallableInterceptorChain(callableInterceptors.values()); try { - for (WebAsyncThreadInitializer initializer : initializers) { - initializer.initialize(); - } + chain.applyPreProcess(asyncWebRequest, callable); concurrentResult = callable.call(); } catch (Throwable t) { concurrentResult = t; } finally { - Collections.reverse(initializers); - for (WebAsyncThreadInitializer initializer : initializers) { - initializer.reset(); - } + chain.applyPostProcess(asyncWebRequest, callable, concurrentResult); } if (logger.isDebugEnabled()) { @@ -220,9 +255,10 @@ public void run() { * Use the given {@link AsyncTask} to configure the task executor as well as * the timeout value of the {@code AsyncWebRequest} before delegating to * {@link #startCallableProcessing(Callable, Object...)}. + * * @param asyncTask an asyncTask containing the target {@code Callable} * @param processingContext additional context to save that can be accessed - * via {@link #getConcurrentResultContext()} + * via {@link #getConcurrentResultContext()} */ public void startCallableProcessing(AsyncTask asyncTask, Object... processingContext) { Assert.notNull(asyncTask, "AsyncTask must not be null"); @@ -241,34 +277,30 @@ public void startCallableProcessing(AsyncTask asyncTask, Object... processingCon } /** - * Start concurrent request processing and initialize the given {@link DeferredResult} - * with a {@link DeferredResultHandler} that saves the result and dispatches - * the request to resume processing of that result. - * The {@code AsyncWebRequest} is also updated with a completion handler that - * expires the {@code DeferredResult} and a timeout handler assuming the - * {@code DeferredResult} has a default timeout result. + * Start concurrent request processing and initialize the given + * {@link DeferredResult} with a {@link DeferredResultHandler} that saves + * the result and dispatches the request to resume processing of that + * result. The {@code AsyncWebRequest} is also updated with a completion + * handler that expires the {@code DeferredResult} and a timeout handler + * assuming the {@code DeferredResult} has a default timeout result. * * @param deferredResult the DeferredResult instance to initialize * @param processingContext additional context to save that can be accessed - * via {@link #getConcurrentResultContext()} + * via {@link #getConcurrentResultContext()} * * @see #getConcurrentResult() * @see #getConcurrentResultContext() */ - public void startDeferredResultProcessing(final DeferredResult<?> deferredResult, Object... processingContext) { + public void startDeferredResultProcessing(final DeferredResult<?> deferredResult, + Object... processingContext) throws Exception { + Assert.notNull(deferredResult, "DeferredResult must not be null"); Long timeout = deferredResult.getTimeoutMilliseconds(); if (timeout != null) { this.asyncWebRequest.setTimeout(timeout); } - this.asyncWebRequest.addCompletionHandler(new Runnable() { - public void run() { - deferredResult.setExpired(); - } - }); - if (deferredResult.hasTimeoutResult()) { this.asyncWebRequest.setTimeoutHandler(new Runnable() { public void run() { @@ -277,6 +309,19 @@ public void run() { }); } + final DeferredResultInterceptorChain chain = + new DeferredResultInterceptorChain(this.deferredResultInterceptors.values()); + + chain.applyPreProcess(this.asyncWebRequest, deferredResult); + + this.asyncWebRequest.addCompletionHandler(new Runnable() { + public void run() { + if (!deferredResult.getAndSetExpired()) { + chain.triggerAfterExpiration(asyncWebRequest, deferredResult); + } + } + }); + startAsyncProcessing(processingContext); deferredResult.setResultHandler(new DeferredResultHandler() { @@ -287,8 +332,7 @@ public void handleResult(Object result) { logger.debug("Deferred result value [" + concurrentResult + "]"); } - Assert.state(!asyncWebRequest.isAsyncComplete(), - "Cannot handle DeferredResult [ " + deferredResult + " ] due to a timeout or network error"); + chain.applyPostProcess(asyncWebRequest, deferredResult, result); logger.debug("Dispatching request to complete processing"); asyncWebRequest.dispatch(); @@ -298,56 +342,17 @@ public void handleResult(Object result) { private void startAsyncProcessing(Object[] processingContext) { + clearConcurrentResult(); + this.concurrentResultContext = processingContext; + Assert.state(this.asyncWebRequest != null, "AsyncWebRequest must not be null"); this.asyncWebRequest.startAsync(); - this.concurrentResult = null; - this.concurrentResultContext = processingContext; - if (logger.isDebugEnabled()) { HttpServletRequest request = asyncWebRequest.getNativeRequest(HttpServletRequest.class); String requestUri = urlPathHelper.getRequestUri(request); logger.debug("Concurrent handling starting for " + request.getMethod() + " [" + requestUri + "]"); } } - /** - * Register an {@link WebAsyncThreadInitializer} for the current request. It may - * later be accessed and applied via {@link #initializeAsyncThread(String)} - * and will also be used to initialize and reset threads for concurrent handler execution. - * @param key a unique the key under which to keep the initializer - * @param initializer the initializer instance - */ - public void registerAsyncThreadInitializer(Object key, WebAsyncThreadInitializer initializer) { - Assert.notNull(initializer, "WebAsyncThreadInitializer must not be null"); - this.threadInitializers.put(key, initializer); - } - - /** - * Invoke the {@linkplain WebAsyncThreadInitializer#initialize() initialize()} - * method of the named {@link WebAsyncThreadInitializer}. - * @param key the key under which the initializer was registered - * @return whether an initializer was found and applied - */ - public boolean initializeAsyncThread(Object key) { - WebAsyncThreadInitializer initializer = this.threadInitializers.get(key); - if (initializer != null) { - initializer.initialize(); - return true; - } - return false; - } - - - /** - * Initialize and reset thread-bound variables. - */ - public interface WebAsyncThreadInitializer { - - void initialize(); - - void reset(); - - } - }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncUtils.java
@@ -64,10 +64,11 @@ public static WebAsyncManager getAsyncManager(WebRequest webRequest) { } /** - * Create an AsyncWebRequest instance. - * <p>By default an instance of {@link StandardServletAsyncWebRequest} is created - * if running in Servlet 3.0 (or higher) environment or as a fallback option an - * instance of {@link NoSupportAsyncWebRequest} is returned. + * Create an AsyncWebRequest instance. By default an instance of + * {@link StandardServletAsyncWebRequest} is created if running in Servlet + * 3.0 (or higher) environment or as a fallback, an instance of + * {@link NoSupportAsyncWebRequest} is returned. + * * @param request the current request * @param response the current response * @return an AsyncWebRequest instance, never {@code null}
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/test/java/org/springframework/web/context/request/async/DeferredResultTests.java
@@ -100,7 +100,7 @@ public void setExpired() { DeferredResult<String> result = new DeferredResult<String>(); assertFalse(result.isSetOrExpired()); - result.setExpired(); + result.getAndSetExpired(); assertTrue(result.isSetOrExpired()); assertFalse(result.setResult("hello")); }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java
@@ -35,7 +35,6 @@ import org.springframework.core.task.AsyncTaskExecutor; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; /** @@ -92,24 +91,26 @@ public void setAsyncWebRequestAfterAsyncStarted() { @Test public void startCallableProcessing() throws Exception { - WebAsyncThreadInitializer initializer = createStrictMock(WebAsyncThreadInitializer.class); - initializer.initialize(); - initializer.reset(); - replay(initializer); + Callable<Object> task = new Callable<Object>() { + public Object call() throws Exception { + return 1; + } + }; + + CallableProcessingInterceptor interceptor = createStrictMock(CallableProcessingInterceptor.class); + interceptor.preProcess(this.asyncWebRequest, task); + interceptor.postProcess(this.asyncWebRequest, task, new Integer(1)); + replay(interceptor); this.asyncWebRequest.startAsync(); expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); this.asyncWebRequest.dispatch(); replay(this.asyncWebRequest); - this.asyncManager.registerAsyncThreadInitializer("testInitializer", initializer); - this.asyncManager.startCallableProcessing(new Callable<Object>() { - public Object call() throws Exception { - return 1; - } - }); + this.asyncManager.registerCallableInterceptor("interceptor", interceptor); + this.asyncManager.startCallableProcessing(task); - verify(initializer, this.asyncWebRequest); + verify(interceptor, this.asyncWebRequest); } @Test @@ -159,26 +160,34 @@ public Object call() throws Exception { @Test public void startDeferredResultProcessing() throws Exception { + DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(1000L, 10); + this.asyncWebRequest.setTimeout(1000L); - this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); this.asyncWebRequest.setTimeoutHandler((Runnable) notNull()); + this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); this.asyncWebRequest.startAsync(); replay(this.asyncWebRequest); - DeferredResult<Integer> deferredResult = new DeferredResult<Integer>(1000L, 10); + DeferredResultProcessingInterceptor interceptor = createStrictMock(DeferredResultProcessingInterceptor.class); + interceptor.preProcess(this.asyncWebRequest, deferredResult); + replay(interceptor); + + this.asyncManager.registerDeferredResultInterceptor("interceptor", interceptor); this.asyncManager.startDeferredResultProcessing(deferredResult); - verify(this.asyncWebRequest); - reset(this.asyncWebRequest); + verify(this.asyncWebRequest, interceptor); + reset(this.asyncWebRequest, interceptor); - expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); this.asyncWebRequest.dispatch(); replay(this.asyncWebRequest); + interceptor.postProcess(asyncWebRequest, deferredResult, 25); + replay(interceptor); + deferredResult.setResult(25); assertEquals(25, this.asyncManager.getConcurrentResult()); - verify(this.asyncWebRequest); + verify(this.asyncWebRequest, interceptor); }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-webmvc/src/main/java/org/springframework/web/servlet/AsyncHandlerInterceptor.java
@@ -19,18 +19,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.web.method.HandlerMethod; + /** * Extends {@code HandlerInterceptor} with a callback method invoked during * asynchronous request handling. * * <p>When a handler starts asynchronous request handling, the DispatcherServlet * exits without invoking {@code postHandle} and {@code afterCompletion}, as it - * normally does, since the results of request handling (e.g. ModelAndView) are - * not available in the current thread and handling is not yet complete. - * In such scenarios, the + * normally does, since the results of request handling (e.g. ModelAndView) + * will. be produced concurrently in another thread. In such scenarios, * {@link #afterConcurrentHandlingStarted(HttpServletRequest, HttpServletResponse)} - * method is invoked instead allowing implementations to perform tasks such as - * cleaning up thread bound attributes. + * is invoked instead allowing implementations to perform tasks such as cleaning + * up thread bound attributes. * * <p>When asynchronous handling completes, the request is dispatched to the * container for further processing. At this stage the DispatcherServlet invokes @@ -40,20 +41,26 @@ * @since 3.2 * * @see org.springframework.web.context.request.async.WebAsyncManager + * @see org.springframework.web.context.request.async.CallableProcessingInterceptor + * @see org.springframework.web.context.request.async.DeferredResultProcessingInterceptor */ public interface AsyncHandlerInterceptor extends HandlerInterceptor { /** - * Called instead of {@code postHandle} and {@code afterCompletion}, when the - * a handler is being executed concurrently. Implementations may use the provided - * request and response but should avoid modifying them in ways that would - * conflict with the concurrent execution of the handler. A typical use of - * this method would be to clean thread local variables. + * Called instead of {@code postHandle} and {@code afterCompletion}, when + * the a handler is being executed concurrently. Implementations may use the + * provided request and response but should avoid modifying them in ways + * that would conflict with the concurrent execution of the handler. A + * typical use of this method would be to clean thread local variables. * * @param request the current request * @param response the current response - * @param handler handler that started async execution, for type and/or instance examination + * @param handler handler (or {@link HandlerMethod}) that started async + * execution, for type and/or instance examination + * @throws Exception in case of errors */ - void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler); + void afterConcurrentHandlingStarted( + HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception; }
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java
@@ -20,6 +20,7 @@ import java.security.Principal; import java.util.ArrayList; import java.util.Collections; +import java.util.concurrent.Callable; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -44,12 +45,13 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.request.NativeWebRequest; 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.context.request.async.WebAsyncUtils; +import org.springframework.web.context.request.async.CallableProcessingInterceptor; import org.springframework.web.context.request.async.WebAsyncManager; -import org.springframework.web.context.request.async.WebAsyncManager.WebAsyncThreadInitializer; +import org.springframework.web.context.request.async.WebAsyncUtils; import org.springframework.web.context.support.ServletRequestHandledEvent; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.context.support.XmlWebApplicationContext; @@ -909,7 +911,7 @@ protected final void processRequest(HttpServletRequest request, HttpServletRespo initContextHolders(request, localeContext, requestAttributes); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); - asyncManager.registerAsyncThreadInitializer(this.getClass().getName(), createAsyncThreadInitializer(request)); + asyncManager.registerCallableInterceptor(this.getClass().getName(), createRequestBindingInterceptor(request)); try { doService(request, response); @@ -992,13 +994,15 @@ private void resetContextHolders(HttpServletRequest request, } } - private WebAsyncThreadInitializer createAsyncThreadInitializer(final HttpServletRequest request) { + private CallableProcessingInterceptor createRequestBindingInterceptor(final HttpServletRequest request) { - return new WebAsyncThreadInitializer() { - public void initialize() { + return new CallableProcessingInterceptor() { + + public void preProcess(NativeWebRequest webRequest, Callable<?> task) { initContextHolders(request, buildLocaleContext(request), new ServletRequestAttributes(request)); } - public void reset() { + + public void postProcess(NativeWebRequest webRequest, Callable<?> task, Object concurrentResult) { resetContextHolders(request, null, null); } };
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-webmvc/src/main/java/org/springframework/web/servlet/HandlerInterceptor.java
@@ -19,6 +19,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.web.method.HandlerMethod; + /** * Workflow interface that allows for customized handler execution chains. * Applications can register any number of existing or custom interceptors @@ -36,8 +38,8 @@ * {@code postHandle} and {@code afterCompletion} callbacks. When concurrent * handler execution completes, the request is dispatched back in order to * proceed with rendering the model and all methods of this contract are invoked - * again. For further options and comments see - * {@code org.springframework.web.servlet.HandlerInterceptor} + * again. For further options and details see + * {@code org.springframework.web.servlet.AsyncHandlerInterceptor} * * <p>Typically an interceptor chain is defined per HandlerMapping bean, * sharing its granularity. To be able to apply a certain interceptor chain @@ -100,7 +102,8 @@ boolean preHandle(HttpServletRequest request, HttpServletResponse response, Obje * getting applied in inverse order of the execution chain. * @param request current HTTP request * @param response current HTTP response - * @param handler chosen handler to execute, for type and/or instance examination + * @param handler handler (or {@link HandlerMethod}) that started async + * execution, for type and/or instance examination * @param modelAndView the <code>ModelAndView</code> that the handler returned * (can also be <code>null</code>) * @throws Exception in case of errors @@ -120,7 +123,8 @@ void postHandle( * the last to be invoked. * @param request current HTTP request * @param response current HTTP response - * @param handler chosen handler to execute, for type and/or instance examination + * @param handler handler (or {@link HandlerMethod}) that started async + * execution, for type and/or instance examination * @param ex exception thrown on handler execution, if any * @throws Exception in case of errors */
true
Other
spring-projects
spring-framework
57c36dd39500654caeea124519257696d98f9f14.json
Add interceptors for async processing This change introduces two new interceptors with callback methods for concurrent request handling. These interfaces are CallableProcessingInterceptor and DeferredResultProcessingInterceptor. Unlike a HandlerInterceptor, and its AsyncHandlerInterceptor sub-type, which intercepts the invocation of a handler in he main request processing thread, the two new interfaces are aimed at intercepting the asynchronous execution of a Callable or a DeferredResult. This allows for the registration of thread initialization logic in the case of Callable executed with an AsyncTaskExecutor, or for centralized tracking of the completion and/or expiration of a DeferredResult.
spring-webmvc/src/main/java/org/springframework/web/servlet/handler/HandlerInterceptorAdapter.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * 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. @@ -19,7 +19,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.AsyncHandlerInterceptor; import org.springframework.web.servlet.ModelAndView; /** @@ -29,7 +29,7 @@ * @author Juergen Hoeller * @since 05.12.2003 */ -public abstract class HandlerInterceptorAdapter implements HandlerInterceptor { +public abstract class HandlerInterceptorAdapter implements AsyncHandlerInterceptor { /** * This implementation always returns <code>true</code>. @@ -55,4 +55,12 @@ public void afterCompletion( throws Exception { } + /** + * This implementation is empty. + */ + public void afterConcurrentHandlingStarted( + HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + } + }
true
Other
spring-projects
spring-framework
f191a55b8f570130f751c843d034451c6a277be3.json
Preserve comments when using JibxMarshaller Prior to this commit, JibxMarshaller used a SAX ContentHandler to marshal to StAX XMLEventWriters, which inadvertently resulted in the deletion of XML comments. After this commit, JibxMarshaller adapts the XMLEventWriter into an XMLStreamWriter and comments are preserved. Issue: SPR-9768
spring-core/src/main/java/org/springframework/util/xml/StaxUtils.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * 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. @@ -309,6 +309,15 @@ public static XMLStreamReader createEventStreamReader(XMLEventReader eventReader return new XMLEventStreamReader(eventReader); } + /** + * Return a {@link XMLStreamWriter} that writes to a {@link XMLEventWriter}. + * @return a stream writer that writes to an event writer + * @since 3.2 + */ + public static XMLStreamWriter createEventStreamWriter(XMLEventWriter eventWriter) { + return new XMLEventStreamWriter(eventWriter, XMLEventFactory.newFactory()); + } + /** * Return a {@link XMLStreamWriter} that writes to a {@link XMLEventWriter}. * @return a stream writer that writes to an event writer
true
Other
spring-projects
spring-framework
f191a55b8f570130f751c843d034451c6a277be3.json
Preserve comments when using JibxMarshaller Prior to this commit, JibxMarshaller used a SAX ContentHandler to marshal to StAX XMLEventWriters, which inadvertently resulted in the deletion of XML comments. After this commit, JibxMarshaller adapts the XMLEventWriter into an XMLStreamWriter and comments are preserved. Issue: SPR-9768
spring-core/src/main/java/org/springframework/util/xml/XMLEventStreamWriter.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * 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. @@ -193,7 +193,7 @@ public void close() throws XMLStreamException { private void writeStartElement(StartElement startElement) throws XMLStreamException { eventWriter.add(startElement); - endElements.add(eventFactory.createEndElement(startElement.getName(), null)); + endElements.add(eventFactory.createEndElement(startElement.getName(), startElement.getNamespaces())); } private void writeNamespace(Namespace namespace) throws XMLStreamException {
true
Other
spring-projects
spring-framework
f191a55b8f570130f751c843d034451c6a277be3.json
Preserve comments when using JibxMarshaller Prior to this commit, JibxMarshaller used a SAX ContentHandler to marshal to StAX XMLEventWriters, which inadvertently resulted in the deletion of XML comments. After this commit, JibxMarshaller adapts the XMLEventWriter into an XMLStreamWriter and comments are preserved. Issue: SPR-9768
spring-core/src/test/java/org/springframework/util/xml/XMLEventStreamWriterTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -29,8 +29,7 @@ public class XMLEventStreamWriterTests { private static final String XML = - "<?pi content?><root xmlns='namespace'><prefix:child xmlns:prefix='namespace2'>content</prefix:child></root>" - ; + "<?pi content?><root xmlns='namespace'><prefix:child xmlns:prefix='namespace2'><!--comment-->content</prefix:child></root>"; private XMLEventStreamWriter streamWriter; @@ -52,6 +51,7 @@ public void write() throws Exception { streamWriter.writeDefaultNamespace("namespace"); streamWriter.writeStartElement("prefix", "child", "namespace2"); streamWriter.writeNamespace("prefix", "namespace2"); + streamWriter.writeComment("comment"); streamWriter.writeCharacters("content"); streamWriter.writeEndElement(); streamWriter.writeEndElement(); @@ -61,4 +61,4 @@ public void write() throws Exception { } -} \ No newline at end of file +}
true
Other
spring-projects
spring-framework
f191a55b8f570130f751c843d034451c6a277be3.json
Preserve comments when using JibxMarshaller Prior to this commit, JibxMarshaller used a SAX ContentHandler to marshal to StAX XMLEventWriters, which inadvertently resulted in the deletion of XML comments. After this commit, JibxMarshaller adapts the XMLEventWriter into an XMLStreamWriter and comments are preserved. Issue: SPR-9768
spring-oxm/src/main/java/org/springframework/oxm/jibx/JibxMarshaller.java
@@ -338,8 +338,8 @@ private void transformAndMarshal(Object graph, Result result) throws IOException @Override protected void marshalXmlEventWriter(Object graph, XMLEventWriter eventWriter) { - ContentHandler contentHandler = StaxUtils.createContentHandler(eventWriter); - marshalSaxHandlers(graph, contentHandler, null); + XMLStreamWriter streamWriter = StaxUtils.createEventStreamWriter(eventWriter); + marshalXmlStreamWriter(graph, streamWriter); }
true
Other
spring-projects
spring-framework
323ac6ad01328d1ac400d001c65ea89c7be98191.json
Release version 3.2.0.M2
gradle.properties
@@ -1 +1 @@ -version=3.2.0.BUILD-SNAPSHOT +version=3.2.0.M2
false
Other
spring-projects
spring-framework
2ff3d53962c1249dccfb493eb46f12e30612de05.json
Ignore parse errors in HttpPutFormContentFilter Errors when parsing the request content-type, in order to find out if the request has form content, are translated to false. Issue: SPR-9769
spring-web/src/main/java/org/springframework/web/filter/HttpPutFormContentFilter.java
@@ -87,14 +87,18 @@ public InputStream getBody() throws IOException { else { filterChain.doFilter(request, response); } - } private boolean isFormContentType(HttpServletRequest request) { String contentType = request.getContentType(); if (contentType != null) { - MediaType mediaType = MediaType.parseMediaType(contentType); - return (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType)); + try { + MediaType mediaType = MediaType.parseMediaType(contentType); + return (MediaType.APPLICATION_FORM_URLENCODED.includes(mediaType)); + } + catch (IllegalArgumentException ex) { + return false; + } } else { return false;
true
Other
spring-projects
spring-framework
2ff3d53962c1249dccfb493eb46f12e30612de05.json
Ignore parse errors in HttpPutFormContentFilter Errors when parsing the request content-type, in order to find out if the request has form content, are translated to false. Issue: SPR-9769
spring-web/src/test/java/org/springframework/web/filter/HttpPutFormContentFilterTests.java
@@ -87,6 +87,15 @@ public void wrapFormEncodedOnly() throws Exception { } } + @Test + public void invalidMediaType() throws Exception { + request.setContent("".getBytes("ISO-8859-1")); + request.setContentType("foo"); + filterChain = new MockFilterChain(); + filter.doFilter(request, response, filterChain); + assertSame(request, filterChain.getRequest()); + } + @Test public void getParameter() throws Exception { request.setContent("name=value".getBytes("ISO-8859-1"));
true
Other
spring-projects
spring-framework
fc859ffd6e0d5ca8e69b736bc93baf8081b89932.json
Update Javadoc in ExtendedBeanInfo - updated the link to the "indexed properties" section of the JavaBeans tutorial
spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java
@@ -45,7 +45,7 @@ * {@link Introspector#getBeanInfo(Class)}) by including non-void returning setter * methods in the collection of {@link #getPropertyDescriptors() property descriptors}. * Both regular and - * <a href="http://download.oracle.com/javase/tutorial/javabeans/properties/indexed.html"> + * <a href="http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html"> * indexed properties</a> are fully supported. * * <p>The wrapped {@code BeanInfo} object is not modified in any way. @@ -371,7 +371,8 @@ public PropertyDescriptor[] getPropertyDescriptors() { /** - * Sorts PropertyDescriptor instances alphanumerically to emulate the behavior of {@link java.beans.BeanInfo#getPropertyDescriptors()}. + * Sorts PropertyDescriptor instances alpha-numerically to emulate the behavior of + * {@link java.beans.BeanInfo#getPropertyDescriptors()}. * * @see ExtendedBeanInfo#propertyDescriptors */
true
Other
spring-projects
spring-framework
fc859ffd6e0d5ca8e69b736bc93baf8081b89932.json
Update Javadoc in ExtendedBeanInfo - updated the link to the "indexed properties" section of the JavaBeans tutorial
spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfoFactory.java
@@ -41,7 +41,7 @@ class ExtendedBeanInfoFactory implements Ordered, BeanInfoFactory { /** * Return whether the given bean class declares or inherits any non-void returning - * JavaBeans or <em>indexed</em> setter methods. + * JavaBeans or <em>indexed property</em> setter methods. */ public boolean supports(Class<?> beanClass) { for (Method method : beanClass.getMethods()) {
true
Other
spring-projects
spring-framework
0721146b14e3df3bde3e6e8f2a871bb0b995ef4f.json
Improve regex for parsing query params Previously UriComponentsBuilder used a regular expression for parsing query name-value pairs where both name and value were expected to not contain neither '&', not '='. The idea is that the presence of reserved characters makes it impossible to guess correctly how to parse the query string (e.g. a=b&c). This change relaxes the constraint on query param values, allowing them to contain '='. In effect '&' is the ultimate separator of name-value pairs, and any '=' in values is ignored. For example "q=1USD=?EUR" is interpreted as "q equals '1USD=?EUR'". Issue: SPR-9832
spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java
@@ -53,7 +53,7 @@ */ public class UriComponentsBuilder { - private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)=?([^&=]+)?"); + private static final Pattern QUERY_PARAM_PATTERN = Pattern.compile("([^&=]+)=?([^&]+)?"); private static final String SCHEME_PATTERN = "([^:/?#]+):";
true
Other
spring-projects
spring-framework
0721146b14e3df3bde3e6e8f2a871bb0b995ef4f.json
Improve regex for parsing query params Previously UriComponentsBuilder used a regular expression for parsing query name-value pairs where both name and value were expected to not contain neither '&', not '='. The idea is that the presence of reserved characters makes it impossible to guess correctly how to parse the query string (e.g. a=b&c). This change relaxes the constraint on query param values, allowing them to contain '='. In effect '&' is the ultimate separator of name-value pairs, and any '=' in values is ignored. For example "q=1USD=?EUR" is interpreted as "q equals '1USD=?EUR'". Issue: SPR-9832
spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java
@@ -146,6 +146,16 @@ public void fromUriString() { assertEquals("28", result.getFragment()); } + // SPR-9832 + + @Test + public void fromUriStringQueryParamWithReservedCharInValue() throws URISyntaxException { + String uri = "http://www.google.com/ig/calculator?q=1USD=?EUR"; + UriComponents result = UriComponentsBuilder.fromUriString(uri).build(); + + assertEquals("q=1USD=?EUR", result.getQuery()); + assertEquals("1USD=?EUR", result.getQueryParams().getFirst("q")); + } @Test public void path() throws URISyntaxException {
true
Other
spring-projects
spring-framework
2f504dda3a8fe682f2ca789955818c9a5609f19e.json
Update remoting chapter (minor) Issue: SPR-9822
src/reference/docbook/new-in-3.2.xml
@@ -38,6 +38,21 @@ </section> + <section id="new-in-3.2-spring-mvc-test"> + <title>Spring MVC Test framework</title> + + <para>First-class support for testing Spring MVC applications with a + fluent API and without a servlet container. Server-side tests involve + use of the <classname>DispatcherServlet</classname> while client-side + REST tests rely on the <classname>RestTemplate</classname>. + See the following presentation for more information before + documentation is added: + <ulink url="https://github.com/rstoyanchev/spring-32-test-webapps"> + "Testing Web Applications with Spring 3.2"</ulink>. + </para> + + </section> + <section id="new-in-3.2-webmvc-content-negotiation"> <title>Content negotiation improvements</title>
true
Other
spring-projects
spring-framework
2f504dda3a8fe682f2ca789955818c9a5609f19e.json
Update remoting chapter (minor) Issue: SPR-9822
src/reference/docbook/remoting.xml
@@ -1389,15 +1389,15 @@ String result = specifying an implementation of <interfacename>ClientHttpRequestFactory</interfacename>. Spring provides the implementation - <classname>CommonsClientHttpRequestFactory</classname> that uses the - Jakarta Commons <classname>HttpClient</classname> to create requests. - <classname>CommonsClientHttpRequestFactory</classname> is configured + <classname>HttpComponentsClientHttpRequestFactory</classname> that uses the + Apache HttpComponents <classname>HttpClient</classname> to create requests. + <classname>HttpComponentsClientHttpRequestFactory</classname> is configured using an instance of - <classname>org.apache.commons.httpclient.HttpClient</classname> which + <classname>org.apache.http.client.HttpClient</classname> which can in turn be configured with credentials information or connection pooling functionality.</para> - <para>The previous example using Jakarta Commons + <para>The previous example using Apache HttpComponents <classname>HttpClient</classname> directly rewritten to use the <classname>RestTemplate</classname> is shown below</para>
true
Other
spring-projects
spring-framework
ff8a6e8fdb147e1b988c1ca5b4c8b3008b67534d.json
Remove code duplication in ModelAndViewAssert ModelAndViewAssert now uses assertion methods in the newly introduced AssertionErrors class.
spring-test/src/main/java/org/springframework/test/web/ModelAndViewAssert.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * 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. @@ -16,6 +16,8 @@ package org.springframework.test.web; +import static org.springframework.test.util.AssertionErrors.*; + import java.util.Collections; import java.util.Comparator; import java.util.HashSet; @@ -55,12 +57,12 @@ public abstract class ModelAndViewAssert { */ @SuppressWarnings("unchecked") public static <T> T assertAndReturnModelAttributeOfType(ModelAndView mav, String modelName, Class<T> expectedType) { - assertCondition(mav != null, "ModelAndView is null"); - assertCondition(mav.getModel() != null, "Model is null"); + assertTrue("ModelAndView is null", mav != null); + assertTrue("Model is null", mav.getModel() != null); Object obj = mav.getModel().get(modelName); - assertCondition(obj != null, "Model attribute with name '" + modelName + "' is null"); - assertCondition(expectedType.isAssignableFrom(obj.getClass()), "Model attribute is not of expected type '" - + expectedType.getName() + "' but rather of type '" + obj.getClass().getName() + "'"); + assertTrue("Model attribute with name '" + modelName + "' is null", obj != null); + assertTrue("Model attribute is not of expected type '" + expectedType.getName() + "' but rather of type '" + + obj.getClass().getName() + "'", expectedType.isAssignableFrom(obj.getClass())); return (T) obj; } @@ -74,12 +76,13 @@ public static <T> T assertAndReturnModelAttributeOfType(ModelAndView mav, String */ @SuppressWarnings("rawtypes") public static void assertCompareListModelAttribute(ModelAndView mav, String modelName, List expectedList) { - assertCondition(mav != null, "ModelAndView is null"); + assertTrue("ModelAndView is null", mav != null); List modelList = assertAndReturnModelAttributeOfType(mav, modelName, List.class); - assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() - + "' while size of expected list is '" + expectedList.size() + "'"); - assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName - + "' is not equal to the expected list."); + assertTrue( + "Size of model list is '" + modelList.size() + "' while size of expected list is '" + expectedList.size() + + "'", expectedList.size() == modelList.size()); + assertTrue("List in model under name '" + modelName + "' is not equal to the expected list.", + expectedList.equals(modelList)); } /** @@ -90,10 +93,10 @@ public static void assertCompareListModelAttribute(ModelAndView mav, String mode * <code>null</code>) */ public static void assertModelAttributeAvailable(ModelAndView mav, String modelName) { - assertCondition(mav != null, "ModelAndView is null"); - assertCondition(mav.getModel() != null, "Model is null"); - assertCondition(mav.getModel().containsKey(modelName), "Model attribute with name '" + modelName - + "' is not available"); + assertTrue("ModelAndView is null", mav != null); + assertTrue("Model is null", mav.getModel() != null); + assertTrue("Model attribute with name '" + modelName + "' is not available", + mav.getModel().containsKey(modelName)); } /** @@ -106,10 +109,10 @@ public static void assertModelAttributeAvailable(ModelAndView mav, String modelN * @param expectedValue the model value */ public static void assertModelAttributeValue(ModelAndView mav, String modelName, Object expectedValue) { - assertCondition(mav != null, "ModelAndView is null"); + assertTrue("ModelAndView is null", mav != null); Object modelValue = assertAndReturnModelAttributeOfType(mav, modelName, Object.class); - assertCondition(modelValue.equals(expectedValue), "Model value with name '" + modelName - + "' is not the same as the expected value which was '" + expectedValue + "'"); + assertTrue("Model value with name '" + modelName + "' is not the same as the expected value which was '" + + expectedValue + "'", modelValue.equals(expectedValue)); } /** @@ -120,8 +123,8 @@ public static void assertModelAttributeValue(ModelAndView mav, String modelName, * @param expectedModel the expected model */ public static void assertModelAttributeValues(ModelAndView mav, Map<String, Object> expectedModel) { - assertCondition(mav != null, "ModelAndView is null"); - assertCondition(mav.getModel() != null, "Model is null"); + assertTrue("ModelAndView is null", mav != null); + assertTrue("Model is null", mav.getModel() != null); if (!mav.getModel().keySet().equals(expectedModel.keySet())) { StringBuilder sb = new StringBuilder("Keyset of expected model does not match.\n"); @@ -161,11 +164,12 @@ public static void assertModelAttributeValues(ModelAndView mav, Map<String, Obje public static void assertSortAndCompareListModelAttribute(ModelAndView mav, String modelName, List expectedList, Comparator comparator) { - assertCondition(mav != null, "ModelAndView is null"); + assertTrue("ModelAndView is null", mav != null); List modelList = assertAndReturnModelAttributeOfType(mav, modelName, List.class); - assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() - + "' while size of expected list is '" + expectedList.size() + "'"); + assertTrue( + "Size of model list is '" + modelList.size() + "' while size of expected list is '" + expectedList.size() + + "'", expectedList.size() == modelList.size()); if (comparator != null) { Collections.sort(modelList, comparator); @@ -176,8 +180,8 @@ public static void assertSortAndCompareListModelAttribute(ModelAndView mav, Stri Collections.sort(expectedList); } - assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName - + "' is not equal to the expected list."); + assertTrue("List in model under name '" + modelName + "' is not equal to the expected list.", + expectedList.equals(modelList)); } /** @@ -188,35 +192,9 @@ public static void assertSortAndCompareListModelAttribute(ModelAndView mav, Stri * @param expectedName the name of the model value */ public static void assertViewName(ModelAndView mav, String expectedName) { - assertCondition(mav != null, "ModelAndView is null"); - assertCondition(ObjectUtils.nullSafeEquals(expectedName, mav.getViewName()), "View name is not equal to '" - + expectedName + "' but was '" + mav.getViewName() + "'"); - } - - /** - * Fails by throwing an <code>AssertionError</code> with the supplied - * <code>message</code>. - * - * @param message the exception message to use - * @see #assertCondition(boolean,String) - */ - private static void fail(String message) { - throw new AssertionError(message); - } - - /** - * Assert the provided boolean <code>condition</code>, throwing - * <code>AssertionError</code> with the supplied <code>message</code> if the - * test result is <code>false</code>. - * - * @param condition a boolean expression - * @param message the exception message to use if the assertion fails - * @see #fail(String) - */ - private static void assertCondition(boolean condition, String message) { - if (!condition) { - fail(message); - } + assertTrue("ModelAndView is null", mav != null); + assertTrue("View name is not equal to '" + expectedName + "' but was '" + mav.getViewName() + "'", + ObjectUtils.nullSafeEquals(expectedName, mav.getViewName())); } private static void appendNonMatchingSetsErrorMessage(Set<String> assertionSet, Set<String> incorrectSet,
false
Other
spring-projects
spring-framework
dbcbdace9e83a020e35ed95f203fbbdb632f2a85.json
Parameterize AsyncTask type
spring-web/src/main/java/org/springframework/web/context/request/async/AsyncTask.java
@@ -27,9 +27,9 @@ * @author Rossen Stoyanchev * @since 3.2 */ -public class AsyncTask { +public class AsyncTask<V> { - private final Callable<?> callable; + private final Callable<V> callable; private final Long timeout; @@ -45,7 +45,7 @@ public class AsyncTask { * @param timeout timeout value in milliseconds * @param callable the callable for concurrent handling */ - public AsyncTask(long timeout, Callable<?> callable) { + public AsyncTask(long timeout, Callable<V> callable) { this(timeout, null, null, callable); Assert.notNull(timeout, "Timeout must not be null"); } @@ -55,7 +55,7 @@ public AsyncTask(long timeout, Callable<?> callable) { * @param timeout timeout value in milliseconds; ignored if {@code null} * @param callable the callable for concurrent handling */ - public AsyncTask(Long timeout, String executorName, Callable<?> callable) { + public AsyncTask(Long timeout, String executorName, Callable<V> callable) { this(timeout, null, executorName, callable); Assert.notNull(executor, "Executor name must not be null"); } @@ -65,12 +65,12 @@ public AsyncTask(Long timeout, String executorName, Callable<?> callable) { * @param timeout timeout value in milliseconds; ignored if {@code null} * @param callable the callable for concurrent handling */ - public AsyncTask(Long timeout, AsyncTaskExecutor executor, Callable<?> callable) { + public AsyncTask(Long timeout, AsyncTaskExecutor executor, Callable<V> callable) { this(timeout, executor, null, callable); Assert.notNull(executor, "Executor must not be null"); } - private AsyncTask(Long timeout, AsyncTaskExecutor executor, String executorName, Callable<?> callable) { + private AsyncTask(Long timeout, AsyncTaskExecutor executor, String executorName, Callable<V> callable) { Assert.notNull(callable, "Callable must not be null"); this.callable = callable; this.timeout = timeout;
true
Other
spring-projects
spring-framework
dbcbdace9e83a020e35ed95f203fbbdb632f2a85.json
Parameterize AsyncTask type
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
@@ -260,7 +260,7 @@ public void run() { * @param processingContext additional context to save that can be accessed * via {@link #getConcurrentResultContext()} */ - public void startCallableProcessing(AsyncTask asyncTask, Object... processingContext) { + public void startCallableProcessing(AsyncTask<?> asyncTask, Object... processingContext) { Assert.notNull(asyncTask, "AsyncTask must not be null"); Long timeout = asyncTask.getTimeout();
true
Other
spring-projects
spring-framework
dbcbdace9e83a020e35ed95f203fbbdb632f2a85.json
Parameterize AsyncTask type
spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java
@@ -124,7 +124,8 @@ public void startCallableProcessingAsyncTask() { this.asyncWebRequest.startAsync(); replay(this.asyncWebRequest); - AsyncTask asyncTask = new AsyncTask(1000L, executor, createMock(Callable.class)); + @SuppressWarnings("unchecked") + AsyncTask<Object> asyncTask = new AsyncTask<Object>(1000L, executor, createMock(Callable.class)); this.asyncManager.startCallableProcessing(asyncTask); verify(executor, this.asyncWebRequest);
true
Other
spring-projects
spring-framework
dbcbdace9e83a020e35ed95f203fbbdb632f2a85.json
Parameterize AsyncTask type
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AsyncTaskMethodReturnValueHandler.java
@@ -52,9 +52,9 @@ public void handleReturnValue(Object returnValue, return; } - AsyncTask asyncTask = (AsyncTask) returnValue; + AsyncTask<?> asyncTask = (AsyncTask<?>) returnValue; asyncTask.setBeanFactory(this.beanFactory); - WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(asyncTask.getCallable(), mavContainer); + WebAsyncUtils.getAsyncManager(webRequest).startCallableProcessing(asyncTask, mavContainer); } }
true
Other
spring-projects
spring-framework
300ab4537bd6fdd4188057a699564759edd5da78.json
Add Spring 32 methods to StandaloneMockMvcBuilder
spring-test-mvc/src/main/java/org/springframework/test/web/mock/servlet/setup/StandaloneMockMvcBuilder.java
@@ -31,6 +31,7 @@ import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.validation.Validator; +import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationObjectSupport; import org.springframework.web.method.support.HandlerMethodArgumentResolver; @@ -42,6 +43,7 @@ import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer; import org.springframework.web.servlet.config.annotation.InterceptorRegistration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; @@ -87,10 +89,14 @@ public class StandaloneMockMvcBuilder extends DefaultMockMvcBuilder<StandaloneMo private Validator validator = null; + private ContentNegotiationManager contentNegotiationManager; + private FormattingConversionService conversionService = null; private List<HandlerExceptionResolver> handlerExceptionResolvers = new ArrayList<HandlerExceptionResolver>(); + private Long asyncRequestTimeout; + private List<ViewResolver> viewResolvers; private LocaleResolver localeResolver = new AcceptHeaderLocaleResolver(); @@ -160,6 +166,23 @@ public StandaloneMockMvcBuilder addMappedInterceptors(String[] pathPatterns, Han return this; } + /** + * Set a ContentNegotiationManager. + */ + protected void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { + this.contentNegotiationManager = contentNegotiationManager; + } + + /** + * Specify the timeout value for async execution. In Spring MVC Test, this + * value is used to determine how to long to wait for async execution to + * complete so that a test can verify the results synchronously. + * @param timeout the timeout value in milliseconds + */ + public void setAsyncRequestTimeout(long timeout) { + this.asyncRequestTimeout = timeout; + } + /** * Provide custom resolvers for controller method arguments. */ @@ -330,11 +353,23 @@ protected void addInterceptors(InterceptorRegistry registry) { } } + @Override + public ContentNegotiationManager mvcContentNegotiationManager() { + return (contentNegotiationManager != null) ? contentNegotiationManager : super.mvcContentNegotiationManager(); + } + @Override public FormattingConversionService mvcConversionService() { return (conversionService != null) ? conversionService : super.mvcConversionService(); } + @Override + public void configureAsyncSupport(AsyncSupportConfigurer configurer) { + if (asyncRequestTimeout != null) { + configurer.setDefaultTimeout(asyncRequestTimeout); + } + } + @Override public Validator mvcValidator() { Validator mvcValidator = (validator != null) ? validator : super.mvcValidator();
false
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/support/AbstractGenericWebContextLoader.java
@@ -34,7 +34,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext; /** - * TODO [SPR-5243] Document AbstractGenericWebContextLoader. + * TODO [SPR-9864] Document AbstractGenericWebContextLoader. * * @author Sam Brannen * @since 3.2 @@ -47,7 +47,7 @@ public abstract class AbstractGenericWebContextLoader extends AbstractContextLoa // --- SmartContextLoader ----------------------------------------------- /** - * TODO [SPR-5243] Document overridden loadContext(MergedContextConfiguration). + * TODO [SPR-9864] Document overridden loadContext(MergedContextConfiguration). * * @see org.springframework.test.context.SmartContextLoader#loadContext(org.springframework.test.context.MergedContextConfiguration) */ @@ -78,7 +78,7 @@ public final ConfigurableApplicationContext loadContext(MergedContextConfigurati } /** - * TODO [SPR-5243] Document configureWebResources(). + * TODO [SPR-9864] Document configureWebResources(). */ protected void configureWebResources(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) { @@ -93,28 +93,28 @@ protected void configureWebResources(GenericWebApplicationContext context, } /** - * TODO [SPR-5243] Document customizeBeanFactory(). + * TODO [SPR-9864] Document customizeBeanFactory(). */ protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory, WebMergedContextConfiguration webMergedConfig) { } /** - * TODO [SPR-5243] Document loadBeanDefinitions(). + * TODO [SPR-9864] Document loadBeanDefinitions(). */ protected abstract void loadBeanDefinitions(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig); /** - * TODO [SPR-5243] Document customizeContext(). + * TODO [SPR-9864] Document customizeContext(). */ protected void customizeContext(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) { } // --- ContextLoader ------------------------------------------------------- /** - * TODO [SPR-5243] Document overridden loadContext(String...). + * TODO [SPR-9864] Document overridden loadContext(String...). * * @see org.springframework.test.context.ContextLoader#loadContext(java.lang.String[]) */
true
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtils.java
@@ -26,7 +26,7 @@ import org.springframework.util.Assert; /** - * TODO [SPR-5243] Document AnnotationConfigContextLoaderUtils. + * TODO [SPR-9864] Document AnnotationConfigContextLoaderUtils. * * @author Sam Brannen * @since 3.2
true
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigWebContextLoader.java
@@ -25,7 +25,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext; /** - * TODO [SPR-5243] Document AnnotationConfigWebContextLoader. + * TODO [SPR-9864] Document AnnotationConfigWebContextLoader. * * @author Sam Brannen * @since 3.2
true
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/support/XmlWebContextLoader.java
@@ -21,7 +21,7 @@ import org.springframework.web.context.support.GenericWebApplicationContext; /** - * TODO [SPR-5243] Document XmlWebContextLoader. + * TODO [SPR-9864] Document XmlWebContextLoader. * * @author Sam Brannen * @since 3.2 @@ -36,7 +36,7 @@ protected String getResourceSuffix() { } /** - * TODO [SPR-5243] Document overridden loadBeanDefinitions(). + * TODO [SPR-9864] Document overridden loadBeanDefinitions(). * * @see org.springframework.test.context.support.AbstractGenericWebContextLoader#loadBeanDefinitions(org.springframework.web.context.support.GenericWebApplicationContext, org.springframework.test.context.web.WebMergedContextConfiguration) */
true
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/web/WebAppConfiguration.java
@@ -24,7 +24,7 @@ import java.lang.annotation.Target; /** - * TODO [SPR-5243] Document WebAppConfiguration. + * TODO [SPR-9864] Document WebAppConfiguration. * * @author Sam Brannen * @since 3.2
true
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/web/WebMergedContextConfiguration.java
@@ -27,7 +27,7 @@ import org.springframework.util.StringUtils; /** - * TODO [SPR-5243] Document WebMergedContextConfiguration. + * TODO [SPR-9864] Document WebMergedContextConfiguration. * * @author Sam Brannen * @since 3.2 @@ -40,7 +40,7 @@ public class WebMergedContextConfiguration extends MergedContextConfiguration { /** - * TODO [SPR-5243] Document WebMergedContextConfiguration constructor. + * TODO [SPR-9864] Document WebMergedContextConfiguration constructor. */ public WebMergedContextConfiguration( Class<?> testClass, @@ -55,7 +55,7 @@ public WebMergedContextConfiguration( } /** - * TODO [SPR-5243] Document getResourceBasePath(). + * TODO [SPR-9864] Document getResourceBasePath(). */ public String getResourceBasePath() { return this.resourceBasePath;
true
Other
spring-projects
spring-framework
0bb24f2922c57e6ba8869a2a443044c3670e1fba.json
Update documentation TODOs Issue: SPR-9864
spring-test/src/main/java/org/springframework/test/context/web/WebTestExecutionListener.java
@@ -33,7 +33,7 @@ import org.springframework.web.context.request.ServletWebRequest; /** - * TODO [SPR-5243] Document WebTestExecutionListener. + * TODO [SPR-9864] Document WebTestExecutionListener. * * @author Sam Brannen * @since 3.2 @@ -44,7 +44,7 @@ public class WebTestExecutionListener extends AbstractTestExecutionListener { /** - * TODO [SPR-5243] Document overridden prepareTestInstance(). + * TODO [SPR-9864] Document overridden prepareTestInstance(). * * @see org.springframework.test.context.support.AbstractTestExecutionListener#prepareTestInstance(org.springframework.test.context.TestContext) */ @@ -54,7 +54,7 @@ public void prepareTestInstance(TestContext testContext) throws Exception { } /** - * TODO [SPR-5243] Document overridden beforeTestMethod(). + * TODO [SPR-9864] Document overridden beforeTestMethod(). * * @see org.springframework.test.context.support.AbstractTestExecutionListener#beforeTestMethod(org.springframework.test.context.TestContext) */ @@ -64,7 +64,7 @@ public void beforeTestMethod(TestContext testContext) throws Exception { } /** - * TODO [SPR-5243] Document setUpRequestContext(). + * TODO [SPR-9864] Document setUpRequestContext(). * * @param testContext * @param servletContext @@ -107,7 +107,7 @@ private void setUpRequestContextIfNecessary(TestContext testContext) { } /** - * TODO [SPR-5243] Document overridden afterTestMethod(). + * TODO [SPR-9864] Document overridden afterTestMethod(). * * @see org.springframework.test.context.support.AbstractTestExecutionListener#afterTestMethod(org.springframework.test.context.TestContext) */
true
Other
spring-projects
spring-framework
98808347ca4e1c0fffa3430321e701bc4c297257.json
Remove trailing whitespace
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java
@@ -53,7 +53,7 @@ public class ReflectiveMethodResolver implements MethodResolver { private Map<Class<?>, MethodFilter> filters = null; - // Using distance will ensure a more accurate match is discovered, + // Using distance will ensure a more accurate match is discovered, // more closely following the Java rules. private boolean useDistance = false; @@ -66,7 +66,7 @@ public ReflectiveMethodResolver() { * This constructors allows the ReflectiveMethodResolver to be configured such that it will * use a distance computation to check which is the better of two close matches (when there * are multiple matches). Using the distance computation is intended to ensure matches - * are more closely representative of what a Java compiler would do when taking into + * are more closely representative of what a Java compiler would do when taking into * account boxing/unboxing and whether the method candidates are declared to handle a * supertype of the type (of the argument) being passed in. * @param useDistance true if distance computation should be used when calculating matches
true
Other
spring-projects
spring-framework
98808347ca4e1c0fffa3430321e701bc4c297257.json
Remove trailing whitespace
spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java
@@ -37,8 +37,8 @@ /** * Simple PropertyAccessor that uses reflection to access properties for reading and writing. A property can be accessed - * if it is accessible as a field on the object or through a getter (if being read) or a setter (if being written). - * + * if it is accessible as a field on the object or through a getter (if being read) or a setter (if being written). + * * @author Andy Clement * @author Juergen Hoeller * @since 3.0 @@ -48,7 +48,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { protected final Map<CacheKey, InvokerPair> readerCache = new ConcurrentHashMap<CacheKey, InvokerPair>(); protected final Map<CacheKey, Member> writerCache = new ConcurrentHashMap<CacheKey, Member>(); - + protected final Map<CacheKey, TypeDescriptor> typeDescriptorCache = new ConcurrentHashMap<CacheKey, TypeDescriptor>(); @@ -85,7 +85,7 @@ public boolean canRead(EvaluationContext context, Object target, String name) th Field field = findField(name, type, target instanceof Class); if (field != null) { TypeDescriptor typeDescriptor = new TypeDescriptor(field); - this.readerCache.put(cacheKey, new InvokerPair(field,typeDescriptor)); + this.readerCache.put(cacheKey, new InvokerPair(field,typeDescriptor)); this.typeDescriptorCache.put(cacheKey, typeDescriptor); return true; } @@ -252,7 +252,7 @@ public void write(EvaluationContext context, Object target, String name, Object throw new AccessException("Neither setter nor field found for property '" + name + "'"); } - + private TypeDescriptor getTypeDescriptor(EvaluationContext context, Object target, String name) { if (target == null) { return null; @@ -340,22 +340,22 @@ protected Field findField(String name, Class<?> clazz, boolean mustBeStatic) { } return null; } - + /** * Captures the member (method/field) to call reflectively to access a property value and the type descriptor for the * value returned by the reflective call. */ private static class InvokerPair { - + final Member member; - + final TypeDescriptor typeDescriptor; public InvokerPair(Member member, TypeDescriptor typeDescriptor) { this.member = member; this.typeDescriptor = typeDescriptor; - } - + } + } private static class CacheKey { @@ -387,9 +387,9 @@ public int hashCode() { } } - /** + /** * Attempt to create an optimized property accessor tailored for a property of a particular name on - * a particular class. The general ReflectivePropertyAccessor will always work but is not optimal + * a particular class. The general ReflectivePropertyAccessor will always work but is not optimal * due to the need to lookup which reflective member (method/field) to use each time read() is called. * This method will just return the ReflectivePropertyAccessor instance if it is unable to build * something more optimal. @@ -438,24 +438,24 @@ public PropertyAccessor createOptimalAccessor(EvaluationContext eContext, Object } return this; } - + /** - * An optimized form of a PropertyAccessor that will use reflection but only knows how to access a particular property - * on a particular class. This is unlike the general ReflectivePropertyResolver which manages a cache of methods/fields that + * An optimized form of a PropertyAccessor that will use reflection but only knows how to access a particular property + * on a particular class. This is unlike the general ReflectivePropertyResolver which manages a cache of methods/fields that * may be invoked to access different properties on different classes. This optimal accessor exists because looking up * the appropriate reflective object by class/name on each read is not cheap. */ static class OptimalPropertyAccessor implements PropertyAccessor { private final Member member; private final TypeDescriptor typeDescriptor; private final boolean needsToBeMadeAccessible; - + OptimalPropertyAccessor(InvokerPair target) { - this.member = target.member; + this.member = target.member; this.typeDescriptor = target.typeDescriptor; if (this.member instanceof Field) { Field field = (Field)member; - needsToBeMadeAccessible = (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) + needsToBeMadeAccessible = (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) && !field.isAccessible(); } else { @@ -468,7 +468,7 @@ static class OptimalPropertyAccessor implements PropertyAccessor { public Class[] getSpecificTargetClasses() { throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor"); } - + public boolean canRead(EvaluationContext context, Object target, String name) throws AccessException { if (target == null) { return false; @@ -504,7 +504,7 @@ public TypedValue read(EvaluationContext context, Object target, String name) th catch (Exception ex) { throw new AccessException("Unable to access property '" + name + "' through getter", ex); } - } + } if (member instanceof Field) { try { if (needsToBeMadeAccessible) { @@ -523,7 +523,7 @@ public TypedValue read(EvaluationContext context, Object target, String name) th public boolean canWrite(EvaluationContext context, Object target, String name) throws AccessException { throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor"); } - + public void write(EvaluationContext context, Object target, String name, Object newValue) throws AccessException { throw new UnsupportedOperationException("Should not be called on an OptimalPropertyAccessor");
true
Other
spring-projects
spring-framework
98808347ca4e1c0fffa3430321e701bc4c297257.json
Remove trailing whitespace
spring-expression/src/test/java/org/springframework/expression/spel/MethodInvocationTests.java
@@ -40,7 +40,7 @@ /** * Tests invocation of methods. - * + * * @author Andy Clement */ public class MethodInvocationTests extends ExpressionTestCase { @@ -89,15 +89,15 @@ public void testArgumentConversion01() { evaluate("new String('hello 2.0 to you').startsWith(7.0d)", false, Boolean.class); evaluate("new String('7.0 foobar').startsWith(7.0d)", true, Boolean.class); } - + @Test public void testMethodThrowingException_SPR6760() { // Test method on inventor: throwException() // On 1 it will throw an IllegalArgumentException // On 2 it will throw a RuntimeException // On 3 it will exit normally // In each case it increments the Inventor field 'counter' when invoked - + SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("throwException(#bar)"); @@ -115,18 +115,18 @@ public void testMethodThrowingException_SPR6760() { o = expr.getValue(eContext); Assert.assertEquals("London", o); // That confirms the logic to mark the cached reference stale and retry is working - - + + // Now let's cause the method to exit via exception and ensure it doesn't cause // a retry. - + // First, switch back to throwException(int) eContext.setVariable("bar",3); o = expr.getValue(eContext); Assert.assertEquals(3, o); Assert.assertEquals(2,parser.parseExpression("counter").getValue(eContext)); - + // Now cause it to throw an exception: eContext.setVariable("bar",1); try { @@ -157,7 +157,7 @@ public void testMethodThrowingException_SPR6760() { // If counter is 5 then the method got called twice! Assert.assertEquals(4,parser.parseExpression("counter").getValue(eContext)); } - + /** * Check on first usage (when the cachedExecutor in MethodReference is null) that the exception is not wrapped. */ @@ -168,10 +168,10 @@ public void testMethodThrowingException_SPR6941() { // On 2 it will throw a RuntimeException // On 3 it will exit normally // In each case it increments the Inventor field 'counter' when invoked - + SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("throwException(#bar)"); - + eContext.setVariable("bar",2); try { expr.getValue(eContext); @@ -184,18 +184,18 @@ public void testMethodThrowingException_SPR6941() { // normal } } - + @Test public void testMethodThrowingException_SPR6941_2() { // Test method on inventor: throwException() // On 1 it will throw an IllegalArgumentException // On 2 it will throw a RuntimeException // On 3 it will exit normally // In each case it increments the Inventor field 'counter' when invoked - + SpelExpressionParser parser = new SpelExpressionParser(); Expression expr = parser.parseExpression("throwException(#bar)"); - + eContext.setVariable("bar",4); try { expr.getValue(eContext); @@ -207,37 +207,37 @@ public void testMethodThrowingException_SPR6941_2() { } Assert.fail("Should not be a SpelEvaluationException"); } - + @Test public void testMethodFiltering_SPR6764() { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); context.setRootObject(new TestObject()); LocalFilter filter = new LocalFilter(); context.registerMethodFilter(TestObject.class,filter); - + // Filter will be called but not do anything, so first doit() will be invoked SpelExpression expr = (SpelExpression) parser.parseExpression("doit(1)"); String result = expr.getValue(context,String.class); Assert.assertEquals("1",result); Assert.assertTrue(filter.filterCalled); - + // Filter will now remove non @Anno annotated methods filter.removeIfNotAnnotated = true; filter.filterCalled = false; expr = (SpelExpression) parser.parseExpression("doit(1)"); result = expr.getValue(context,String.class); Assert.assertEquals("double 1.0",result); Assert.assertTrue(filter.filterCalled); - + // check not called for other types filter.filterCalled=false; context.setRootObject(new String("abc")); expr = (SpelExpression) parser.parseExpression("charAt(0)"); result = expr.getValue(context,String.class); Assert.assertEquals("a",result); Assert.assertFalse(filter.filterCalled); - + // check de-registration works filter.filterCalled = false; context.registerMethodFilter(TestObject.class,null);//clear filter @@ -247,14 +247,14 @@ public void testMethodFiltering_SPR6764() { Assert.assertEquals("1",result); Assert.assertFalse(filter.filterCalled); } - + // Simple filter static class LocalFilter implements MethodFilter { - + public boolean removeIfNotAnnotated = false; - + public boolean filterCalled = false; - + private boolean isAnnotated(Method m) { Annotation[] annos = m.getAnnotations(); if (annos==null) { @@ -282,53 +282,53 @@ public List<Method> filter(List<Method> methods) { } return methods; } - + } - + @Retention(RetentionPolicy.RUNTIME) @interface Anno {} - + class TestObject { public int doit(int i) { return i; } - + @Anno public String doit(double d) { return "double "+d; } - + } - + @Test public void testAddingMethodResolvers() { StandardEvaluationContext ctx = new StandardEvaluationContext(); - + // reflective method accessor is the only one by default List<MethodResolver> methodResolvers = ctx.getMethodResolvers(); Assert.assertEquals(1,methodResolvers.size()); - + MethodResolver dummy = new DummyMethodResolver(); ctx.addMethodResolver(dummy); Assert.assertEquals(2,ctx.getMethodResolvers().size()); - + List<MethodResolver> copy = new ArrayList<MethodResolver>(); copy.addAll(ctx.getMethodResolvers()); Assert.assertTrue(ctx.removeMethodResolver(dummy)); Assert.assertFalse(ctx.removeMethodResolver(dummy)); Assert.assertEquals(1,ctx.getMethodResolvers().size()); - + ctx.setMethodResolvers(copy); Assert.assertEquals(2,ctx.getMethodResolvers().size()); } - + static class DummyMethodResolver implements MethodResolver { public MethodExecutor resolve(EvaluationContext context, Object targetObject, String name, List<TypeDescriptor> argumentTypes) throws AccessException { throw new UnsupportedOperationException("Auto-generated method stub"); } - + } @@ -355,7 +355,7 @@ public void testVarargsInvocation02() { evaluate("aVarargsMethod2(2,'a',3.0d)", 4, Integer.class); // evaluate("aVarargsMethod2(8,new String[]{'a','b','c'})", 11, Integer.class); } - + @Test public void testInvocationOnNullContextObject() { evaluateAndCheckError("null.toString()",SpelMessage.METHOD_CALL_ON_NULL_OBJECT_NOT_ALLOWED);
true
Other
spring-projects
spring-framework
98808347ca4e1c0fffa3430321e701bc4c297257.json
Remove trailing whitespace
spring-expression/src/test/java/org/springframework/expression/spel/PropertyAccessTests.java
@@ -37,7 +37,7 @@ /** * Tests accessing of properties. - * + * * @author Andy Clement */ public class PropertyAccessTests extends ExpressionTestCase { @@ -65,9 +65,9 @@ public void testNonExistentPropertiesAndMethods() { // name is ok but foobar does not exist: evaluateAndCheckError("name.foobar", SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE, 5); } - + /** - * The standard reflection resolver cannot find properties on null objects but some + * The standard reflection resolver cannot find properties on null objects but some * supplied resolver might be able to - so null shouldn't crash the reflection resolver. */ @Test @@ -132,25 +132,25 @@ public void testAddingSpecificPropertyAccessor() throws Exception { // System.out.println(e.getMessage()); } } - + @Test public void testAddingRemovingAccessors() { StandardEvaluationContext ctx = new StandardEvaluationContext(); - + // reflective property accessor is the only one by default List<PropertyAccessor> propertyAccessors = ctx.getPropertyAccessors(); Assert.assertEquals(1,propertyAccessors.size()); - + StringyPropertyAccessor spa = new StringyPropertyAccessor(); ctx.addPropertyAccessor(spa); Assert.assertEquals(2,ctx.getPropertyAccessors().size()); - + List<PropertyAccessor> copy = new ArrayList<PropertyAccessor>(); copy.addAll(ctx.getPropertyAccessors()); Assert.assertTrue(ctx.removePropertyAccessor(spa)); Assert.assertFalse(ctx.removePropertyAccessor(spa)); Assert.assertEquals(1,ctx.getPropertyAccessors().size()); - + ctx.setPropertyAccessors(copy); Assert.assertEquals(2,ctx.getPropertyAccessors().size()); }
true
Other
spring-projects
spring-framework
c8061393fbe3aa20bb51606c60d01a772d3df536.json
Prevent memory leaks with @Configuration beans Refactor ConfigurationClassEnhancer to allow cglib caching of generated classes. Prior to this commit each enhanced @Configuration class would consume permgen space when created. The CallbackFilter and Callback Types are now defined as static final members so that they can be shared by all enhancers. Only the callbackInstances remain specific to a @Configuration class and these are not used by cglib as part of the cache key. Issue: SPR-9851
spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java
@@ -17,8 +17,6 @@ package org.springframework.context.annotation; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -54,40 +52,40 @@ class ConfigurationClassEnhancer { private static final Log logger = LogFactory.getLog(ConfigurationClassEnhancer.class); - private final List<Callback> callbackInstances = new ArrayList<Callback>(); + private static final Class<?>[] CALLBACK_TYPES = { BeanMethodInterceptor.class, + DisposableBeanMethodInterceptor.class, NoOp.class }; - private final List<Class<? extends Callback>> callbackTypes = new ArrayList<Class<? extends Callback>>(); + private static final CallbackFilter CALLBACK_FILTER = new CallbackFilter() { - private final CallbackFilter callbackFilter; + public int accept(Method candidateMethod) { + // Set up the callback filter to return the index of the BeanMethodInterceptor when + // handling a @Bean-annotated method; otherwise, return index of the NoOp callback. + if (BeanAnnotationHelper.isBeanAnnotated(candidateMethod)) { + return 0; + } + if (DisposableBeanMethodInterceptor.isDestroyMethod(candidateMethod)) { + return 1; + } + return 2; + } + }; + + private static final Callback DISPOSABLE_BEAN_METHOD_INTERCEPTOR = new DisposableBeanMethodInterceptor(); + + + private final Callback[] callbackInstances; /** * Creates a new {@link ConfigurationClassEnhancer} instance. */ public ConfigurationClassEnhancer(ConfigurableBeanFactory beanFactory) { Assert.notNull(beanFactory, "BeanFactory must not be null"); - - this.callbackInstances.add(new BeanMethodInterceptor(beanFactory)); - this.callbackInstances.add(new DisposableBeanMethodInterceptor()); - this.callbackInstances.add(NoOp.INSTANCE); - - for (Callback callback : this.callbackInstances) { - this.callbackTypes.add(callback.getClass()); - } - - // Set up the callback filter to return the index of the BeanMethodInterceptor when - // handling a @Bean-annotated method; otherwise, return index of the NoOp callback. - callbackFilter = new CallbackFilter() { - public int accept(Method candidateMethod) { - if (BeanAnnotationHelper.isBeanAnnotated(candidateMethod)) { - return 0; - } - if (DisposableBeanMethodInterceptor.isDestroyMethod(candidateMethod)) { - return 1; - } - return 2; - } - }; + // Callback instances must be ordered in the same way as CALLBACK_TYPES and CALLBACK_FILTER + this.callbackInstances = new Callback[] { + new BeanMethodInterceptor(beanFactory), + DISPOSABLE_BEAN_METHOD_INTERCEPTOR, + NoOp.INSTANCE }; } /** @@ -135,15 +133,11 @@ public interface EnhancedConfiguration extends DisposableBean { */ private Enhancer newEnhancer(Class<?> superclass) { Enhancer enhancer = new Enhancer(); - // Because callbackFilter and callbackTypes are dynamically populated - // there's no opportunity for caching. This does not appear to be causing - // any performance problem. - enhancer.setUseCache(false); enhancer.setSuperclass(superclass); enhancer.setInterfaces(new Class[] {EnhancedConfiguration.class}); enhancer.setUseFactory(false); - enhancer.setCallbackFilter(this.callbackFilter); - enhancer.setCallbackTypes(this.callbackTypes.toArray(new Class[this.callbackTypes.size()])); + enhancer.setCallbackFilter(CALLBACK_FILTER); + enhancer.setCallbackTypes(CALLBACK_TYPES); return enhancer; } @@ -154,7 +148,7 @@ private Enhancer newEnhancer(Class<?> superclass) { private Class<?> createClass(Enhancer enhancer) { Class<?> subclass = enhancer.createClass(); // registering callbacks statically (as opposed to threadlocal) is critical for usage in an OSGi env (SPR-5932) - Enhancer.registerStaticCallbacks(subclass, this.callbackInstances.toArray(new Callback[this.callbackInstances.size()])); + Enhancer.registerStaticCallbacks(subclass, this.callbackInstances); return subclass; } @@ -166,7 +160,7 @@ private Class<?> createClass(Enhancer enhancer) { * @see BeanMethodInterceptor#enhanceFactoryBean(Class, String) */ private static class GetObjectMethodInterceptor implements MethodInterceptor { - + private final ConfigurableBeanFactory beanFactory; private final String beanName; @@ -178,7 +172,7 @@ public GetObjectMethodInterceptor(ConfigurableBeanFactory beanFactory, String be public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return beanFactory.getBean(beanName); } - + } @@ -216,8 +210,19 @@ public static boolean isDestroyMethod(Method candidateMethod) { */ private static class BeanMethodInterceptor implements MethodInterceptor { + private static final Class<?>[] CALLBACK_TYPES = { + GetObjectMethodInterceptor.class, NoOp.class }; + + private static final CallbackFilter CALLBACK_FITLER = new CallbackFilter() { + public int accept(Method method) { + return method.getName().equals("getObject") ? 0 : 1; + } + }; + + private final ConfigurableBeanFactory beanFactory; + public BeanMethodInterceptor(ConfigurableBeanFactory beanFactory) { this.beanFactory = beanFactory; } @@ -246,7 +251,7 @@ public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object // to handle the case of an inter-bean method reference, we must explicitly check the // container for already cached instances - + // first, check to see if the requested bean is a FactoryBean. If so, create a subclass // proxy that intercepts calls to getObject() and returns any cached bean instance. // this ensures that the semantics of calling a FactoryBean from within @Bean methods @@ -328,26 +333,18 @@ private boolean factoryContainsBean(String beanName) { */ private Object enhanceFactoryBean(Class<?> fbClass, String beanName) throws InstantiationException, IllegalAccessException { Enhancer enhancer = new Enhancer(); - enhancer.setUseCache(false); enhancer.setSuperclass(fbClass); enhancer.setUseFactory(false); - enhancer.setCallbackFilter(new CallbackFilter() { - public int accept(Method method) { - return method.getName().equals("getObject") ? 0 : 1; - } - }); - List<Callback> callbackInstances = new ArrayList<Callback>(); - callbackInstances.add(new GetObjectMethodInterceptor(this.beanFactory, beanName)); - callbackInstances.add(NoOp.INSTANCE); - - List<Class<? extends Callback>> callbackTypes = new ArrayList<Class<? extends Callback>>(); - for (Callback callback : callbackInstances) { - callbackTypes.add(callback.getClass()); - } - - enhancer.setCallbackTypes(callbackTypes.toArray(new Class[callbackTypes.size()])); + enhancer.setCallbackFilter(CALLBACK_FITLER); + // Callback instances must be ordered in the same way as CALLBACK_TYPES and CALLBACK_FILTER + Callback[] callbackInstances = new Callback[] { + new GetObjectMethodInterceptor(this.beanFactory, beanName), + NoOp.INSTANCE + }; + + enhancer.setCallbackTypes(CALLBACK_TYPES); Class<?> fbSubclass = enhancer.createClass(); - Enhancer.registerCallbacks(fbSubclass, callbackInstances.toArray(new Callback[callbackInstances.size()])); + Enhancer.registerCallbacks(fbSubclass, callbackInstances); return fbSubclass.newInstance(); }
false
Other
spring-projects
spring-framework
e543ffdfd7070a4b559d724ba4ffa37c58b66bb4.json
Improve annotation methods in TypeDescriptor - Use generic typing for getAnnotation() - Add hasAnnoation() method - Update existing code and tests to make use of changes Issue: SPR-9744
spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -211,7 +211,7 @@ public Set<ConvertiblePair> getConvertibleTypes() { } public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return sourceType.getAnnotation(annotationType) != null; + return sourceType.hasAnnotation(annotationType); } public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { @@ -251,7 +251,7 @@ public Set<ConvertiblePair> getConvertibleTypes() { } public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) { - return targetType.getAnnotation(annotationType) != null; + return targetType.hasAnnotation(annotationType); } public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
true
Other
spring-projects
spring-framework
e543ffdfd7070a4b559d724ba4ffa37c58b66bb4.json
Improve annotation methods in TypeDescriptor - Use generic typing for getAnnotation() - Add hasAnnoation() method - Update existing code and tests to make use of changes Issue: SPR-9744
spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java
@@ -271,15 +271,25 @@ public Annotation[] getAnnotations() { return this.annotations; } + /** + * Determine if this type descriptor has the specified annotation. + * @param annotationType the annotation type + * @return <tt>true</tt> if the annotation is present + */ + public boolean hasAnnotation(Class<? extends Annotation> annotationType) { + return getAnnotation(annotationType) != null; + } + /** * Obtain the annotation associated with this type descriptor of the specified type. * @param annotationType the annotation type * @return the annotation, or null if no such annotation exists on this type descriptor */ - public Annotation getAnnotation(Class<? extends Annotation> annotationType) { + @SuppressWarnings("unchecked") + public <T extends Annotation> T getAnnotation(Class<T> annotationType) { for (Annotation annotation : getAnnotations()) { if (annotation.annotationType().equals(annotationType)) { - return annotation; + return (T) annotation; } } return null;
true
Other
spring-projects
spring-framework
e543ffdfd7070a4b559d724ba4ffa37c58b66bb4.json
Improve annotation methods in TypeDescriptor - Use generic typing for getAnnotation() - Add hasAnnoation() method - Update existing code and tests to make use of changes Issue: SPR-9744
spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java
@@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -191,15 +191,17 @@ public void parameterAnnotated() throws Exception { assertEquals(String.class, t1.getType()); assertEquals(1, t1.getAnnotations().length); assertNotNull(t1.getAnnotation(ParameterAnnotation.class)); + assertTrue(t1.hasAnnotation(ParameterAnnotation.class)); + assertEquals(123, t1.getAnnotation(ParameterAnnotation.class).value()); } @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface ParameterAnnotation { - + int value(); } - public void testAnnotatedMethod(@ParameterAnnotation String parameter) { + public void testAnnotatedMethod(@ParameterAnnotation(123) String parameter) { } @@ -297,6 +299,7 @@ public void propertyGenericClassList() throws Exception { assertEquals(List.class, desc.getType()); assertEquals(Integer.class, desc.getElementTypeDescriptor().getType()); assertNotNull(desc.getAnnotation(MethodAnnotation1.class)); + assertTrue(desc.hasAnnotation(MethodAnnotation1.class)); } public static class GenericClass<T> {
true
Other
spring-projects
spring-framework
2748f2b8eba22264408f2a05725810b58e80649d.json
Remove deprecated methods in spring-test-mvc
spring-test-mvc/src/main/java/org/springframework/test/web/mock/client/match/MockRestRequestMatchers.java
@@ -214,50 +214,4 @@ public static XpathRequestMatchers xpath(String expression, Map<String, String> return new XpathRequestMatchers(expression, namespaces, args); } - - // Deprecated methods .. - - /** - * Expect that the specified request header contains a subtring - * - * @deprecated in favor of {@link #header(String, Matcher...)} - */ - public static RequestMatcher headerContains(final String header, final String substring) { - Assert.notNull(header, "'header' must not be null"); - Assert.notNull(substring, "'substring' must not be null"); - return new RequestMatcher() { - public void match(ClientHttpRequest request) throws AssertionError { - List<String> actualHeaders = request.getHeaders().get(header); - AssertionErrors.assertTrue("Expected header <" + header + "> in request", actualHeaders != null); - - boolean foundMatch = false; - for (String headerValue : actualHeaders) { - if (headerValue.contains(substring)) { - foundMatch = true; - break; - } - } - - AssertionErrors.assertTrue("Expected value containing <" + substring + "> in header <" + header + ">", - foundMatch); - } - }; - } - - /** - * Expect the given request body content. - * - * @deprecated in favor of {@link #content()} as well as {@code jsonPath(..)}, - * and {@code xpath(..)} methods in this class - */ - public static RequestMatcher body(final String body) { - Assert.notNull(body, "'body' must not be null"); - return new RequestMatcher() { - public void match(ClientHttpRequest request) throws AssertionError, IOException { - MockClientHttpRequest mockRequest = (MockClientHttpRequest) request; - AssertionErrors.assertEquals("Unexpected body content", body, mockRequest.getBodyAsString()); - } - }; - } - }
true
Other
spring-projects
spring-framework
2748f2b8eba22264408f2a05725810b58e80649d.json
Remove deprecated methods in spring-test-mvc
spring-test-mvc/src/main/java/org/springframework/test/web/mock/client/response/MockRestResponseCreators.java
@@ -119,71 +119,4 @@ public static DefaultResponseCreator withStatus(HttpStatus status) { return new DefaultResponseCreator(status); } - /** - * Respond with a given body, headers, status code, and status text. - * - * @param body the body of the response "UTF-8" encoded - * @param headers the response headers - * @param statusCode the response status code - * @param statusText the response status text - * - * @deprecated in favor of methods returning DefaultResponseCreator - */ - public static ResponseCreator withResponse(final String body, final HttpHeaders headers, - final HttpStatus statusCode, final String statusText) { - - return new ResponseCreator() { - public MockClientHttpResponse createResponse(ClientHttpRequest request) throws IOException { - MockClientHttpResponse response = new MockClientHttpResponse(body.getBytes("UTF-8"), statusCode); - response.getHeaders().putAll(headers); - return response; - } - }; - } - - /** - * Respond with the given body, headers, and a status code of 200 (OK). - * - * @param body the body of the response "UTF-8" encoded - * @param headers the response headers - * - * @deprecated in favor of methods 'withXyz' in this class returning DefaultResponseCreator - */ - public static ResponseCreator withResponse(String body, HttpHeaders headers) { - return withResponse(body, headers, HttpStatus.OK, ""); - } - - /** - * Respond with a given body, headers, status code, and text. - * - * @param body a {@link Resource} containing the body of the response - * @param headers the response headers - * @param statusCode the response status code - * @param statusText the response status text - * - * @deprecated in favor of methods 'withXyz' in this class returning DefaultResponseCreator - */ - public static ResponseCreator withResponse(final Resource body, final HttpHeaders headers, - final HttpStatus statusCode, String statusText) { - - return new ResponseCreator() { - public MockClientHttpResponse createResponse(ClientHttpRequest request) throws IOException { - MockClientHttpResponse response = new MockClientHttpResponse(body.getInputStream(), statusCode); - response.getHeaders().putAll(headers); - return response; - } - }; - } - - /** - * Respond with the given body, headers, and a status code of 200 (OK). - * @param body the body of the response - * @param headers the response headers - * - * @deprecated in favor of methods 'withXyz' in this class returning DefaultResponseCreator - */ - public static ResponseCreator withResponse(final Resource body, final HttpHeaders headers) { - return withResponse(body, headers, HttpStatus.OK, ""); - } - }
true
Other
spring-projects
spring-framework
7718936158434e0f658233f74c33ab72bea5d440.json
Recognize wildcards in media types with a suffix The "includes" and "isCompatibleWith" methods of MediaType take into account media types with suffices (e.g. application/soap+xml) including wildcards with suffices (e.g. application/*+xml). However before this change, the isWildcardSubtype() method returned true only for subtype "*". Now a media type such as application/*+xml is also recognized as having a wildcard subtype. Issue: SPR-9841
spring-web/src/main/java/org/springframework/http/MediaType.java
@@ -413,11 +413,12 @@ public String getSubtype() { } /** - * Indicates whether the {@linkplain #getSubtype() subtype} is the wildcard character <code>&#42;</code> or not. + * Indicates whether the {@linkplain #getSubtype() subtype} is the wildcard character <code>&#42;</code> + * or the wildcard character followed by a sufiix (e.g. <code>&#42;+xml</code>), or not. * @return whether the subtype is <code>&#42;</code> */ public boolean isWildcardSubtype() { - return WILDCARD_TYPE.equals(subtype); + return WILDCARD_TYPE.equals(subtype) || subtype.startsWith("*+"); } /**
true
Other
spring-projects
spring-framework
7718936158434e0f658233f74c33ab72bea5d440.json
Recognize wildcards in media types with a suffix The "includes" and "isCompatibleWith" methods of MediaType take into account media types with suffices (e.g. application/soap+xml) including wildcards with suffices (e.g. application/*+xml). However before this change, the isWildcardSubtype() method returned true only for subtype "*". Now a media type such as application/*+xml is also recognized as having a wildcard subtype. Issue: SPR-9841
spring-web/src/test/java/org/springframework/http/MediaTypeTests.java
@@ -313,6 +313,7 @@ public void specificityComparator() throws Exception { MediaType audio07 = new MediaType("audio", "*", 0.7); MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1")); MediaType textHtml = new MediaType("text", "html"); + MediaType allXml = new MediaType("application", "*+xml"); MediaType all = MediaType.ALL; Comparator<MediaType> comp = MediaType.SPECIFICITY_COMPARATOR; @@ -328,9 +329,11 @@ public void specificityComparator() throws Exception { assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0); assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0); assertTrue("Invalid comparison result", comp.compare(audio, all) < 0); + assertTrue("Invalid comparison result", comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0); // unspecific to specific assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0); + assertTrue("Invalid comparison result", comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0); assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0); assertTrue("Invalid comparison result", comp.compare(all, audio) > 0); @@ -414,6 +417,7 @@ public void qualityComparator() throws Exception { MediaType audio07 = new MediaType("audio", "*", 0.7); MediaType audioBasicLevel = new MediaType("audio", "basic", Collections.singletonMap("level", "1")); MediaType textHtml = new MediaType("text", "html"); + MediaType allXml = new MediaType("application", "*+xml"); MediaType all = MediaType.ALL; Comparator<MediaType> comp = MediaType.QUALITY_VALUE_COMPARATOR; @@ -429,11 +433,13 @@ public void qualityComparator() throws Exception { assertTrue("Invalid comparison result", comp.compare(audioBasic, audio) < 0); assertTrue("Invalid comparison result", comp.compare(audioBasic, all) < 0); assertTrue("Invalid comparison result", comp.compare(audio, all) < 0); + assertTrue("Invalid comparison result", comp.compare(MediaType.APPLICATION_XHTML_XML, allXml) < 0); // unspecific to specific assertTrue("Invalid comparison result", comp.compare(audio, audioBasic) > 0); assertTrue("Invalid comparison result", comp.compare(all, audioBasic) > 0); assertTrue("Invalid comparison result", comp.compare(all, audio) > 0); + assertTrue("Invalid comparison result", comp.compare(allXml, MediaType.APPLICATION_XHTML_XML) > 0); // qualifiers assertTrue("Invalid comparison result", comp.compare(audio, audio07) < 0);
true
Other
spring-projects
spring-framework
7718936158434e0f658233f74c33ab72bea5d440.json
Recognize wildcards in media types with a suffix The "includes" and "isCompatibleWith" methods of MediaType take into account media types with suffices (e.g. application/soap+xml) including wildcards with suffices (e.g. application/*+xml). However before this change, the isWildcardSubtype() method returned true only for subtype "*". Now a media type such as application/*+xml is also recognized as having a wildcard subtype. Issue: SPR-9841
spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessorMockTests.java
@@ -279,6 +279,28 @@ public void handleReturnValueNotAcceptableProduces() throws Exception { processor.handleReturnValue("Foo", returnTypeStringProduces, mavContainer, webRequest); } + // SPR-9841 + + @Test + public void handleReturnValueMediaTypeSuffix() throws Exception { + String body = "Foo"; + MediaType accepted = MediaType.APPLICATION_XHTML_XML; + List<MediaType> supported = Collections.singletonList(MediaType.valueOf("application/*+xml")); + + servletRequest.addHeader("Accept", accepted); + + expect(messageConverter.canWrite(String.class, null)).andReturn(true); + expect(messageConverter.getSupportedMediaTypes()).andReturn(supported); + expect(messageConverter.canWrite(String.class, accepted)).andReturn(true); + messageConverter.write(eq(body), eq(accepted), isA(HttpOutputMessage.class)); + replay(messageConverter); + + processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest); + + assertTrue(mavContainer.isRequestHandled()); + verify(messageConverter); + } + // SPR-9160 @Test @@ -308,6 +330,7 @@ public void handleReturnValueString() throws Exception { assertEquals("Foo", servletResponse.getContentAsString()); } + @ResponseBody public String handle1(@RequestBody String s, int i) { return s;
true
Other
spring-projects
spring-framework
e16f3b95cb012cdbcf2a1310a86fe881ad8c0fb1.json
Fix typo in Javadoc
spring-web/src/main/java/org/springframework/http/converter/AbstractHttpMessageConverter.java
@@ -214,7 +214,7 @@ protected Long getContentLength(T t, MediaType contentType) throws IOException { protected abstract boolean supports(Class<?> clazz); /** - * Abstract template method that reads the actualy object. Invoked from {@link #read}. + * Abstract template method that reads the actual object. Invoked from {@link #read}. * @param clazz the type of object to return * @param inputMessage the HTTP input message to read from * @return the converted object
false
Other
spring-projects
spring-framework
a3e4f6cad4d1b625a6364fcf3564bb89c41f340e.json
Use EasyMock 2.5.2 consistently across the build This commit ensures that EasyMock version 2.5.2 is used consistently across the test suite. This applies to both the easymock and easymockclassextension artifacts. Using the same version for both of these artifacts helps to better align us for a future upgrade to EasyMock 3.0 since the Class Extension artifact is deprecated in 3.x releases of the library. Issue: SPR-10069
build.gradle
@@ -11,6 +11,7 @@ buildscript { configure(allprojects) { ext.aspectjVersion = '1.6.12' + ext.easymockVersion='2.5.2' ext.hsqldbVersion='1.8.0.10' ext.junitVersion = '4.11.20120805.1225' // temporary use of snapshot; spring-test // still builds against 4.10 @@ -39,7 +40,7 @@ configure(allprojects) { dependencies { testCompile "org.hamcrest:hamcrest-all:1.3" - testCompile "org.easymock:easymock:2.5.1" + testCompile "org.easymock:easymock:${easymockVersion}" } } @@ -281,7 +282,7 @@ project('spring-tx') { compile("com.ibm.websphere:uow:6.0.2.17", provided) compile("javax.resource:connector-api:1.5", optional) compile("org.apache.geronimo.specs:geronimo-jta_1.1_spec:1.1", optional) - testCompile "org.easymock:easymockclassextension:2.3" + testCompile "org.easymock:easymockclassextension:${easymockVersion}" } } @@ -334,7 +335,6 @@ project('spring-jdbc') { compile("org.apache.derby:derby:10.5.3.0_1", optional) compile("org.apache.derby:derbyclient:10.5.3.0_1", optional) compile("org.apache.geronimo.specs:geronimo-jta_1.1_spec:1.1", optional) - testCompile "org.easymock:easymock:2.5.1" } } @@ -608,7 +608,7 @@ project('spring-test-mvc') { testCompile "cglib:cglib-nodep:2.2" testCompile "rome:rome:1.0" testCompile "javax.xml.bind:jaxb-api:2.2.6" - testCompile "org.easymock:easymockclassextension:2.3" + testCompile "org.easymock:easymockclassextension:${easymockVersion}" testCompile("org.springframework.security:spring-security-core:3.1.2.RELEASE") { exclude group: 'org.springframework' }
false
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java
@@ -57,7 +57,7 @@ abstract class ContextLoaderUtils { private static final Log logger = LogFactory.getLog(ContextLoaderUtils.class); private static final String DEFAULT_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.support.DelegatingSmartContextLoader"; - private static final String DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.support.WebDelegatingSmartContextLoader"; + private static final String DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME = "org.springframework.test.context.web.WebDelegatingSmartContextLoader"; private static final String WEB_APP_CONFIGURATION_CLASS_NAME = "org.springframework.test.context.web.WebAppConfiguration"; private static final String WEB_MERGED_CONTEXT_CONFIGURATION_CLASS_NAME = "org.springframework.test.context.web.WebMergedContextConfiguration";
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/support/AbstractDelegatingSmartContextLoader.java
@@ -63,7 +63,7 @@ * @since 3.2 * @see SmartContextLoader */ -abstract class AbstractDelegatingSmartContextLoader implements SmartContextLoader { +public abstract class AbstractDelegatingSmartContextLoader implements SmartContextLoader { private static final Log logger = LogFactory.getLog(AbstractDelegatingSmartContextLoader.class);
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/support/AnnotationConfigContextLoaderUtils.java
@@ -31,7 +31,7 @@ * @author Sam Brannen * @since 3.2 */ -abstract class AnnotationConfigContextLoaderUtils { +public abstract class AnnotationConfigContextLoaderUtils { private static final Log logger = LogFactory.getLog(AnnotationConfigContextLoaderUtils.class); @@ -86,7 +86,7 @@ private static boolean isDefaultConfigurationClassCandidate(Class<?> clazz) { * @return an array of default configuration classes, potentially empty but * never <code>null</code> */ - static Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) { + public static Class<?>[] detectDefaultConfigurationClasses(Class<?> declaringClass) { Assert.notNull(declaringClass, "Declaring class must not be null"); List<Class<?>> configClasses = new ArrayList<Class<?>>();
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/web/AbstractGenericWebContextLoader.java
@@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.test.context.support; +package org.springframework.test.context.web; import javax.servlet.ServletContext; @@ -29,7 +29,7 @@ import org.springframework.core.io.ResourceLoader; import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.MergedContextConfiguration; -import org.springframework.test.context.web.WebMergedContextConfiguration; +import org.springframework.test.context.support.AbstractContextLoader; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.GenericWebApplicationContext;
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/web/AnnotationConfigWebContextLoader.java
@@ -14,13 +14,14 @@ * limitations under the License. */ -package org.springframework.test.context.support; +package org.springframework.test.context.web; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; import org.springframework.test.context.ContextConfigurationAttributes; -import org.springframework.test.context.web.WebMergedContextConfiguration; +import org.springframework.test.context.support.AbstractContextLoader; +import org.springframework.test.context.support.AnnotationConfigContextLoaderUtils; import org.springframework.util.ObjectUtils; import org.springframework.web.context.support.GenericWebApplicationContext;
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/web/GenericXmlWebContextLoader.java
@@ -14,36 +14,35 @@ * limitations under the License. */ -package org.springframework.test.context.support; +package org.springframework.test.context.web; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.test.context.web.WebMergedContextConfiguration; import org.springframework.web.context.support.GenericWebApplicationContext; /** - * TODO [SPR-9864] Document XmlWebContextLoader. + * TODO [SPR-9864] Document GenericXmlWebContextLoader. * * @author Sam Brannen * @since 3.2 */ -public class XmlWebContextLoader extends AbstractGenericWebContextLoader { - - /** - * Returns &quot;<code>-context.xml</code>&quot;. - */ - protected String getResourceSuffix() { - return "-context.xml"; - } +public class GenericXmlWebContextLoader extends AbstractGenericWebContextLoader { /** * TODO [SPR-9864] Document overridden loadBeanDefinitions(). * - * @see org.springframework.test.context.support.AbstractGenericWebContextLoader#loadBeanDefinitions(org.springframework.web.context.support.GenericWebApplicationContext, org.springframework.test.context.web.WebMergedContextConfiguration) + * @see org.springframework.test.context.web.AbstractGenericWebContextLoader#loadBeanDefinitions(org.springframework.web.context.support.GenericWebApplicationContext, org.springframework.test.context.web.WebMergedContextConfiguration) */ @Override protected void loadBeanDefinitions(GenericWebApplicationContext context, WebMergedContextConfiguration webMergedConfig) { new XmlBeanDefinitionReader(context).loadBeanDefinitions(webMergedConfig.getLocations()); } + /** + * Returns &quot;<code>-context.xml</code>&quot;. + */ + protected String getResourceSuffix() { + return "-context.xml"; + } + }
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java
@@ -20,7 +20,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; @@ -29,6 +28,7 @@ import org.springframework.mock.web.MockServletContext; import org.springframework.test.context.TestContext; import org.springframework.test.context.TestExecutionListener; +import org.springframework.test.context.support.AbstractTestExecutionListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletWebRequest; @@ -39,21 +39,11 @@ * @author Sam Brannen * @since 3.2 */ -public class ServletTestExecutionListener implements TestExecutionListener { +public class ServletTestExecutionListener extends AbstractTestExecutionListener { private static final Log logger = LogFactory.getLog(ServletTestExecutionListener.class); - /** - * The default implementation is <em>empty</em>. Can be overridden by - * subclasses as necessary. - * - * @see TestExecutionListener#beforeTestClass(TestContext) - */ - public void beforeTestClass(TestContext testContext) throws Exception { - /* no-op */ - } - /** * TODO [SPR-9864] Document overridden prepareTestInstance(). * @@ -84,21 +74,10 @@ public void afterTestMethod(TestContext testContext) throws Exception { RequestContextHolder.resetRequestAttributes(); } - /** - * The default implementation is <em>empty</em>. Can be overridden by - * subclasses as necessary. - * - * @see TestExecutionListener#afterTestClass(TestContext) - */ - public void afterTestClass(TestContext testContext) throws Exception { - /* no-op */ - } - /** * TODO [SPR-9864] Document setUpRequestContext(). * * @param testContext - * @param servletContext */ private void setUpRequestContextIfNecessary(TestContext testContext) {
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/web/WebDelegatingSmartContextLoader.java
@@ -14,25 +14,26 @@ * limitations under the License. */ -package org.springframework.test.context.support; +package org.springframework.test.context.web; import org.springframework.test.context.SmartContextLoader; +import org.springframework.test.context.support.AbstractDelegatingSmartContextLoader; /** * {@code WebDelegatingSmartContextLoader} is a concrete implementation of - * {@link AbstractDelegatingSmartContextLoader} that delegates to an - * {@link XmlWebContextLoader} and an {@link AnnotationConfigWebContextLoader}. + * {@link AbstractDelegatingSmartContextLoader} that delegates to a + * {@link GenericXmlWebContextLoader} and an {@link AnnotationConfigWebContextLoader}. * * @author Sam Brannen * @since 3.2 * @see SmartContextLoader * @see AbstractDelegatingSmartContextLoader - * @see XmlWebContextLoader + * @see GenericXmlWebContextLoader * @see AnnotationConfigWebContextLoader */ public class WebDelegatingSmartContextLoader extends AbstractDelegatingSmartContextLoader { - private final SmartContextLoader xmlLoader = new XmlWebContextLoader(); + private final SmartContextLoader xmlLoader = new GenericXmlWebContextLoader(); private final SmartContextLoader annotationConfigLoader = new AnnotationConfigWebContextLoader();
true
Other
spring-projects
spring-framework
d0503ab733bb9d4987e51cb76a8b2ec58c5f8468.json
Relocate web artifacts in the TCF to web package This commit relocates recently introduced web artifacts in the TestContext framework to the ~.test.context.web package and renames some classes for consistency with the existing code base. - introduced package-info.java in the web package. - ServletTestExecutionListener now extends AbstractTestExecutionListener instead of implementing TestExecutionListener. - relocated AbstractGenericWebContextLoader, AnnotationConfigWebContextLoader, XmlWebContextLoader, and WebDelegatingSmartContextLoader to the web package. - renamed XmlWebContextLoader to GenericXmlWebContextLoader for consistency with GenericXmlContextLoader. - changed the visibility of AbstractDelegatingSmartContextLoader and AnnotationConfigContextLoaderUtils to public. Issue: SPR-10067
spring-test/src/main/java/org/springframework/test/context/web/package-info.java
@@ -0,0 +1,6 @@ +/** + * Web support classes for the <em>Spring TestContext Framework</em>. + */ + +package org.springframework.test.context.web; +
true
Other
spring-projects
spring-framework
e0e3143dd56b6a3693434eba8c036715d253bc8c.json
Fix Javadoc errors in TransactionalTEL This commit fixes recently introduced formatting errors in the Javadoc of TransactionalTestExecutionListener.
spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java
@@ -64,15 +64,15 @@ * <em>rolled back</em> after completion of the test; whereas, changes to the * database during a test that is run with {@code @NotTransactional} will * <strong>not</strong> be run within a transaction. Test methods that are not - * annotated with either {@code @Transactional} (at the class or method level) - * or {@code @NotTransactional} will not be run within a transaction. + * annotated with {@code @Transactional} (at the class or method level) will not + * be run within a transaction. * * <p>Transactional commit and rollback behavior can be configured via the * class-level {@link TransactionConfiguration @TransactionConfiguration} and * method-level {@link Rollback @Rollback} annotations. * * <p>In case there are multiple instances of {@code PlatformTransactionManager} - * within the test's {@code ApplicationContext}, @{@code TransactionConfiguration} + * within the test's {@code ApplicationContext}, {@code @TransactionConfiguration} * supports configuring the bean name of the {@code PlatformTransactionManager} * that should be used to drive transactions. Alternatively, * {@link TransactionManagementConfigurer} can be implemented in an @@ -90,6 +90,7 @@ * @author Juergen Hoeller * @since 2.5 * @see TransactionConfiguration + * @see TransactionManagementConfigurer * @see org.springframework.transaction.annotation.Transactional * @see org.springframework.test.annotation.NotTransactional * @see org.springframework.test.annotation.Rollback @@ -122,9 +123,9 @@ public class TransactionalTestExecutionListener extends AbstractTestExecutionLis * configured to run within a transaction, this method will run * {@link BeforeTransaction &#064;BeforeTransaction methods} and start a new * transaction. - * <p>Note that if a {@code BeforeTransaction &#064;BeforeTransaction method} fails, - * remaining {@code BeforeTransaction &#064;BeforeTransaction methods} will not - * be invoked, and a transaction will not be started. + * <p>Note that if a {@code @BeforeTransaction} method fails, any remaining + * {@code @BeforeTransaction} methods will not be invoked, and a transaction + * will not be started. * @see org.springframework.transaction.annotation.Transactional * @see org.springframework.test.annotation.NotTransactional * @see #getTransactionManager(TestContext, String) @@ -175,7 +176,7 @@ public String getName() { * If a transaction is currently active for the test method of the supplied * {@link TestContext test context}, this method will end the transaction * and run {@link AfterTransaction &#064;AfterTransaction methods}. - * <p>{@code AfterTransaction &#064;AfterTransaction methods} are guaranteed to be + * <p>{@code @AfterTransaction} methods are guaranteed to be * invoked even if an error occurs while ending the transaction. */ @Override @@ -521,9 +522,9 @@ private boolean isShadowed(Method current, Method previous) { * Retrieves the {@link TransactionConfigurationAttributes} for the * specified {@link Class class} which may optionally declare or inherit * {@link TransactionConfiguration &#064;TransactionConfiguration}. If - * {@code &#064;TransactionConfiguration} is not present for the supplied + * {@code @TransactionConfiguration} is not present for the supplied * class, the <em>default values</em> for attributes defined in - * {@code &#064;TransactionConfiguration} will be used instead. + * {@code @TransactionConfiguration} will be used instead. * @param testContext the test context for which the configuration * attributes should be retrieved * @return a new TransactionConfigurationAttributes instance
false
Other
spring-projects
spring-framework
7ff964afa88da9a8b6eb8cf93b5f042f4aea9195.json
Add JSON converters to FormHttpMessageConverter The FormHttpMessageConverter now adds Jackson JSON converters (version 1.x or 2.x) if available on the classpath. Issue: SPR-10055
spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
@@ -36,11 +36,15 @@ import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; import org.springframework.util.FileCopyUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.RestTemplate; /** * Implementation of {@link HttpMessageConverter} that can handle form data, including multipart form data (i.e. file @@ -72,6 +76,14 @@ */ public class FormHttpMessageConverter implements HttpMessageConverter<MultiValueMap<String, ?>> { + private static final boolean jackson2Present = + ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", RestTemplate.class.getClassLoader()) && + ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", RestTemplate.class.getClassLoader()); + + private static final boolean jacksonPresent = + ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", RestTemplate.class.getClassLoader()) && + ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", RestTemplate.class.getClassLoader()); + private static final byte[] BOUNDARY_CHARS = new byte[]{'-', '_', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', @@ -96,6 +108,12 @@ public FormHttpMessageConverter() { stringHttpMessageConverter.setWriteAcceptCharset(false); this.partConverters.add(stringHttpMessageConverter); this.partConverters.add(new ResourceHttpMessageConverter()); + if (jackson2Present) { + this.partConverters.add(new MappingJackson2HttpMessageConverter()); + } + else if (jacksonPresent) { + this.partConverters.add(new MappingJacksonHttpMessageConverter()); + } }
true
Other
spring-projects
spring-framework
7ff964afa88da9a8b6eb8cf93b5f042f4aea9195.json
Add JSON converters to FormHttpMessageConverter The FormHttpMessageConverter now adds Jackson JSON converters (version 1.x or 2.x) if available on the classpath. Issue: SPR-10055
src/dist/changelog.txt
@@ -102,7 +102,7 @@ Changes in version 3.2 RC1 (2012-11-04) * use concurrent cache to improve performance of GenericTypeResolver (SPR-8701) * cache and late resolve annotations on bean properties to improve performance (SPR-9166) * allow PropertyResolver implementations to ignore unresolvable ${placeholders} (SPR-9569) - +* FormHttpMessageConverter now adds Jackson JSON converters if available on the classpath (SPR-10055) Changes in version 3.2 M2 (2012-09-11) --------------------------------------
true
Other
spring-projects
spring-framework
42a928596fc3dcd2e1a5270d534da66bb9d1978f.json
Remove tiles-request-servlet-wildcard dependency The tiles-request-servlet-wildcard contained only one class that is an implementation of the tiles-request ServletApplicationContext using a Spring ApplicationContext to look up resources. It makes sense for this class to be part of the Spring Tiles 3 integration. Issue: SPR-10054
build.gradle
@@ -521,10 +521,6 @@ project('spring-webmvc-tiles3') { compile("javax.servlet:jstl:1.1.2", provided) compile("javax.servlet.jsp:jsp-api:2.1", provided) compile("org.apache.tiles:tiles-request-api:1.0.1", optional) - compile("org.apache.tiles:tiles-request-servlet-wildcard:1.0.1") { dep-> - optional dep - exclude group: 'org.springframework', module: 'spring-web' - } compile("org.apache.tiles:tiles-api:3.0.1", optional) compile("org.apache.tiles:tiles-core:3.0.1", optional) compile("org.apache.tiles:tiles-servlet:3.0.1", optional)
true
Other
spring-projects
spring-framework
42a928596fc3dcd2e1a5270d534da66bb9d1978f.json
Remove tiles-request-servlet-wildcard dependency The tiles-request-servlet-wildcard contained only one class that is an implementation of the tiles-request ServletApplicationContext using a Spring ApplicationContext to look up resources. It makes sense for this class to be part of the Spring Tiles 3 integration. Issue: SPR-10054
spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/SpringWildcardServletTilesApplicationContext.java
@@ -0,0 +1,102 @@ +/* + * 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.view.tiles3; + +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Locale; + +import javax.servlet.ServletContext; + +import org.apache.tiles.request.ApplicationResource; +import org.apache.tiles.request.locale.URLApplicationResource; +import org.apache.tiles.request.servlet.ServletApplicationContext; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.ResourcePatternResolver; +import org.springframework.web.context.support.ServletContextResourcePatternResolver; + +/** + * Spring-specific subclass of the Tiles ServletApplicationContext. + * + * @author Rossen Stoyanchev + * @since 3.2 + */ +public class SpringWildcardServletTilesApplicationContext extends ServletApplicationContext { + + /** + * The pattern resolver. + */ + protected ResourcePatternResolver resolver; + + /** + * Constructor. + * + * @param servletContext The servlet context. + */ + public SpringWildcardServletTilesApplicationContext(ServletContext servletContext) { + super(servletContext); + resolver = new ServletContextResourcePatternResolver(servletContext); + } + + @Override + public ApplicationResource getResource(String localePath) { + ApplicationResource retValue = null; + Collection<ApplicationResource> urlSet = getResources(localePath); + if (urlSet != null && !urlSet.isEmpty()) { + retValue = urlSet.iterator().next(); + } + return retValue; + } + + @Override + public ApplicationResource getResource(ApplicationResource base, Locale locale) { + ApplicationResource retValue = null; + Collection<ApplicationResource> urlSet = getResources(base.getLocalePath(locale)); + if (urlSet != null && !urlSet.isEmpty()) { + retValue = urlSet.iterator().next(); + } + return retValue; + } + + @Override + public Collection<ApplicationResource> getResources(String path) { + Resource[] resources; + try { + resources = resolver.getResources(path); + } catch (IOException e) { + return Collections.<ApplicationResource> emptyList(); + } + Collection<ApplicationResource> resourceList = new ArrayList<ApplicationResource>(); + if (resources != null && resources.length > 0) { + for (int i = 0; i < resources.length; i++) { + URL url; + try { + url = resources[i].getURL(); + resourceList.add(new URLApplicationResource(url.toExternalForm(), url)); + } catch (IOException e) { + // shouldn't happen with the kind of resources we're using + throw new IllegalArgumentException("no URL for " + resources[i].toString(), e); + } + } + } + return resourceList; + } + +} +
true
Other
spring-projects
spring-framework
42a928596fc3dcd2e1a5270d534da66bb9d1978f.json
Remove tiles-request-servlet-wildcard dependency The tiles-request-servlet-wildcard contained only one class that is an implementation of the tiles-request ServletApplicationContext using a Spring ApplicationContext to look up resources. It makes sense for this class to be part of the Spring Tiles 3 integration. Issue: SPR-10054
spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java
@@ -51,7 +51,6 @@ import org.apache.tiles.preparer.factory.PreparerFactory; import org.apache.tiles.request.ApplicationContext; import org.apache.tiles.request.ApplicationResource; -import org.apache.tiles.request.servlet.wildcard.WildcardServletApplicationContext; import org.apache.tiles.startup.DefaultTilesInitializer; import org.apache.tiles.startup.TilesInitializer; import org.slf4j.Logger; @@ -249,8 +248,8 @@ public void setServletContext(ServletContext servletContext) { */ public void afterPropertiesSet() throws TilesException { - WildcardServletApplicationContext preliminaryContext = - new WildcardServletApplicationContext(this.servletContext); + SpringWildcardServletTilesApplicationContext preliminaryContext = + new SpringWildcardServletTilesApplicationContext(this.servletContext); if (this.tilesInitializer == null) { this.tilesInitializer = new SpringTilesInitializer();
true
Other
spring-projects
spring-framework
d3c977b54b13c27bdf22747bbee8615d643c9559.json
Fix failing tests failing when debug logging is on Issue: SPR-10048
spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java
@@ -77,6 +77,7 @@ public void varArgsTemplateVariables() throws Exception { .andReturn(request); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -93,6 +94,7 @@ public void varArgsNullTemplateVariable() throws Exception { .andReturn(request); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -108,6 +110,7 @@ public void mapTemplateVariables() throws Exception { .andReturn(request); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -124,6 +127,7 @@ public void mapNullTemplateVariable() throws Exception { .andReturn(request); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -177,6 +181,7 @@ public void getForObject() throws Exception { expect(converter.canRead(String.class, textPlain)).andReturn(true); String expected = "Hello World"; expect(converter.read(String.class, response)).andReturn(expected); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -205,6 +210,7 @@ public void getUnsupportedMediaType() throws Exception { expect(response.getStatusCode()).andReturn(HttpStatus.OK); expect(response.getHeaders()).andReturn(responseHeaders).times(2); expect(converter.canRead(String.class, contentType)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -239,6 +245,7 @@ public void getForEntity() throws Exception { String expected = "Hello World"; expect(converter.read(String.class, response)).andReturn(expected); expect(response.getStatusCode()).andReturn(HttpStatus.OK); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -260,6 +267,7 @@ public void headForHeaders() throws Exception { expect(errorHandler.hasError(response)).andReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -282,6 +290,7 @@ public void postForLocation() throws Exception { URI expected = new URI("http://example.com/hotels"); responseHeaders.setLocation(expected); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -307,6 +316,7 @@ public void postForLocationEntityContentType() throws Exception { URI expected = new URI("http://example.com/hotels"); responseHeaders.setLocation(expected); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -335,6 +345,7 @@ public void postForLocationEntityCustomHeader() throws Exception { URI expected = new URI("http://example.com/hotels"); responseHeaders.setLocation(expected); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -360,6 +371,7 @@ public void postForLocationNoLocation() throws Exception { expect(errorHandler.hasError(response)).andReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -379,6 +391,7 @@ public void postForLocationNull() throws Exception { expect(errorHandler.hasError(response)).andReturn(false); HttpHeaders responseHeaders = new HttpHeaders(); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -409,6 +422,7 @@ public void postForObject() throws Exception { Integer expected = 42; expect(converter.canRead(Integer.class, textPlain)).andReturn(true); expect(converter.read(Integer.class, response)).andReturn(expected); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -442,6 +456,7 @@ public void postForEntity() throws Exception { expect(converter.canRead(Integer.class, textPlain)).andReturn(true); expect(converter.read(Integer.class, response)).andReturn(expected); expect(response.getStatusCode()).andReturn(HttpStatus.OK); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -472,6 +487,7 @@ public void postForObjectNull() throws Exception { expect(response.getHeaders()).andReturn(responseHeaders).times(2); expect(converter.canRead(Integer.class, textPlain)).andReturn(true); expect(converter.read(Integer.class, response)).andReturn(null); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -500,6 +516,7 @@ public void postForEntityNull() throws Exception { expect(converter.canRead(Integer.class, textPlain)).andReturn(true); expect(converter.read(Integer.class, response)).andReturn(null); expect(response.getStatusCode()).andReturn(HttpStatus.OK); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -520,6 +537,7 @@ public void put() throws Exception { converter.write(helloWorld, null, request); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -536,6 +554,7 @@ public void putNull() throws Exception { expect(request.getHeaders()).andReturn(requestHeaders); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -550,6 +569,7 @@ public void delete() throws Exception { expect(requestFactory.createRequest(new URI("http://example.com"), HttpMethod.DELETE)).andReturn(request); expect(request.execute()).andReturn(response); expect(errorHandler.hasError(response)).andReturn(false); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -568,6 +588,7 @@ public void optionsForAllow() throws Exception { EnumSet<HttpMethod> expected = EnumSet.of(HttpMethod.GET, HttpMethod.POST); responseHeaders.setAllow(expected); expect(response.getHeaders()).andReturn(responseHeaders); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -621,6 +642,7 @@ public void exchange() throws Exception { expect(converter.canRead(Integer.class, MediaType.TEXT_PLAIN)).andReturn(true); expect(converter.read(Integer.class, response)).andReturn(expected); expect(response.getStatusCode()).andReturn(HttpStatus.OK); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replayMocks(); @@ -663,6 +685,7 @@ public void exchangeParameterizedType() throws Exception { expect(converter.canRead(intList.getType(), null, MediaType.TEXT_PLAIN)).andReturn(true); expect(converter.read(intList.getType(), null, response)).andReturn(expected); expect(response.getStatusCode()).andReturn(HttpStatus.OK); + addLogResponseStatusExpectations(HttpStatus.OK); response.close(); replay(requestFactory, request, response, errorHandler, converter); @@ -681,6 +704,11 @@ public void exchangeParameterizedType() throws Exception { } + private void addLogResponseStatusExpectations(HttpStatus status) throws IOException { + expect(response.getStatusCode()).andReturn(status).times(0, 1); + expect(response.getStatusText()).andReturn(status.getReasonPhrase()).times(0, 1); + } + private void replayMocks() { replay(requestFactory, request, response, errorHandler, converter); }
true
Other
spring-projects
spring-framework
d3c977b54b13c27bdf22747bbee8615d643c9559.json
Fix failing tests failing when debug logging is on Issue: SPR-10048
spring-web/src/test/java/org/springframework/web/context/request/async/WebAsyncManagerTests.java
@@ -31,6 +31,8 @@ import java.util.concurrent.Callable; +import javax.servlet.http.HttpServletRequest; + import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; @@ -49,10 +51,13 @@ public class WebAsyncManagerTests { private AsyncWebRequest asyncWebRequest; + private MockHttpServletRequest servletRequest; + @Before public void setUp() { - this.asyncManager = WebAsyncUtils.getAsyncManager(new MockHttpServletRequest()); + this.servletRequest = new MockHttpServletRequest(); + this.asyncManager = WebAsyncUtils.getAsyncManager(servletRequest); this.asyncManager.setTaskExecutor(new SyncTaskExecutor()); this.asyncWebRequest = createStrictMock(AsyncWebRequest.class); @@ -275,6 +280,7 @@ public void startCallableProcessingWithAsyncTask() throws Exception { this.asyncWebRequest.addTimeoutHandler(EasyMock.<Runnable>anyObject()); this.asyncWebRequest.addCompletionHandler(EasyMock.<Runnable>anyObject()); this.asyncWebRequest.startAsync(); + expect(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).andReturn(this.servletRequest).times(0, 1); replay(this.asyncWebRequest); @SuppressWarnings("unchecked") @@ -411,6 +417,7 @@ private void setupDefaultAsyncScenario() { this.asyncWebRequest.addTimeoutHandler((Runnable) notNull()); this.asyncWebRequest.addCompletionHandler((Runnable) notNull()); this.asyncWebRequest.startAsync(); + expect(this.asyncWebRequest.getNativeRequest(HttpServletRequest.class)).andReturn(this.servletRequest).times(0, 1); expect(this.asyncWebRequest.isAsyncComplete()).andReturn(false); this.asyncWebRequest.dispatch(); replay(this.asyncWebRequest);
true
Other
spring-projects
spring-framework
1e62ad8665bb0f4138e140974108d693a20ee287.json
Add beforeConcurrentHandling support Previously CallableProcessingInterceptor and DeferredResultProcessingInterceptor did not have support for capturing the state of the original Thread just prior to processing. This made it difficult to transfer the state of one Thread (i.e. ThreadLocal) to the Thread used to process the Callable. This commit adds a new method to CallableProcessingInterceptor and DeferredResultProcessingInterceptor named beforeConcurrentHandling which will be invoked on the original Thread used to submit the Callable or DeferredResult. This means the state of the original Thread can be captured in beforeConcurrentHandling and transfered to the new Thread in preProcess. Issue: SPR-10052
spring-web/src/main/java/org/springframework/web/context/request/async/CallableInterceptorChain.java
@@ -26,6 +26,7 @@ * Assists with the invocation of {@link CallableProcessingInterceptor}'s. * * @author Rossen Stoyanchev + * @author Rob Winch * @since 3.2 */ class CallableInterceptorChain { @@ -41,6 +42,12 @@ public CallableInterceptorChain(List<CallableProcessingInterceptor> interceptors this.interceptors = interceptors; } + public void applyBeforeConcurrentHandling(NativeWebRequest request, Callable<?> task) throws Exception { + for (CallableProcessingInterceptor interceptor : this.interceptors) { + interceptor.beforeConcurrentHandling(request, task); + } + } + public void applyPreProcess(NativeWebRequest request, Callable<?> task) throws Exception { for (CallableProcessingInterceptor interceptor : this.interceptors) { interceptor.preProcess(request, task);
true
Other
spring-projects
spring-framework
1e62ad8665bb0f4138e140974108d693a20ee287.json
Add beforeConcurrentHandling support Previously CallableProcessingInterceptor and DeferredResultProcessingInterceptor did not have support for capturing the state of the original Thread just prior to processing. This made it difficult to transfer the state of one Thread (i.e. ThreadLocal) to the Thread used to process the Callable. This commit adds a new method to CallableProcessingInterceptor and DeferredResultProcessingInterceptor named beforeConcurrentHandling which will be invoked on the original Thread used to submit the Callable or DeferredResult. This means the state of the original Thread can be captured in beforeConcurrentHandling and transfered to the new Thread in preProcess. Issue: SPR-10052
spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptor.java
@@ -39,6 +39,7 @@ * can select a value to be used to resume processing. * * @author Rossen Stoyanchev + * @author Rob Winch * @since 3.2 */ public interface CallableProcessingInterceptor { @@ -47,6 +48,24 @@ public interface CallableProcessingInterceptor { static final Object RESPONSE_HANDLED = new Object(); + /** + * Invoked <em>before</em> the start of concurrent handling in the original + * thread in which the {@code Callable} is submitted for concurrent handling. + * + * <p> + * This is useful for capturing the state of the current thread just prior to + * invoking the {@link Callable}. Once the state is captured, it can then be + * transfered to the new {@link Thread} in + * {@link #preProcess(NativeWebRequest, Callable)}. Capturing the state of + * Spring Security's SecurityContextHolder and migrating it to the new Thread + * is a concrete example of where this is useful. + * </p> + * + * @param request the current request + * @param task the task for the current async request + * @throws Exception in case of errors + */ + <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) throws Exception; /** * Invoked <em>after</em> the start of concurrent handling in the async
true
Other
spring-projects
spring-framework
1e62ad8665bb0f4138e140974108d693a20ee287.json
Add beforeConcurrentHandling support Previously CallableProcessingInterceptor and DeferredResultProcessingInterceptor did not have support for capturing the state of the original Thread just prior to processing. This made it difficult to transfer the state of one Thread (i.e. ThreadLocal) to the Thread used to process the Callable. This commit adds a new method to CallableProcessingInterceptor and DeferredResultProcessingInterceptor named beforeConcurrentHandling which will be invoked on the original Thread used to submit the Callable or DeferredResult. This means the state of the original Thread can be captured in beforeConcurrentHandling and transfered to the new Thread in preProcess. Issue: SPR-10052
spring-web/src/main/java/org/springframework/web/context/request/async/CallableProcessingInterceptorAdapter.java
@@ -24,10 +24,17 @@ * for simplified implementation of individual methods. * * @author Rossen Stoyanchev + * @author Rob Winch * @since 3.2 */ public abstract class CallableProcessingInterceptorAdapter implements CallableProcessingInterceptor { + /** + * This implementation is empty. + */ + public <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) throws Exception { + } + /** * This implementation is empty. */
true
Other
spring-projects
spring-framework
1e62ad8665bb0f4138e140974108d693a20ee287.json
Add beforeConcurrentHandling support Previously CallableProcessingInterceptor and DeferredResultProcessingInterceptor did not have support for capturing the state of the original Thread just prior to processing. This made it difficult to transfer the state of one Thread (i.e. ThreadLocal) to the Thread used to process the Callable. This commit adds a new method to CallableProcessingInterceptor and DeferredResultProcessingInterceptor named beforeConcurrentHandling which will be invoked on the original Thread used to submit the Callable or DeferredResult. This means the state of the original Thread can be captured in beforeConcurrentHandling and transfered to the new Thread in preProcess. Issue: SPR-10052
spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultInterceptorChain.java
@@ -40,6 +40,12 @@ public DeferredResultInterceptorChain(List<DeferredResultProcessingInterceptor> this.interceptors = interceptors; } + public void applyBeforeConcurrentHandling(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception { + for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { + interceptor.beforeConcurrentHandling(request, deferredResult); + } + } + public void applyPreProcess(NativeWebRequest request, DeferredResult<?> deferredResult) throws Exception { for (DeferredResultProcessingInterceptor interceptor : this.interceptors) { interceptor.preProcess(request, deferredResult);
true
Other
spring-projects
spring-framework
1e62ad8665bb0f4138e140974108d693a20ee287.json
Add beforeConcurrentHandling support Previously CallableProcessingInterceptor and DeferredResultProcessingInterceptor did not have support for capturing the state of the original Thread just prior to processing. This made it difficult to transfer the state of one Thread (i.e. ThreadLocal) to the Thread used to process the Callable. This commit adds a new method to CallableProcessingInterceptor and DeferredResultProcessingInterceptor named beforeConcurrentHandling which will be invoked on the original Thread used to submit the Callable or DeferredResult. This means the state of the original Thread can be captured in beforeConcurrentHandling and transfered to the new Thread in preProcess. Issue: SPR-10052
spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResultProcessingInterceptor.java
@@ -36,10 +36,22 @@ * method can set the {@code DeferredResult} in order to resume processing. * * @author Rossen Stoyanchev + * @author Rob Winch * @since 3.2 */ public interface DeferredResultProcessingInterceptor { + /** + * Invoked immediately before the start of concurrent handling, in the same + * thread that started it. This method may be used to capture state just prior + * to the start of concurrent processing with the given {@code DeferredResult}. + * + * @param request the current request + * @param deferredResult the DeferredResult for the current request + * @throws Exception in case of errors + */ + <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) throws Exception; + /** * Invoked immediately after the start of concurrent handling, in the same * thread that started it. This method may be used to detect the start of
true