From d52f883453ead747a1247e8089c58d68799f4c1d Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 3 Jan 2013 22:45:20 -0800 Subject: [PATCH 001/311] Add test dependencies sources for testCompile Update the TestSourceSetDependenciesPlugin to consider testCompile configurations. --- .../build/gradle/TestSourceSetDependenciesPlugin.groovy | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/TestSourceSetDependenciesPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/TestSourceSetDependenciesPlugin.groovy index 363c66c00f..6cb6421273 100644 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/TestSourceSetDependenciesPlugin.groovy +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/TestSourceSetDependenciesPlugin.groovy @@ -43,7 +43,7 @@ class TestSourceSetDependenciesPlugin implements Plugin { private void collectProjectDependencies(Set projectDependencies, Project project) { - for(def configurationName in ["compile", "optional", "provided"]) { + for(def configurationName in ["compile", "optional", "provided", "testCompile"]) { Configuration configuration = project.getConfigurations().findByName(configurationName) if(configuration) { configuration.dependencies.findAll { it instanceof ProjectDependency }.each { From 16a3a8bda82f0c1ecba55f741d872c0e630b1e6e Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 3 Jan 2013 22:47:11 -0800 Subject: [PATCH 002/311] Polish test sourceSet dependencies Remove all direct sourceSets.test.output dependencies and instead rely on the 'test-source-set-dependencies' plugin. This commit also updates the api JavaDoc task to ensure that dependencies are not resolved too early. --- build.gradle | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/build.gradle b/build.gradle index 071fdc3d61..c1ddba9033 100644 --- a/build.gradle +++ b/build.gradle @@ -603,7 +603,6 @@ project("spring-webmvc") { testCompile("commons-io:commons-io:1.3") testCompile("org.hibernate:hibernate-validator:4.3.0.Final") testCompile("org.apache.httpcomponents:httpclient:4.2") - testCompile(project(":spring-web").sourceSets.test.output) } // pick up DispatcherServlet.properties in src/main @@ -615,6 +614,7 @@ project("spring-webmvc-tiles3") { merge.into = project(":spring-webmvc") dependencies { compile(project(":spring-context")) + compile(project(":spring-web")) provided("javax.el:el-api:1.0") provided("javax.servlet:jstl:1.2") provided("javax.servlet.jsp:jsp-api:2.1") @@ -633,7 +633,6 @@ project("spring-webmvc-tiles3") { exclude group: "org.slf4j", module: "jcl-over-slf4j" } provided("javax.servlet:javax.servlet-api:3.0.1") - compile(project(":spring-web").sourceSets*.output) // mock request & response testCompile("org.slf4j:slf4j-jcl:${slf4jVersion}") } } @@ -777,7 +776,6 @@ configure(rootProject) { dependencies { // for integration tests testCompile(project(":spring-core")) - testCompile(project(":spring-core").sourceSets.test.output) testCompile(project(":spring-beans")) testCompile(project(":spring-aop")) testCompile(project(":spring-expression")) @@ -813,18 +811,20 @@ configure(rootProject) { project.sourceSets.main.allJava } - classpath = files( - // ensure servlet 3.x and Hibernate 4.x have precedence on the Javadoc - // classpath over their respective 2.5 and 3.x variants - project(":spring-webmvc").sourceSets.main.compileClasspath.files.find { it =~ "servlet-api" }, - rootProject.sourceSets.test.compileClasspath.files.find { it =~ "hibernate-core" }, - // ensure the javadoc process can resolve types compiled from .aj sources - project(":spring-aspects").sourceSets.main.output - ) - classpath += files(subprojects.collect { it.sourceSets.main.compileClasspath }) - maxMemory = "1024m" destinationDir = new File(buildDir, "api") + + doFirst { + classpath = files( + // ensure servlet 3.x and Hibernate 4.x have precedence on the Javadoc + // classpath over their respective 2.5 and 3.x variants + project(":spring-webmvc").sourceSets.main.compileClasspath.files.find { it =~ "servlet-api" }, + rootProject.sourceSets.test.compileClasspath.files.find { it =~ "hibernate-core" }, + // ensure the javadoc process can resolve types compiled from .aj sources + project(":spring-aspects").sourceSets.main.output + ) + classpath += files(subprojects.collect { it.sourceSets.main.compileClasspath }) + } } task docsZip(type: Zip) { From 2a30fa07ea545c5187788825febd6e5eb7460275 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 2 Jan 2013 12:43:15 -0800 Subject: [PATCH 003/311] Replace test beans with test objects Refactor spring-core tests to replace test beans from 'org.springframework.beans' with lighter test objects in 'org.springframework.tests.sample.objects'. --- .../beans/DerivedTestBean.java | 87 ---- .../springframework/beans/GenericBean.java | 237 ---------- .../org/springframework/beans/ITestBean.java | 71 --- .../beans/IndexedTestBean.java | 145 ------ .../springframework/beans/NestedTestBean.java | 61 --- .../org/springframework/beans/TestBean.java | 442 ------------------ .../core/ConventionsTests.java | 22 +- .../GenericCollectionTypeResolverTests.java | 6 +- ...ableTableParameterNameDiscovererTests.java | 10 +- ...ioritizedParameterNameDiscovererTests.java | 4 +- .../sample/objects/DerivedTestObject.java} | 18 +- .../sample/objects/GenericObject.java} | 28 +- .../sample/objects/ITestInterface.java} | 10 +- .../sample/objects/ITestObject.java} | 20 +- .../tests/sample/objects/TestObject.java | 72 +++ .../tests/sample/objects/package-info.java | 4 + .../util/AutoPopulatingListTests.java | 24 +- .../springframework/util/ClassUtilsTests.java | 30 +- .../util/ReflectionUtilsTests.java | 61 ++- .../util/SerializationTestUtils.java | 4 +- 20 files changed, 196 insertions(+), 1160 deletions(-) delete mode 100644 spring-core/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-core/src/test/java/org/springframework/beans/GenericBean.java delete mode 100644 spring-core/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-core/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-core/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-core/src/test/java/org/springframework/beans/TestBean.java rename spring-core/src/test/java/org/springframework/{beans/CustomEnum.java => tests/sample/objects/DerivedTestObject.java} (70%) rename spring-core/src/test/java/org/springframework/{beans/Colour.java => tests/sample/objects/GenericObject.java} (50%) rename spring-core/src/test/java/org/springframework/{beans/IOther.java => tests/sample/objects/ITestInterface.java} (80%) rename spring-core/src/test/java/org/springframework/{beans/INestedTestBean.java => tests/sample/objects/ITestObject.java} (66%) create mode 100644 spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java create mode 100644 spring-core/src/test/java/org/springframework/tests/sample/objects/package-info.java diff --git a/spring-core/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-core/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index 70a3fcfe6b..0000000000 --- a/spring-core/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-core/src/test/java/org/springframework/beans/GenericBean.java b/spring-core/src/test/java/org/springframework/beans/GenericBean.java deleted file mode 100644 index c4b85fa1f6..0000000000 --- a/spring-core/src/test/java/org/springframework/beans/GenericBean.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.core.io.Resource; - -/** - * @author Juergen Hoeller - */ -public class GenericBean { - - private Set integerSet; - - private List resourceList; - - private List> listOfLists; - - private ArrayList listOfArrays; - - private List> listOfMaps; - - private Map plainMap; - - private Map shortMap; - - private HashMap longMap; - - private Map> collectionMap; - - private Map> mapOfMaps; - - private Map> mapOfLists; - - private CustomEnum customEnum; - - private T genericProperty; - - private List genericListProperty; - - - public GenericBean() { - } - - public GenericBean(Set integerSet) { - this.integerSet = integerSet; - } - - public GenericBean(Set integerSet, List resourceList) { - this.integerSet = integerSet; - this.resourceList = resourceList; - } - - public GenericBean(HashSet integerSet, Map shortMap) { - this.integerSet = integerSet; - this.shortMap = shortMap; - } - - public GenericBean(Map shortMap, Resource resource) { - this.shortMap = shortMap; - this.resourceList = Collections.singletonList(resource); - } - - public GenericBean(Map plainMap, Map shortMap) { - this.plainMap = plainMap; - this.shortMap = shortMap; - } - - public GenericBean(HashMap longMap) { - this.longMap = longMap; - } - - public GenericBean(boolean someFlag, Map> collectionMap) { - this.collectionMap = collectionMap; - } - - - public Set getIntegerSet() { - return integerSet; - } - - public void setIntegerSet(Set integerSet) { - this.integerSet = integerSet; - } - - public List getResourceList() { - return resourceList; - } - - public void setResourceList(List resourceList) { - this.resourceList = resourceList; - } - - public List> getListOfLists() { - return listOfLists; - } - - public ArrayList getListOfArrays() { - return listOfArrays; - } - - public void setListOfArrays(ArrayList listOfArrays) { - this.listOfArrays = listOfArrays; - } - - public void setListOfLists(List> listOfLists) { - this.listOfLists = listOfLists; - } - - public List> getListOfMaps() { - return listOfMaps; - } - - public void setListOfMaps(List> listOfMaps) { - this.listOfMaps = listOfMaps; - } - - public Map getPlainMap() { - return plainMap; - } - - public Map getShortMap() { - return shortMap; - } - - public void setShortMap(Map shortMap) { - this.shortMap = shortMap; - } - - public HashMap getLongMap() { - return longMap; - } - - public void setLongMap(HashMap longMap) { - this.longMap = longMap; - } - - public Map> getCollectionMap() { - return collectionMap; - } - - public void setCollectionMap(Map> collectionMap) { - this.collectionMap = collectionMap; - } - - public Map> getMapOfMaps() { - return mapOfMaps; - } - - public void setMapOfMaps(Map> mapOfMaps) { - this.mapOfMaps = mapOfMaps; - } - - public Map> getMapOfLists() { - return mapOfLists; - } - - public void setMapOfLists(Map> mapOfLists) { - this.mapOfLists = mapOfLists; - } - - public T getGenericProperty() { - return genericProperty; - } - - public void setGenericProperty(T genericProperty) { - this.genericProperty = genericProperty; - } - - public List getGenericListProperty() { - return genericListProperty; - } - - public void setGenericListProperty(List genericListProperty) { - this.genericListProperty = genericListProperty; - } - - public CustomEnum getCustomEnum() { - return customEnum; - } - - public void setCustomEnum(CustomEnum customEnum) { - this.customEnum = customEnum; - } - - - public static GenericBean createInstance(Set integerSet) { - return new GenericBean(integerSet); - } - - public static GenericBean createInstance(Set integerSet, List resourceList) { - return new GenericBean(integerSet, resourceList); - } - - public static GenericBean createInstance(HashSet integerSet, Map shortMap) { - return new GenericBean(integerSet, shortMap); - } - - public static GenericBean createInstance(Map shortMap, Resource resource) { - return new GenericBean(shortMap, resource); - } - - public static GenericBean createInstance(Map map, Map shortMap) { - return new GenericBean(map, shortMap); - } - - public static GenericBean createInstance(HashMap longMap) { - return new GenericBean(longMap); - } - - public static GenericBean createInstance(boolean someFlag, Map> collectionMap) { - return new GenericBean(someFlag, collectionMap); - } - -} \ No newline at end of file diff --git a/spring-core/src/test/java/org/springframework/beans/ITestBean.java b/spring-core/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-core/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-core/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-core/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770e..0000000000 --- a/spring-core/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-core/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-core/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-core/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-core/src/test/java/org/springframework/beans/TestBean.java b/spring-core/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 06ad95816d..0000000000 --- a/spring-core/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java index 19d9b264f0..b906164710 100644 --- a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java @@ -23,7 +23,7 @@ import java.util.Set; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.TestObject; /** * @author Rob Harrop @@ -31,23 +31,23 @@ import org.springframework.beans.TestBean; public class ConventionsTests extends TestCase { public void testSimpleObject() { - TestBean testBean = new TestBean(); - assertEquals("Incorrect singular variable name", "testBean", Conventions.getVariableName(testBean)); + TestObject testObject = new TestObject(); + assertEquals("Incorrect singular variable name", "testObject", Conventions.getVariableName(testObject)); } public void testArray() { - TestBean[] testBeans = new TestBean[0]; - assertEquals("Incorrect plural array form", "testBeanList", Conventions.getVariableName(testBeans)); + TestObject[] testObjects = new TestObject[0]; + assertEquals("Incorrect plural array form", "testObjectList", Conventions.getVariableName(testObjects)); } public void testCollections() { - List list = new ArrayList(); - list.add(new TestBean()); - assertEquals("Incorrect plural List form", "testBeanList", Conventions.getVariableName(list)); + List list = new ArrayList(); + list.add(new TestObject()); + assertEquals("Incorrect plural List form", "testObjectList", Conventions.getVariableName(list)); - Set set = new HashSet(); - set.add(new TestBean()); - assertEquals("Incorrect plural Set form", "testBeanList", Conventions.getVariableName(set)); + Set set = new HashSet(); + set.add(new TestObject()); + assertEquals("Incorrect plural Set form", "testObjectList", Conventions.getVariableName(set)); List emptyList = new ArrayList(); try { diff --git a/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java b/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java index bb70889aae..c598269137 100644 --- a/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java @@ -25,8 +25,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.springframework.beans.GenericBean; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.objects.GenericObject; /** * @author Serge Bogatyrjov @@ -93,11 +93,11 @@ public class GenericCollectionTypeResolverTests extends AbstractGenericsTests { } public void testProgrammaticListIntrospection() throws Exception { - Method setter = GenericBean.class.getMethod("setResourceList", List.class); + Method setter = GenericObject.class.getMethod("setResourceList", List.class); assertEquals(Resource.class, GenericCollectionTypeResolver.getCollectionParameterType(new MethodParameter(setter, 0))); - Method getter = GenericBean.class.getMethod("getResourceList"); + Method getter = GenericObject.class.getMethod("getResourceList"); assertEquals(Resource.class, GenericCollectionTypeResolver.getCollectionReturnType(getter)); } diff --git a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java index 0580ae54c2..a151571379 100644 --- a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java @@ -25,7 +25,7 @@ import java.util.Date; import junit.framework.TestCase; import org.junit.Ignore; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.TestObject; /** * @author Adrian Colyer @@ -35,14 +35,14 @@ public class LocalVariableTableParameterNameDiscovererTests extends TestCase { private LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer(); public void testMethodParameterNameDiscoveryNoArgs() throws NoSuchMethodException { - Method getName = TestBean.class.getMethod("getName", new Class[0]); + Method getName = TestObject.class.getMethod("getName", new Class[0]); String[] names = discoverer.getParameterNames(getName); assertNotNull("should find method info", names); assertEquals("no argument names", 0, names.length); } public void testMethodParameterNameDiscoveryWithArgs() throws NoSuchMethodException { - Method setName = TestBean.class.getMethod("setName", new Class[] { String.class }); + Method setName = TestObject.class.getMethod("setName", new Class[] { String.class }); String[] names = discoverer.getParameterNames(setName); assertNotNull("should find method info", names); assertEquals("one argument", 1, names.length); @@ -50,14 +50,14 @@ public class LocalVariableTableParameterNameDiscovererTests extends TestCase { } public void testConsParameterNameDiscoveryNoArgs() throws NoSuchMethodException { - Constructor noArgsCons = TestBean.class.getConstructor(new Class[0]); + Constructor noArgsCons = TestObject.class.getConstructor(new Class[0]); String[] names = discoverer.getParameterNames(noArgsCons); assertNotNull("should find cons info", names); assertEquals("no argument names", 0, names.length); } public void testConsParameterNameDiscoveryArgs() throws NoSuchMethodException { - Constructor twoArgCons = TestBean.class.getConstructor(new Class[] { String.class, int.class }); + Constructor twoArgCons = TestObject.class.getConstructor(new Class[] { String.class, int.class }); String[] names = discoverer.getParameterNames(twoArgCons); assertNotNull("should find cons info", names); assertEquals("one argument", 2, names.length); diff --git a/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java b/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java index eea35b88e6..cd16ed0446 100644 --- a/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java @@ -22,7 +22,7 @@ import java.util.Arrays; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.TestObject; public class PrioritizedParameterNameDiscovererTests extends TestCase { @@ -56,7 +56,7 @@ public class PrioritizedParameterNameDiscovererTests extends TestCase { private final Class anyClass = Object.class; public PrioritizedParameterNameDiscovererTests() throws SecurityException, NoSuchMethodException { - anyMethod = TestBean.class.getMethod("getAge", (Class[]) null); + anyMethod = TestObject.class.getMethod("getAge", (Class[]) null); } public void testNoParametersDiscoverers() { diff --git a/spring-core/src/test/java/org/springframework/beans/CustomEnum.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/DerivedTestObject.java similarity index 70% rename from spring-core/src/test/java/org/springframework/beans/CustomEnum.java rename to spring-core/src/test/java/org/springframework/tests/sample/objects/DerivedTestObject.java index 1e43492191..45ab490a7d 100644 --- a/spring-core/src/test/java/org/springframework/beans/CustomEnum.java +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/DerivedTestObject.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,17 +14,11 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.objects; -/** - * @author Juergen Hoeller - */ -public enum CustomEnum { +import java.io.Serializable; - VALUE_1, VALUE_2; +@SuppressWarnings("serial") +public class DerivedTestObject extends TestObject implements Serializable { - public String toString() { - return "CustomEnum: " + name(); - } - -} \ No newline at end of file +} diff --git a/spring-core/src/test/java/org/springframework/beans/Colour.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/GenericObject.java similarity index 50% rename from spring-core/src/test/java/org/springframework/beans/Colour.java rename to spring-core/src/test/java/org/springframework/tests/sample/objects/GenericObject.java index a992a2ebfc..efd0455fdc 100644 --- a/spring-core/src/test/java/org/springframework/beans/Colour.java +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/GenericObject.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,23 +14,23 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.objects; -import org.springframework.core.enums.ShortCodedLabeledEnum; +import java.util.List; -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { +import org.springframework.core.io.Resource; - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - private Colour(int code, String label) { - super(code, label); +public class GenericObject { + + private List resourceList; + + public List getResourceList() { + return this.resourceList; + } + + public void setResourceList(List resourceList) { + this.resourceList = resourceList; } } diff --git a/spring-core/src/test/java/org/springframework/beans/IOther.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/ITestInterface.java similarity index 80% rename from spring-core/src/test/java/org/springframework/beans/IOther.java rename to spring-core/src/test/java/org/springframework/tests/sample/objects/ITestInterface.java index d7fb346185..4aca1f255b 100644 --- a/spring-core/src/test/java/org/springframework/beans/IOther.java +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/ITestInterface.java @@ -1,6 +1,5 @@ - /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,10 +14,11 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.objects; -public interface IOther { + +public interface ITestInterface { void absquatulate(); -} \ No newline at end of file +} diff --git a/spring-core/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/ITestObject.java similarity index 66% rename from spring-core/src/test/java/org/springframework/beans/INestedTestBean.java rename to spring-core/src/test/java/org/springframework/tests/sample/objects/ITestObject.java index e0ae5f20a3..ca795cb0c1 100644 --- a/spring-core/src/test/java/org/springframework/beans/INestedTestBean.java +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/ITestObject.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,10 +14,20 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.objects; -public interface INestedTestBean { +public interface ITestObject { - public String getCompany(); + String getName(); -} \ No newline at end of file + void setName(String name); + + int getAge(); + + void setAge(int age); + + TestObject getSpouse(); + + void setSpouse(TestObject spouse); + +} diff --git a/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java new file mode 100644 index 0000000000..68ce8c644b --- /dev/null +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/TestObject.java @@ -0,0 +1,72 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.tests.sample.objects; + +public class TestObject implements ITestObject, ITestInterface, Comparable { + + private String name; + + private int age; + + private TestObject spouse; + + public TestObject() { + } + + public TestObject(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return this.age; + } + + public void setAge(int age) { + this.age = age; + } + + public TestObject getSpouse() { + return this.spouse; + } + + public void setSpouse(TestObject spouse) { + this.spouse = spouse; + } + + @Override + public void absquatulate() { + } + + @Override + public int compareTo(Object o) { + if (this.name != null && o instanceof TestObject) { + return this.name.compareTo(((TestObject) o).getName()); + } + else { + return 1; + } + } +} diff --git a/spring-core/src/test/java/org/springframework/tests/sample/objects/package-info.java b/spring-core/src/test/java/org/springframework/tests/sample/objects/package-info.java new file mode 100644 index 0000000000..98c15ca647 --- /dev/null +++ b/spring-core/src/test/java/org/springframework/tests/sample/objects/package-info.java @@ -0,0 +1,4 @@ +/** + * General purpose sample objects that can be used with tests. + */ +package org.springframework.tests.sample.objects; diff --git a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java index ff97d15d92..460e81b297 100644 --- a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java +++ b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java @@ -20,7 +20,7 @@ import java.util.LinkedList; import junit.framework.*; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.TestObject; /** * @author Rob Harrop @@ -29,11 +29,11 @@ import org.springframework.beans.TestBean; public class AutoPopulatingListTests extends TestCase { public void testWithClass() throws Exception { - doTestWithClass(new AutoPopulatingList(TestBean.class)); + doTestWithClass(new AutoPopulatingList(TestObject.class)); } public void testWithClassAndUserSuppliedBackingList() throws Exception { - doTestWithClass(new AutoPopulatingList(new LinkedList(), TestBean.class)); + doTestWithClass(new AutoPopulatingList(new LinkedList(), TestObject.class)); } public void testWithElementFactory() throws Exception { @@ -49,7 +49,7 @@ public class AutoPopulatingListTests extends TestCase { for (int x = 0; x < 10; x++) { Object element = list.get(x); assertNotNull("Element is null", list.get(x)); - assertTrue("Element is incorrect type", element instanceof TestBean); + assertTrue("Element is incorrect type", element instanceof TestObject); assertNotSame(lastElement, element); lastElement = element; } @@ -59,10 +59,10 @@ public class AutoPopulatingListTests extends TestCase { list.add(11, helloWorld); assertEquals(helloWorld, list.get(11)); - assertTrue(list.get(10) instanceof TestBean); - assertTrue(list.get(12) instanceof TestBean); - assertTrue(list.get(13) instanceof TestBean); - assertTrue(list.get(20) instanceof TestBean); + assertTrue(list.get(10) instanceof TestObject); + assertTrue(list.get(12) instanceof TestObject); + assertTrue(list.get(13) instanceof TestObject); + assertTrue(list.get(20) instanceof TestObject); } private void doTestWithElementFactory(AutoPopulatingList list) { @@ -70,14 +70,14 @@ public class AutoPopulatingListTests extends TestCase { for(int x = 0; x < list.size(); x++) { Object element = list.get(x); - if(element instanceof TestBean) { - assertEquals(x, ((TestBean) element).getAge()); + if(element instanceof TestObject) { + assertEquals(x, ((TestObject) element).getAge()); } } } public void testSerialization() throws Exception { - AutoPopulatingList list = new AutoPopulatingList(TestBean.class); + AutoPopulatingList list = new AutoPopulatingList(TestObject.class); assertEquals(list, SerializationTestUtils.serializeAndDeserialize(list)); } @@ -86,7 +86,7 @@ public class AutoPopulatingListTests extends TestCase { @Override public Object createElement(int index) { - TestBean bean = new TestBean(); + TestObject bean = new TestObject(); bean.setAge(index); return bean; } diff --git a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java index e8ab847406..f99216bbbe 100644 --- a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java @@ -28,10 +28,10 @@ import java.util.List; import junit.framework.TestCase; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.IOther; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.DerivedTestObject; +import org.springframework.tests.sample.objects.ITestInterface; +import org.springframework.tests.sample.objects.ITestObject; +import org.springframework.tests.sample.objects.TestObject; /** * @author Colin Sampaleanu @@ -61,11 +61,11 @@ public class ClassUtilsTests extends TestCase { assertEquals(String[].class, ClassUtils.forName(String[].class.getName(), classLoader)); assertEquals(String[][].class, ClassUtils.forName(String[][].class.getName(), classLoader)); assertEquals(String[][][].class, ClassUtils.forName(String[][][].class.getName(), classLoader)); - assertEquals(TestBean.class, ClassUtils.forName("org.springframework.beans.TestBean", classLoader)); - assertEquals(TestBean[].class, ClassUtils.forName("org.springframework.beans.TestBean[]", classLoader)); - assertEquals(TestBean[].class, ClassUtils.forName(TestBean[].class.getName(), classLoader)); - assertEquals(TestBean[][].class, ClassUtils.forName("org.springframework.beans.TestBean[][]", classLoader)); - assertEquals(TestBean[][].class, ClassUtils.forName(TestBean[][].class.getName(), classLoader)); + assertEquals(TestObject.class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject", classLoader)); + assertEquals(TestObject[].class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[]", classLoader)); + assertEquals(TestObject[].class, ClassUtils.forName(TestObject[].class.getName(), classLoader)); + assertEquals(TestObject[][].class, ClassUtils.forName("org.springframework.tests.sample.objects.TestObject[][]", classLoader)); + assertEquals(TestObject[][].class, ClassUtils.forName(TestObject[][].class.getName(), classLoader)); assertEquals(short[][][].class, ClassUtils.forName("[[[S", classLoader)); } @@ -201,11 +201,11 @@ public class ClassUtilsTests extends TestCase { } public void testCountOverloadedMethods() { - assertFalse(ClassUtils.hasAtLeastOneMethodWithName(TestBean.class, "foobar")); + assertFalse(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "foobar")); // no args - assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestBean.class, "hashCode")); + assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "hashCode")); // matches although it takes an arg - assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestBean.class, "setAge")); + assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestObject.class, "setAge")); } public void testNoArgsStaticMethod() throws IllegalAccessException, InvocationTargetException { @@ -260,12 +260,12 @@ public class ClassUtilsTests extends TestCase { } public void testGetAllInterfaces() { - DerivedTestBean testBean = new DerivedTestBean(); + DerivedTestObject testBean = new DerivedTestObject(); List ifcs = Arrays.asList(ClassUtils.getAllInterfaces(testBean)); assertEquals("Correct number of interfaces", 4, ifcs.size()); assertTrue("Contains Serializable", ifcs.contains(Serializable.class)); - assertTrue("Contains ITestBean", ifcs.contains(ITestBean.class)); - assertTrue("Contains IOther", ifcs.contains(IOther.class)); + assertTrue("Contains ITestBean", ifcs.contains(ITestObject.class)); + assertTrue("Contains IOther", ifcs.contains(ITestInterface.class)); } public void testClassNamesToString() { diff --git a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java index d0eb51d285..44025a090f 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -35,7 +35,7 @@ import java.util.List; import org.junit.Ignore; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.TestObject; /** * @author Rob Harrop @@ -47,19 +47,19 @@ public class ReflectionUtilsTests { @Test public void findField() { - Field field = ReflectionUtils.findField(TestBeanSubclassWithPublicField.class, "publicField", String.class); + Field field = ReflectionUtils.findField(TestObjectSubclassWithPublicField.class, "publicField", String.class); assertNotNull(field); assertEquals("publicField", field.getName()); assertEquals(String.class, field.getType()); assertTrue("Field should be public.", Modifier.isPublic(field.getModifiers())); - field = ReflectionUtils.findField(TestBeanSubclassWithNewField.class, "prot", String.class); + field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "prot", String.class); assertNotNull(field); assertEquals("prot", field.getName()); assertEquals(String.class, field.getType()); assertTrue("Field should be protected.", Modifier.isProtected(field.getModifiers())); - field = ReflectionUtils.findField(TestBeanSubclassWithNewField.class, "name", String.class); + field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); assertNotNull(field); assertEquals("name", field.getName()); assertEquals(String.class, field.getType()); @@ -68,8 +68,8 @@ public class ReflectionUtilsTests { @Test public void setField() { - final TestBeanSubclassWithNewField testBean = new TestBeanSubclassWithNewField(); - final Field field = ReflectionUtils.findField(TestBeanSubclassWithNewField.class, "name", String.class); + final TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField(); + final Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); ReflectionUtils.makeAccessible(field); @@ -83,8 +83,8 @@ public class ReflectionUtilsTests { @Test(expected = IllegalStateException.class) public void setFieldIllegal() { - final TestBeanSubclassWithNewField testBean = new TestBeanSubclassWithNewField(); - final Field field = ReflectionUtils.findField(TestBeanSubclassWithNewField.class, "name", String.class); + final TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField(); + final Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class); ReflectionUtils.setField(field, testBean, "FooBar"); } @@ -92,11 +92,11 @@ public class ReflectionUtilsTests { public void invokeMethod() throws Exception { String rob = "Rob Harrop"; - TestBean bean = new TestBean(); + TestObject bean = new TestObject(); bean.setName(rob); - Method getName = TestBean.class.getMethod("getName", (Class[]) null); - Method setName = TestBean.class.getMethod("setName", new Class[] { String.class }); + Method getName = TestObject.class.getMethod("getName", (Class[]) null); + Method setName = TestObject.class.getMethod("setName", new Class[] { String.class }); Object name = ReflectionUtils.invokeMethod(getName, bean); assertEquals("Incorrect name returned", rob, name); @@ -123,7 +123,7 @@ public class ReflectionUtilsTests { @Test public void copySrcToDestinationOfIncorrectClass() { - TestBean src = new TestBean(); + TestObject src = new TestObject(); String dest = new String(); try { ReflectionUtils.shallowCopyFieldState(src, dest); @@ -135,7 +135,7 @@ public class ReflectionUtilsTests { @Test public void rejectsNullSrc() { - TestBean src = null; + TestObject src = null; String dest = new String(); try { ReflectionUtils.shallowCopyFieldState(src, dest); @@ -147,7 +147,7 @@ public class ReflectionUtilsTests { @Test public void rejectsNullDest() { - TestBean src = new TestBean(); + TestObject src = new TestObject(); String dest = null; try { ReflectionUtils.shallowCopyFieldState(src, dest); @@ -159,15 +159,15 @@ public class ReflectionUtilsTests { @Test public void validCopy() { - TestBean src = new TestBean(); - TestBean dest = new TestBean(); + TestObject src = new TestObject(); + TestObject dest = new TestObject(); testValidCopy(src, dest); } @Test public void validCopyOnSubTypeWithNewField() { - TestBeanSubclassWithNewField src = new TestBeanSubclassWithNewField(); - TestBeanSubclassWithNewField dest = new TestBeanSubclassWithNewField(); + TestObjectSubclassWithNewField src = new TestObjectSubclassWithNewField(); + TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField(); src.magic = 11; // Will check inherited fields are copied @@ -180,8 +180,8 @@ public class ReflectionUtilsTests { @Test public void validCopyToSubType() { - TestBean src = new TestBean(); - TestBeanSubclassWithNewField dest = new TestBeanSubclassWithNewField(); + TestObject src = new TestObject(); + TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField(); dest.magic = 11; testValidCopy(src, dest); // Should have left this one alone @@ -190,28 +190,27 @@ public class ReflectionUtilsTests { @Test public void validCopyToSubTypeWithFinalField() { - TestBeanSubclassWithFinalField src = new TestBeanSubclassWithFinalField(); - TestBeanSubclassWithFinalField dest = new TestBeanSubclassWithFinalField(); + TestObjectSubclassWithFinalField src = new TestObjectSubclassWithFinalField(); + TestObjectSubclassWithFinalField dest = new TestObjectSubclassWithFinalField(); // Check that this doesn't fail due to attempt to assign final testValidCopy(src, dest); } - private void testValidCopy(TestBean src, TestBean dest) { + private void testValidCopy(TestObject src, TestObject dest) { src.setName("freddie"); src.setAge(15); - src.setSpouse(new TestBean()); + src.setSpouse(new TestObject()); assertFalse(src.getAge() == dest.getAge()); ReflectionUtils.shallowCopyFieldState(src, dest); assertEquals(src.getAge(), dest.getAge()); assertEquals(src.getSpouse(), dest.getSpouse()); - assertEquals(src.getDoctor(), dest.getDoctor()); } @Test public void doWithProtectedMethods() { ListSavingMethodCallback mc = new ListSavingMethodCallback(); - ReflectionUtils.doWithMethods(TestBean.class, mc, new ReflectionUtils.MethodFilter() { + ReflectionUtils.doWithMethods(TestObject.class, mc, new ReflectionUtils.MethodFilter() { @Override public boolean matches(Method m) { return Modifier.isProtected(m.getModifiers()); @@ -227,7 +226,7 @@ public class ReflectionUtilsTests { @Test public void duplicatesFound() { ListSavingMethodCallback mc = new ListSavingMethodCallback(); - ReflectionUtils.doWithMethods(TestBeanSubclass.class, mc); + ReflectionUtils.doWithMethods(TestObjectSubclass.class, mc); int absquatulateCount = 0; for (String name : mc.getMethodNames()) { if (name.equals("absquatulate")) { @@ -370,7 +369,7 @@ public class ReflectionUtilsTests { } } - private static class TestBeanSubclass extends TestBean { + private static class TestObjectSubclass extends TestObject { @Override public void absquatulate() { @@ -378,20 +377,20 @@ public class ReflectionUtilsTests { } } - private static class TestBeanSubclassWithPublicField extends TestBean { + private static class TestObjectSubclassWithPublicField extends TestObject { @SuppressWarnings("unused") public String publicField = "foo"; } - private static class TestBeanSubclassWithNewField extends TestBean { + private static class TestObjectSubclassWithNewField extends TestObject { private int magic; protected String prot = "foo"; } - private static class TestBeanSubclassWithFinalField extends TestBean { + private static class TestObjectSubclassWithFinalField extends TestObject { @SuppressWarnings("unused") private final String foo = "will break naive copy that doesn't exclude statics"; diff --git a/spring-core/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-core/src/test/java/org/springframework/util/SerializationTestUtils.java index 39a7582e83..0d7fcdd3c4 100644 --- a/spring-core/src/test/java/org/springframework/util/SerializationTestUtils.java +++ b/spring-core/src/test/java/org/springframework/util/SerializationTestUtils.java @@ -17,7 +17,7 @@ import java.io.Serializable; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.objects.TestObject; /** * Utilities for testing serializability of objects. @@ -64,7 +64,7 @@ public class SerializationTestUtils extends TestCase { } public void testWithNonSerializableObject() throws IOException { - TestBean o = new TestBean(); + TestObject o = new TestObject(); assertFalse(o instanceof Serializable); assertFalse(isSerializable(o)); From 42b5d6dd7edda6121bd87852805471ea53074985 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 3 Jan 2013 00:43:48 -0800 Subject: [PATCH 004/311] Remove duplicate test classes Prior to this commit many test utility classes and sample beans were duplicated across projects. This was previously necessary due to the fact that dependent test sources were not shared during a gradle build. Since the introduction of the 'test-source-set-dependencies' gradle plugin this is no longer the case. This commit attempts to remove as much duplicate code as possible, co-locating test utilities and beans in the most suitable project. For example, test beans are now located in the 'spring-beans' project. Some of the duplicated code had started to drift apart when modifications made in one project where not ported to others. All changes have now been consolidated and when necessary existing tests have been refactored to account for the differences. Conflicts: spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java --- .../AspectJExpressionPointcutTests.java | 28 +- .../BeanNamePointcutMatchingTests.java | 4 +- ...hodInvocationProceedingJoinPointTests.java | 6 +- .../TigerAspectJExpressionPointcutTests.java | 6 +- .../aspectj/TypePatternClassFilterTests.java | 16 +- .../AbstractAspectJAdvisorFactoryTests.java | 10 +- .../annotation/ArgumentBindingTests.java | 6 +- .../AspectJPointcutAdvisorTests.java | 4 +- .../annotation/AspectProxyFactoryTests.java | 8 +- .../AspectJNamespaceHandlerTests.java | 7 +- .../AopNamespaceHandlerEventTests-context.xml | 2 +- .../config/AopNamespaceHandlerEventTests.java | 11 +- ...PointcutErrorTests-pointcutDuplication.xml | 2 +- ...dlerPointcutErrorTests-pointcutMissing.xml | 2 +- ...AopNamespaceHandlerPointcutErrorTests.java | 4 +- .../aop/config/TopLevelAopTagTests.java | 4 +- .../aop/framework/AopProxyUtilsTests.java | 6 +- .../framework/IntroductionBenchmarkTests.java | 6 +- .../aop/framework/MethodInvocationTests.java | 4 +- .../aop/framework/PrototypeTargetTests.java | 4 +- .../aop/framework/ProxyFactoryTests.java | 29 +- .../adapter/ThrowsAdviceInterceptorTests.java | 16 +- .../ConcurrencyThrottleInterceptorTests.java | 14 +- .../ExposeBeanNameAdvisorsTests.java | 6 +- ...poseInvocationInterceptorTests-context.xml | 12 +- .../ExposeInvocationInterceptorTests.java | 9 +- .../aop/scope/ScopedProxyAutowireTests.java | 4 +- .../AbstractRegexpMethodPointcutTests.java | 11 +- .../aop/support/AopUtilsTests.java | 12 +- .../aop/support/ClassFiltersTests.java | 6 +- .../aop/support/ClassUtilsTests.java | 4 +- .../aop/support/ComposablePointcutTests.java | 4 +- .../aop/support/ControlFlowPointcutTests.java | 11 +- ...elegatingIntroductionInterceptorTests.java | 25 +- .../aop/support/MethodMatchersTests.java | 15 +- .../support/NameMatchMethodPointcutTests.java | 16 +- .../aop/support/PointcutsTests.java | 4 +- ...ointcutAdvisorIntegrationTests-context.xml | 22 +- ...MethodPointcutAdvisorIntegrationTests.java | 16 +- ...monsPoolTargetSourceProxyTests-context.xml | 2 +- .../CommonsPoolTargetSourceProxyTests.java | 7 +- .../HotSwappableTargetSourceTests-context.xml | 11 +- .../target/HotSwappableTargetSourceTests.java | 14 +- ...LazyInitTargetSourceTests-customTarget.xml | 2 +- .../LazyInitTargetSourceTests-singleton.xml | 2 +- .../aop/target/LazyInitTargetSourceTests.java | 7 +- .../PrototypeBasedTargetSourceTests.java | 12 +- .../PrototypeTargetSourceTests-context.xml | 20 +- .../target/PrototypeTargetSourceTests.java | 7 +- .../ThreadLocalTargetSourceTests-context.xml | 33 +- .../target/ThreadLocalTargetSourceTests.java | 9 +- .../advice/CountingAfterReturningAdvice.java | 2 +- .../aop/advice}/CountingBeforeAdvice.java | 2 +- .../tests/aop}/advice/MethodCounter.java | 2 +- .../tests/aop}/advice/MyThrowsHandler.java | 2 +- .../advice/TimestampIntroductionAdvisor.java | 4 +- .../aop}/interceptor/NopInterceptor.java | 2 +- .../SerializableNopInterceptor.java | 2 +- .../TimestampIntroductionInterceptor.java | 7 +- .../tests/sample}/beans/Person.java | 12 +- .../sample}/beans/SerializablePerson.java | 2 +- .../tests/sample}/beans/subpkg/DeepBean.java | 2 +- .../src/test/java/test/aop/MethodCounter.java | 70 -- .../test/java/test/aop/NopInterceptor.java | 58 -- .../test/aop/SerializableNopInterceptor.java | 50 - .../src/test/java/test/beans/Colour.java | 36 - .../test/java/test/beans/DerivedTestBean.java | 90 -- .../test/java/test/beans/INestedTestBean.java | 23 - .../src/test/java/test/beans/IOther.java | 24 - .../src/test/java/test/beans/ITestBean.java | 69 -- .../test/java/test/beans/NestedTestBean.java | 61 -- .../src/test/java/test/beans/Person.java | 36 - .../java/test/beans/SerializablePerson.java | 70 -- .../src/test/java/test/beans/TestBean.java | 431 -------- .../CollectingReaderEventListener.java | 97 -- .../test/util/SerializationTestUtils.java | 100 -- .../src/test/java/test/util/TimeStamped.java | 34 - .../org/springframework/beans/Colour.java | 36 - .../beans/DerivedTestBean.java | 86 -- .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 60 -- .../org/springframework/beans/TestBean.java | 437 -------- .../aspectj/AbstractBeanConfigurerTests.java | 4 +- .../aspectj/beanConfigurerTests-beans.xml | 2 +- .../cache/aspectj/AbstractAnnotationTest.java | 596 ----------- ...nTest.java => AspectJAnnotationTests.java} | 35 +- .../cache/config/DefaultCacheableService.java | 27 +- .../CallCountingTransactionManager.java | 59 -- .../TransactionAspectTests-context.xml | 2 +- .../aspectj/TransactionAspectTests.java | 4 +- .../ComponentBeanDefinitionParserTest.java | 5 +- .../springframework/beans/BeanUtilsTests.java | 8 +- .../beans/BeanWrapperEnumTests.java | 6 +- .../beans/BeanWrapperGenericsTests.java | 10 +- .../beans/BeanWrapperTests.java | 12 +- .../CachedIntrospectionResultsTests.java | 6 +- .../beans/ExtendedBeanInfoTests.java | 4 +- .../factory/BeanFactoryUtilsTests-leaf.xml | 2 +- .../factory/BeanFactoryUtilsTests-middle.xml | 11 +- .../factory/BeanFactoryUtilsTests-root.xml | 10 +- .../beans/factory/BeanFactoryUtilsTests.java | 12 +- .../factory/ConcurrentBeanFactoryTests.java | 7 +- .../DefaultListableBeanFactoryTests.java | 60 +- .../beans/factory/FactoryBeanTests.java | 4 +- .../factory/SharedBeanRegistryTests.java | 6 +- .../beans/factory/access/beans1.xml | 0 .../beans/factory/access/beans2.xml | 0 ...wiredAnnotationBeanPostProcessorTests.java | 10 +- .../CustomAutowireConfigurerTests.java | 4 +- ...njectAnnotationBeanPostProcessorTests.java | 10 +- .../config/CustomEditorConfigurerTests.java | 4 +- ...ieldRetrievingFactoryBeanTests-context.xml | 2 +- .../FieldRetrievingFactoryBeanTests.java | 8 +- ...ObjectFactoryCreatingFactoryBeanTests.java | 4 +- .../config/PropertiesFactoryBeanTests.java | 4 +- .../PropertyPathFactoryBeanTests-context.xml | 14 +- .../config/PropertyPathFactoryBeanTests.java | 8 +- .../PropertyPlaceholderConfigurerTests.java | 4 +- .../PropertyResourceConfigurerTests.java | 8 +- .../config/SimpleScopeTests-context.xml | 2 +- .../factory/config/SimpleScopeTests.java | 6 +- .../CustomProblemReporterTests-context.xml | 8 +- .../parsing/CustomProblemReporterTests.java | 6 +- .../support/BeanDefinitionBuilderTests.java | 4 +- .../factory/support/BeanDefinitionTests.java | 4 +- .../support/BeanFactoryGenericsTests.java | 13 +- ...DefinitionMetadataEqualsHashCodeTests.java | 4 +- .../PropertiesBeanDefinitionReaderTests.java | 4 +- .../factory/support/genericBeanTests.xml | 6 +- .../wiring/BeanConfigurerSupportTests.java | 4 +- .../factory/xml/AbstractBeanFactoryTests.java | 39 +- .../xml/AbstractListableBeanFactoryTests.java | 8 +- .../xml/AutowireWithExclusionTests.java | 4 +- .../factory/xml/CollectionMergingTests.java | 4 +- .../xml/CollectionsWithDefaultTypesTests.java | 4 +- .../xml/ConstructorDependenciesBean.java | 7 +- .../beans/factory/xml/CountingFactory.java | 4 +- .../beans/factory/xml/DummyReferencer.java | 6 +- ...uplicateBeanIdTests-multiLevel-context.xml | 4 +- ...DuplicateBeanIdTests-sameLevel-context.xml | 4 +- .../factory/xml/DuplicateBeanIdTests.java | 4 +- .../factory/xml/EventPublicationTests.java | 3 +- .../beans/factory/xml/FactoryMethodTests.java | 4 +- .../beans/factory/xml/FactoryMethods.java | 5 +- .../beans/factory/xml/InstanceFactory.java | 4 +- ...edBeansElementAttributeRecursionTests.java | 4 +- .../factory/xml/SchemaValidationTests.java | 4 +- ...impleConstructorNamespaceHandlerTests.java | 6 +- .../SimplePropertyNamespaceHandlerTests.java | 6 +- .../beans/factory/xml/TestBeanCreator.java | 4 +- .../xml/UtilNamespaceHandlerTests.java | 7 +- .../factory/xml/XmlBeanCollectionTests.java | 98 +- .../xml/XmlBeanDefinitionReaderTests.java | 4 +- .../xml/XmlListableBeanFactoryTests.java | 10 +- .../propertyeditors/CustomEditorTests.java | 16 +- .../beans/support/PagedListHolderTests.java | 11 +- .../beans}/CollectingReaderEventListener.java | 2 +- .../tests/sample}/beans/BooleanTestBean.java | 2 +- .../tests/sample}/beans/Colour.java | 2 +- .../tests/sample}/beans/CountingTestBean.java | 6 +- .../tests/sample}/beans/CustomEnum.java | 2 +- .../sample/beans}/DependenciesBean.java | 4 +- .../tests/sample}/beans/DerivedTestBean.java | 2 +- .../tests/sample}/beans/DummyBean.java | 2 +- .../tests/sample}/beans/DummyFactory.java | 3 +- .../tests/sample}/beans/GenericBean.java | 17 +- .../sample}/beans/GenericIntegerBean.java | 2 +- .../beans/GenericSetOfIntegerBean.java | 2 +- .../tests/sample/beans}/HasMap.java | 24 +- .../tests/sample}/beans/INestedTestBean.java | 2 +- .../tests/sample}/beans/IOther.java | 2 +- .../tests/sample}/beans/ITestBean.java | 8 +- .../tests/sample}/beans/IndexedTestBean.java | 2 +- .../tests/sample}/beans/LifecycleBean.java | 2 +- .../sample/beans}/MustBeInitialized.java | 4 +- .../tests/sample}/beans/NestedTestBean.java | 2 +- .../tests/sample}/beans/NumberTestBean.java | 2 +- .../beans/PackageLevelVisibleBean.java | 2 +- .../tests/sample}/beans/Pet.java | 2 +- .../tests/sample}/beans/SideEffectBean.java | 2 +- .../tests/sample}/beans/TestBean.java | 48 +- .../sample}/beans/factory/DummyFactory.java | 20 +- .../tests/sample/beans/package-info.java | 4 + .../util/SerializationTestUtils.java | 65 -- .../src/test/java/test/beans/Colour.java | 36 - .../src/test/java/test/beans/CustomEnum.java | 30 - .../test/java/test/beans/INestedTestBean.java | 23 - .../src/test/java/test/beans/ITestBean.java | 71 -- .../src/test/java/test/beans/TestBean.java | 457 --------- .../java/test/util/TestResourceUtils.java | 46 - .../support/multiConstructorArgs.properties | 4 +- .../support/refConstructorArg.properties | 6 +- .../support/simpleConstructorArg.properties | 4 +- ...tAttributeRecursionTests-merge-context.xml | 2 +- .../autowire-constructor-with-exclusion.xml | 4 +- .../factory/xml/autowire-with-exclusion.xml | 4 +- .../factory/xml/autowire-with-inclusion.xml | 4 +- .../xml/autowire-with-selective-inclusion.xml | 4 +- .../beans/factory/xml/beanEvents.xml | 8 +- .../beans/factory/xml/collectionMerging.xml | 28 +- .../beans/factory/xml/collections.xml | 78 +- .../xml/collectionsWithDefaultTypes.xml | 4 +- .../beans/factory/xml/factory-methods.xml | 4 +- .../beans/factory/xml/schemaValidated.xml | 10 +- ...simpleConstructorNamespaceHandlerTests.xml | 22 +- ...tructorNamespaceHandlerTestsWithErrors.xml | 2 +- .../simplePropertyNamespaceHandlerTests.xml | 10 +- ...ropertyNamespaceHandlerTestsWithErrors.xml | 4 +- .../beans/factory/xml/test.xml | 32 +- .../beans/factory/xml/testUtilNamespace.xml | 18 +- .../beans/factory/xml/validateWithDtd.xml | 2 +- .../beans/factory/xml/validateWithXsd.xml | 2 +- .../beans/factory/xml/withMeta.xml | 6 +- .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 457 --------- .../scheduling/TestMethodInvokingTask.java | 52 - .../scheduling/quartz/QuartzSupportTests.java | 4 +- .../aop/aspectj/AfterAdviceBindingTests.java | 6 +- .../aop/aspectj/AfterAdviceBindingTests.xml | 2 +- .../AfterReturningAdviceBindingTests.java | 6 +- .../AfterReturningAdviceBindingTests.xml | 4 +- .../AfterThrowingAdviceBindingTests.java | 4 +- .../AfterThrowingAdviceBindingTests.xml | 2 +- .../aop/aspectj/AroundAdviceBindingTests.java | 6 +- .../aop/aspectj/AroundAdviceBindingTests.xml | 2 +- .../aop/aspectj/AroundAdviceCircularTests.xml | 4 +- .../AspectAndAdvicePrecedenceTests.java | 4 +- .../AspectAndAdvicePrecedenceTests.xml | 2 +- ...AspectJExpressionPointcutAdvisorTests.java | 4 +- .../AspectJExpressionPointcutAdvisorTests.xml | 4 +- .../BeanNamePointcutAtAspectTests.java | 6 +- .../aspectj/BeanNamePointcutAtAspectTests.xml | 10 +- .../aop/aspectj/BeanNamePointcutTests.java | 4 +- .../aop/aspectj/BeanNamePointcutTests.xml | 12 +- .../aop/aspectj/BeforeAdviceBindingTests.java | 6 +- .../aop/aspectj/BeforeAdviceBindingTests.xml | 2 +- .../aop/aspectj/DeclareParentsTests.java | 4 +- .../aop/aspectj/DeclareParentsTests.xml | 6 +- ...licitJPArgumentMatchingAtAspectJTests.java | 6 +- ...plicitJPArgumentMatchingAtAspectJTests.xml | 2 +- .../ImplicitJPArgumentMatchingTests.xml | 4 +- .../OverloadedAdviceTests-ambiguous.xml | 2 +- .../aop/aspectj/OverloadedAdviceTests.xml | 2 +- ...pectImplementingInterfaceTests-context.xml | 2 +- .../AspectImplementingInterfaceTests.java | 4 +- ...xyCreatorAndLazyInitTargetSourceTests.java | 6 +- .../AspectJAutoProxyCreatorTests-aspects.xml | 4 +- ...toProxyCreatorTests-aspectsPlusAdvisor.xml | 6 +- ...xyCreatorTests-aspectsWithAbstractBean.xml | 2 +- ...oProxyCreatorTests-aspectsWithOrdering.xml | 2 +- ...AspectJAutoProxyCreatorTests-pertarget.xml | 4 +- .../AspectJAutoProxyCreatorTests-perthis.xml | 2 +- ...JAutoProxyCreatorTests-twoAdviceAspect.xml | 2 +- ...yCreatorTests-twoAdviceAspectPrototype.xml | 2 +- ...pectJAutoProxyCreatorTests-usesInclude.xml | 2 +- ...oProxyCreatorTests-usesJoinPointAspect.xml | 2 +- .../AspectJAutoProxyCreatorTests.java | 11 +- .../AtAspectJAfterThrowingTests-context.xml | 2 +- .../AtAspectJAfterThrowingTests.java | 6 +- .../benchmark/BenchmarkTests-aspectj.xml | 2 +- .../benchmark/BenchmarkTests-springAop.xml | 2 +- .../autoproxy/benchmark/BenchmarkTests.java | 4 +- ...fterReturningGenericTypeMatchingTests.java | 6 +- ...pNamespaceHandlerAdviceTypeTests-error.xml | 6 +- .../AopNamespaceHandlerAdviceTypeTests-ok.xml | 6 +- ...AopNamespaceHandlerArgNamesTests-error.xml | 6 +- .../AopNamespaceHandlerArgNamesTests-ok.xml | 6 +- ...ceHandlerProxyTargetClassTests-context.xml | 6 +- ...NamespaceHandlerProxyTargetClassTests.java | 4 +- ...opNamespaceHandlerReturningTests-error.xml | 6 +- .../AopNamespaceHandlerReturningTests-ok.xml | 6 +- .../AopNamespaceHandlerTests-context.xml | 6 +- .../aop/config/AopNamespaceHandlerTests.java | 14 +- ...AopNamespaceHandlerThrowingTests-error.xml | 6 +- .../AopNamespaceHandlerThrowingTests-ok.xml | 6 +- .../config/PrototypeProxyTests-context.xml | 10 +- .../aop/framework/AbstractAopProxyTests.java | 47 +- .../aop/framework/CglibProxyTests.java | 21 +- .../aop/framework/JdkDynamicProxyTests.java | 8 +- .../ProxyFactoryBeanTests-autowiring.xml | 4 +- .../ProxyFactoryBeanTests-context.xml | 66 +- ...xyFactoryBeanTests-double-targetsource.xml | 10 +- .../ProxyFactoryBeanTests-frozen.xml | 26 +- ...roxyFactoryBeanTests-inner-bean-target.xml | 23 +- .../ProxyFactoryBeanTests-invalid.xml | 4 +- ...yFactoryBeanTests-notlast-targetsource.xml | 6 +- .../ProxyFactoryBeanTests-prototype.xml | 6 +- .../ProxyFactoryBeanTests-serialization.xml | 20 +- .../ProxyFactoryBeanTests-targetsource.xml | 34 +- .../ProxyFactoryBeanTests-throws-advice.xml | 18 +- .../aop/framework/ProxyFactoryBeanTests.java | 20 +- ...visorAdapterRegistrationTests-with-bpp.xml | 4 +- ...orAdapterRegistrationTests-without-bpp.xml | 4 +- .../AdvisorAdapterRegistrationTests.java | 4 +- ...oProxyCreatorTests-common-interceptors.xml | 6 +- ...oProxyCreatorTests-custom-targetsource.xml | 28 +- ...AdvisorAutoProxyCreatorTests-optimized.xml | 4 +- ...toProxyCreatorTests-quick-targetsource.xml | 10 +- .../AdvisorAutoProxyCreatorTests.java | 26 +- .../autoproxy/AutoProxyCreatorTests.java | 10 +- ...nNameAutoProxyCreatorInitTests-context.xml | 2 +- .../BeanNameAutoProxyCreatorInitTests.java | 4 +- .../BeanNameAutoProxyCreatorTests-context.xml | 26 +- .../BeanNameAutoProxyCreatorTests.java | 19 +- .../aop/scope/ScopedProxyTests-list.xml | 2 +- .../aop/scope/ScopedProxyTests-override.xml | 2 +- .../aop/scope/ScopedProxyTests-testbean.xml | 2 +- .../aop/scope/ScopedProxyTests.java | 8 +- .../CommonsPoolTargetSourceTests-context.xml | 8 +- .../target/CommonsPoolTargetSourceTests.java | 8 +- .../org/springframework/beans/Colour.java | 36 - .../beans/DerivedTestBean.java | 90 -- .../beans/FieldAccessBean.java | 44 - .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 146 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/Person.java | 36 - .../beans/SerializablePerson.java | 70 -- .../factory/AbstractBeanFactoryTests.java | 329 ------ .../AbstractListableBeanFactoryTests.java | 84 -- .../beans/factory/LifecycleBean.java | 164 --- .../SingletonBeanFactoryLocatorTests.java | 182 ---- .../beans/factory/access/TestBean.java | 75 -- .../beans/factory/access/ref1.xml | 28 - .../CollectingReaderEventListener.java | 89 -- .../beans/factory/xml/DependenciesBean.java | 77 -- ...MethodWrappedByCglibProxyTests-context.xml | 2 +- .../LookupMethodWrappedByCglibProxyTests.java | 4 +- ...aceHandlerWithExpressionLanguageTests.java | 4 +- .../factory/xml/XmlBeanFactoryTestTypes.java | 10 +- .../xml/XmlBeanFactoryTests-autowire.xml | 12 +- .../factory/xml/XmlBeanFactoryTests-child.xml | 6 +- .../xml/XmlBeanFactoryTests-collections.xml | 74 +- ...lBeanFactoryTests-complexFactoryCircle.xml | 8 +- .../XmlBeanFactoryTests-constructorArg.xml | 12 +- ...lBeanFactoryTests-constructorOverrides.xml | 2 +- .../XmlBeanFactoryTests-defaultAutowire.xml | 8 +- .../XmlBeanFactoryTests-defaultLazyInit.xml | 2 +- ...mlBeanFactoryTests-delegationOverrides.xml | 4 +- .../xml/XmlBeanFactoryTests-factoryCircle.xml | 2 +- .../xml/XmlBeanFactoryTests-initializers.xml | 2 +- .../xml/XmlBeanFactoryTests-invalid.xml | 13 +- ...toryTests-invalidOverridesNoSuchMethod.xml | 2 +- ...nFactoryTests-localCollectionsUsingXsd.xml | 2 +- .../xml/XmlBeanFactoryTests-overrides.xml | 16 +- .../xml/XmlBeanFactoryTests-parent.xml | 6 +- .../xml/XmlBeanFactoryTests-reftypes.xml | 72 +- .../xml/XmlBeanFactoryTests-resource.xml | 2 +- .../XmlBeanFactoryTests-resourceImport.xml | 2 +- ...lBeanFactoryTests-satisfiedAllDepCheck.xml | 4 +- ...anFactoryTests-satisfiedObjectDepCheck.xml | 4 +- ...anFactoryTests-satisfiedSimpleDepCheck.xml | 2 +- ...toryTests-testWithDuplicateNameInAlias.xml | 4 +- ...eanFactoryTests-testWithDuplicateNames.xml | 4 +- ...s-unsatisfiedAllDepCheckMissingObjects.xml | 2 +- ...ts-unsatisfiedAllDepCheckMissingSimple.xml | 4 +- ...FactoryTests-unsatisfiedObjectDepCheck.xml | 2 +- ...FactoryTests-unsatisfiedSimpleDepCheck.xml | 2 +- .../factory/xml/XmlBeanFactoryTests.java | 15 +- .../CustomNamespaceHandlerTests-context.xml | 8 +- .../support/CustomNamespaceHandlerTests.java | 25 +- .../AbstractApplicationContextTests.java | 8 +- .../context/LifecycleContextBean.java | 4 +- ...ndiBeanFactoryLocatorTests-collections.xml | 74 +- ...textJndiBeanFactoryLocatorTests-parent.xml | 6 +- .../ContextJndiBeanFactoryLocatorTests.java | 4 +- .../AbstractCircularImportDetectionTests.java | 4 +- .../AnnotationProcessorPerformanceTests.java | 6 +- .../ClassPathBeanDefinitionScannerTests.java | 4 +- ...PathFactoryBeanDefinitionScannerTests.java | 6 +- ...ommonAnnotationBeanPostProcessorTests.java | 12 +- ...mponentScanAnnotationIntegrationTests.java | 4 +- .../ComponentScanParserScopedProxyTests.java | 4 +- .../ConfigurationClassAndBFPPTests.java | 4 +- ...nClassPostConstructAndAutowiringTests.java | 4 +- .../ConfigurationClassPostProcessorTests.java | 4 +- .../FooServiceDependentConverter.java | 8 +- .../NestedConfigurationClassTests.java | 4 +- .../PropertySourceAnnotationTests.java | 4 +- .../componentscan/level1/Level1Config.java | 4 +- .../componentscan/level2/Level2Config.java | 4 +- .../AutowiredConfigurationTests.java | 6 +- .../BeanMethodQualificationTests.java | 4 +- ...figurationClassAspectIntegrationTests.java | 8 +- .../ConfigurationClassProcessingTests.java | 6 +- ...assWithPlaceholderConfigurerBeanTests.java | 6 +- .../ConfigurationMetaAnnotationTests.java | 4 +- .../ImportAnnotationDetectionTests.java | 4 +- ...ortNonXmlResourceConfig-context.properties | 2 +- .../configuration/ImportResourceTests.java | 6 +- .../annotation/configuration/ImportTests.java | 6 +- .../configuration/ImportXmlConfig-context.xml | 2 +- .../ImportXmlWithAopNamespace-context.xml | 2 +- ...tedConfigurationClassEnhancementTests.java | 4 +- .../configuration/ScopingTests.java | 6 +- .../annotation4/FactoryMethodComponent.java | 4 +- .../context/annotation4/SimpleBean.java | 4 +- .../annotation6/ConfigForScanning.java | 2 +- .../event/ApplicationContextEventTests.java | 4 +- .../EventPublicationInterceptorTests.java | 6 +- .../ApplicationContextExpressionTests.java | 4 +- .../EnvironmentAccessorIntegrationTests.java | 4 +- .../BeanFactoryPostProcessorTests.java | 4 +- ...athXmlApplicationContextTests-resource.xml | 2 +- ...ApplicationContextTests-resourceImport.xml | 2 +- .../ClassPathXmlApplicationContextTests.java | 4 +- .../ConversionServiceFactoryBeanTests.java | 4 +- ...rtyResourceConfigurerIntegrationTests.java | 4 +- ...ertySourcesPlaceholderConfigurerTests.java | 4 +- .../support/SimpleThreadScopeTest.java | 4 +- ...ticApplicationContextMulticasterTests.java | 4 +- .../StaticApplicationContextTests.java | 4 +- .../support/StaticMessageSourceTests.java | 6 +- .../context/support/conversionService.xml | 2 +- ...onversionServiceWithResourceOverriding.xml | 2 +- .../context/support/testBeans.properties | 20 +- .../config/JeeNamespaceHandlerEventTests.java | 4 +- .../ejb/config/JeeNamespaceHandlerTests.java | 6 +- .../ejb/config/jeeNamespaceHandlerTests.xml | 14 +- .../jmx/export/MBeanExporterTests.java | 7 +- .../AbstractMetadataAssemblerTests.java | 5 +- .../export/propertyPlaceholderConfigurer.xml | 2 +- .../jndi/JndiObjectFactoryBeanTests.java | 12 +- .../jndi/JndiPropertySourceTests.java | 4 +- .../jndi/SimpleNamingContextTests.java | 6 +- .../mock/env/MockPropertySource.java | 104 -- .../mock/jndi/ExpectedLookupTemplate.java | 82 -- .../mock/jndi/SimpleNamingContextBuilder.java | 237 ----- .../mock/jndi/package-info.java | 10 - .../scheduling/timer/TimerSupportTests.java | 4 +- .../scripting/ContextScriptBean.java | 4 +- .../scripting/TestBeanAwareMessenger.java | 4 +- .../scripting/bsh/BshScriptFactoryTests.java | 4 +- .../scripting/bsh/MessengerImpl.bsh | 2 +- .../scripting/bsh/bsh-with-xsd.xml | 2 +- .../groovy/GroovyScriptFactoryTests.java | 2 +- .../scripting/groovy/ScriptBean.groovy | 2 +- .../groovy/groovy-multiple-properties.xml | 2 +- ...tFactoryTests-beanNameAutoProxyCreator.xml | 2 +- ...sedJRubyScriptFactoryTests-factoryBean.xml | 2 +- .../jruby/AdvisedJRubyScriptFactoryTests.java | 5 +- .../jruby/JRubyScriptFactoryTests.java | 2 +- .../scripting/jruby/jruby-with-xsd.xml | 2 +- .../context}/SimpleMapScope.java | 3 +- .../context}/TestMethodInvokingTask.java | 2 +- .../mock/jndi/ExpectedLookupTemplate.java | 2 +- .../mock/jndi/SimpleNamingContext.java | 4 +- .../mock/jndi/SimpleNamingContextBuilder.java | 2 +- .../tests/mock/jndi/package-info.java} | 28 +- .../sample}/beans/BeanWithObjectProperty.java | 2 +- .../tests/sample}/beans/Employee.java | 4 +- .../tests/sample}/beans/FactoryMethods.java | 2 +- .../tests/sample}/beans/FieldAccessBean.java | 2 +- .../sample}/beans/ResourceTestBean.java | 2 +- .../org/springframework/ui/ModelMapTests.java | 4 +- .../util/SerializationTestUtils.java | 65 -- .../DataBinderFieldAccessTests.java | 6 +- .../validation/DataBinderTests.java | 36 +- .../DefaultMessageCodesResolverTests.java | 16 +- .../validation/ValidationUtilsTests.java | 4 +- .../BeanValidationPostProcessorTests.java | 4 +- .../test/advice/CountingBeforeAdvice.java | 36 - .../test/java/test/advice/MethodCounter.java | 70 -- .../src/test/java/test/beans/Colour.java | 37 - .../src/test/java/test/beans/CustomScope.java | 74 -- .../java/test/beans/DependsOnTestBean.java | 36 - .../test/java/test/beans/INestedTestBean.java | 22 - .../src/test/java/test/beans/IOther.java | 22 - .../src/test/java/test/beans/ITestBean.java | 62 -- .../test/java/test/beans/IndexedTestBean.java | 143 --- .../test/java/test/beans/NestedTestBean.java | 64 -- .../src/test/java/test/beans/TestBean.java | 436 -------- ...paceHandlerWithExpressionLanguageTests.xml | 4 +- .../support/simpleThreadScopeTests.xml | 18 +- .../core/type/AnnotationMetadataTests.java | 4 +- .../type}/TestAutowired.java | 2 +- .../type}/TestQualifier.java | 2 +- .../tests}/TestResourceUtils.java | 4 +- .../springframework/tests}/TimeStamped.java | 2 +- .../util/SerializationTestUtils.java | 60 +- .../org/springframework/beans/Colour.java | 36 - .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 457 --------- .../jdbc/core/RowMapperTests.java | 4 +- .../BeanPropertySqlParameterSourceTests.java | 4 +- .../JdbcBeanDefinitionReaderTests.java | 6 +- .../org/springframework/beans/Colour.java | 36 - .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 457 --------- .../jms/config/JmsNamespaceHandlerTests.java | 4 +- .../jms/config/jmsNamespaceHandlerTests.xml | 6 +- .../jms/remoting/JmsInvokerTests.java | 6 +- .../CallCountingTransactionManager.java | 63 -- .../web/DelegatingServletInputStream.java | 68 -- .../web/DelegatingServletOutputStream.java | 74 -- .../mock/web/HeaderValueHolder.java | 96 -- .../mock/web/MockFilterChain.java | 184 ---- .../mock/web/MockFilterConfig.java | 108 -- .../mock/web/MockHttpServletRequest.java | 964 ------------------ .../mock/web/MockHttpServletResponse.java | 641 ------------ .../mock/web/MockHttpSession.java | 278 ----- .../mock/web/MockRequestDispatcher.java | 95 -- .../mock/web/MockServletConfig.java | 107 -- .../mock/web/MockServletContext.java | 516 ---------- .../mock/web/PassThroughFilterChain.java | 86 -- .../org/springframework/beans/Colour.java | 36 - .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 457 --------- .../beans/factory/config/SimpleMapScope.java | 88 -- .../mock/jndi/ExpectedLookupTemplate.java | 82 -- .../mock/jndi/SimpleNamingContext.java | 381 ------- .../mock/jndi/SimpleNamingContextBuilder.java | 237 ----- .../HibernateJtaTransactionTests.java | 4 +- .../hibernate3/HibernateTemplateTests.java | 4 +- .../LocalSessionFactoryBeanTests.java | 10 +- .../orm/hibernate3/support/LobTypeTests.java | 4 +- .../orm/jdo/JdoTransactionManagerTests.java | 6 +- .../orm/jpa/domain/ContextualPerson.java | 4 +- .../orm/jpa/domain/Person.java | 4 +- .../orm/jpa/domain/persistence-multi.xml | 2 +- .../PersistenceXmlParsingTests.java | 4 +- .../support/PersistenceInjectionTests.java | 6 +- .../transaction/MockJtaTransaction.java | 67 -- .../util/SerializationTestUtils.java | 97 -- .../beans/factory/xml/child.xml | 6 +- .../beans/factory/xml/test.xml | 32 +- .../org/springframework/beans/Colour.java | 37 - .../org/springframework/beans/Employee.java | 39 - .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 146 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 455 --------- ...stractSpr3350SingleSpringContextTests.java | 4 +- ...ingleSpringContextTests-context.properties | 2 +- ...pr3350SingleSpringContextTests-context.xml | 2 +- ...AndInheritedLoaderTests-context.properties | 2 +- ...dingPropertiesAndInheritedLoaderTests.java | 4 +- ...xtendingPropertiesTests-context.properties | 2 +- ...ithPropertiesExtendingPropertiesTests.java | 4 +- ...ionalJUnit38SpringContextTests-context.xml | 4 +- ...ransactionalJUnit38SpringContextTests.java | 6 +- ...tionalJUnit4SpringContextTests-context.xml | 4 +- ...TransactionalJUnit4SpringContextTests.java | 6 +- ...ltContextLoaderClassSpringRunnerTests.java | 4 +- ...gJUnit4ClassRunnerAppCtxTests-context1.xml | 2 +- ...gJUnit4ClassRunnerAppCtxTests-context2.xml | 2 +- ...erizedDependencyInjectionTests-context.xml | 6 +- ...ParameterizedDependencyInjectionTests.java | 6 +- ...4ClassRunnerAppCtxTests-context.properties | 2 +- ...sedSpringJUnit4ClassRunnerAppCtxTests.java | 4 +- ...ngJUnit4ClassRunnerAppCtxTests-context.xml | 4 +- .../SpringJUnit4ClassRunnerAppCtxTests.java | 6 +- ...ingDefaultConfigClassesInheritedTests.java | 4 +- .../DefaultConfigClassesBaseTests.java | 4 +- .../DefaultConfigClassesInheritedTests.java | 4 +- ...ingDefaultConfigClassesInheritedTests.java | 4 +- ...ltLoaderDefaultConfigClassesBaseTests.java | 4 +- ...derDefaultConfigClassesInheritedTests.java | 4 +- ...tLoaderExplicitConfigClassesBaseTests.java | 4 +- ...erExplicitConfigClassesInheritedTests.java | 4 +- .../ExplicitConfigClassesBaseTests.java | 4 +- .../ExplicitConfigClassesInheritedTests.java | 4 +- .../annotation/PojoAndStringConfig.java | 6 +- .../DefaultProfileAnnotationConfigTests.java | 6 +- .../annotation/DefaultProfileConfig.java | 4 +- .../profile/annotation/DevProfileConfig.java | 4 +- .../DefaultProfileAnnotationConfigTests.java | 6 +- .../importresource/DefaultProfileConfig.java | 4 +- .../junit4/profile/importresource/import.xml | 2 +- .../DefaultProfileXmlConfigTests-context.xml | 4 +- .../xml/DefaultProfileXmlConfigTests.java | 6 +- ...DefaultLocationsInheritedTests-context.xml | 2 +- .../DefaultLocationsBaseTests-context.xml | 2 +- .../spr3896/DefaultLocationsBaseTests.java | 4 +- ...DefaultLocationsInheritedTests-context.xml | 2 +- .../DefaultLocationsInheritedTests.java | 4 +- .../spr3896/ExplicitLocationsBaseTests.java | 4 +- .../ExplicitLocationsInheritedTests.java | 4 +- ...ransactionalAnnotatedConfigClassTests.java | 4 +- ...edConfigClassWithAtConfigurationTests.java | 4 +- ...figClassesWithoutAtConfigurationTests.java | 4 +- ...aTransactionManagementConfigurerTests.java | 6 +- .../spr9645/LookUpNonexistentTxMgrTests.java | 6 +- .../LookUpTxMgrByTypeAndDefaultNameTests.java | 6 +- .../LookUpTxMgrByTypeAndNameTests.java | 6 +- ...grByTypeAndQualifierAtClassLevelTests.java | 6 +- ...rByTypeAndQualifierAtMethodLevelTests.java | 6 +- .../spr9645/LookUpTxMgrByTypeTests.java | 6 +- ...TransactionalTestNGSpringContextTests.java | 6 +- ...tionalTestNGSpringContextTests-context.xml | 4 +- ...TransactionalTestNGSpringContextTests.java | 6 +- .../RequestAndSessionScopedBeansWacTests.java | 4 +- ...tAndSessionScopedBeansWacTests-context.xml | 4 +- .../org/springframework/beans/Colour.java | 36 - .../beans/DerivedTestBean.java | 90 -- .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 457 --------- .../CollectingReaderEventListener.java | 91 -- .../mock/jndi/SimpleNamingContext.java | 381 ------- .../CallCountingTransactionManager.java | 3 +- .../transaction/MockJtaTransaction.java | 2 +- .../CallCountingTransactionManager.java | 63 -- .../JndiJtaTransactionManagerTests.java | 4 +- .../JtaTransactionManagerTests.java | 3 +- .../TxNamespaceHandlerEventTests.java | 4 +- .../transaction/TxNamespaceHandlerTests.java | 5 +- ...tationTransactionAttributeSourceTests.java | 4 +- ...AnnotationTransactionInterceptorTests.java | 4 +- ...ationTransactionNamespaceHandlerTests.java | 4 +- .../EnableTransactionManagementTests.java | 4 +- ...tationTransactionNamespaceHandlerTests.xml | 2 +- .../config/AnnotationDrivenTests.java | 4 +- .../TransactionManagerConfiguration.java | 4 +- .../annotationDrivenProxyTargetClassTests.xml | 4 +- .../AbstractTransactionAspectTests.java | 6 +- .../BeanFactoryTransactionTests.java | 10 +- .../interceptor/ImplementsNoInterfaces.java | 4 +- .../noTransactionAttributeSource.xml | 5 +- .../interceptor/transactionalBeanFactory.xml | 12 +- .../WebSphereUowTransactionManagerTests.java | 4 +- ...aTransactionManagerSerializationTests.java | 4 +- .../transaction/txNamespaceHandlerTests.xml | 4 +- .../util/SerializationTestUtils.java | 97 -- .../beans/BeanWithObjectProperty.java | 35 - .../org/springframework/beans/Colour.java | 36 - .../beans/DerivedTestBean.java | 90 -- .../beans/FieldAccessBean.java | 44 - .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../beans/SerializablePerson.java | 70 -- .../org/springframework/beans/TestBean.java | 495 --------- .../beans/factory/DummyFactory.java | 179 ---- .../AbstractHttpRequestFactoryTestCase.java | 3 +- .../http/client/FreePortScanner.java | 99 -- .../remoting/caucho/CauchoRemotingTests.java | 6 +- .../httpinvoker/HttpInvokerTests.java | 6 +- .../tests/web}/FreePortScanner.java | 2 +- .../util/SerializationTestUtils.java | 97 -- .../web/bind/EscapedErrorsTests.java | 4 +- .../bind/ServletRequestDataBinderTests.java | 6 +- .../support/WebRequestDataBinderTests.java | 39 +- .../client/RestTemplateIntegrationTests.java | 4 +- .../RequestAndSessionScopedBeanTests.java | 4 +- .../context/request/RequestScopeTests.java | 6 +- .../request/RequestScopedProxyTests.java | 10 +- .../context/request/SessionScopeTests.java | 6 +- .../WebApplicationContextScopeTests.java | 4 +- .../SpringBeanAutowiringSupportTests.java | 6 +- .../jsf/DelegatingVariableResolverTests.java | 4 +- .../ModelAttributeMethodProcessorTests.java | 4 +- .../SessionAttributesHandlerTests.java | 4 +- .../web/context/request/requestScopeTests.xml | 18 +- .../request/requestScopedProxyTests.xml | 20 +- .../web/context/request/sessionScopeTests.xml | 4 +- .../org/springframework/beans/Colour.java | 36 - .../beans/DerivedTestBean.java | 90 -- .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/TestBean.java | 457 --------- .../factory/AbstractBeanFactoryTests.java | 329 ------ .../AbstractListableBeanFactoryTests.java | 84 -- .../beans/factory/DummyFactory.java | 179 ---- .../beans/factory/LifecycleBean.java | 164 --- .../beans/factory/MustBeInitialized.java | 47 - .../AbstractApplicationContextTests.java | 160 --- .../context/LifecycleContextBean.java | 2 +- .../web/DelegatingServletOutputStream.java | 74 -- .../mock/web/HeaderValueHolder.java | 96 -- .../mock/web/MockHttpServletResponse.java | 641 ------------ .../mock/web/MockHttpSession.java | 278 ----- .../mock/web/MockMultipartFile.java | 139 --- .../mock/web/MockRequestDispatcher.java | 95 -- .../mock/web/MockServletContext.java | 516 ---------- .../mock/web/portlet/MockPortletSession.java | 5 +- .../ComplexPortletApplicationContext.java | 5 +- .../web/portlet/DispatcherPortletTests.java | 4 +- .../SimplePortletApplicationContext.java | 4 +- .../bind/PortletRequestDataBinderTests.java | 6 +- ...AbstractXmlWebApplicationContextTests.java | 4 +- .../PortletApplicationContextScopeTests.java | 14 +- .../context/WEB-INF/applicationContext.xml | 6 +- .../context/WEB-INF/contextInclude.xml | 2 +- .../portlet/context/WEB-INF/test-servlet.xml | 16 +- .../XmlPortletApplicationContextTests.java | 4 +- .../portlet/mvc/CommandControllerTests.java | 6 +- .../Portlet20AnnotationControllerTests.java | 8 +- .../PortletAnnotationControllerTests.java | 8 +- .../web/portlet/util/PortletUtilsTests.java | 6 +- .../beans/BeanWithObjectProperty.java | 35 - .../org/springframework/beans/Colour.java | 36 - .../beans/DerivedTestBean.java | 90 -- .../springframework/beans/GenericBean.java | 247 ----- .../beans/INestedTestBean.java | 23 - .../org/springframework/beans/IOther.java | 24 - .../org/springframework/beans/ITestBean.java | 71 -- .../beans/IndexedTestBean.java | 145 --- .../springframework/beans/NestedTestBean.java | 61 -- .../org/springframework/beans/Person.java | 36 - .../java/org/springframework/beans/Pet.java | 54 - .../org/springframework/beans/TestBean.java | 457 --------- .../beans/factory/DummyFactory.java | 179 ---- .../beans/factory/LifecycleBean.java | 164 --- .../beans/factory/MustBeInitialized.java | 47 - .../context/LifecycleContextBean.java | 2 +- .../ui/jasperreports/PersonBean.java | 64 -- .../ui/jasperreports/ProductBean.java | 64 -- .../util/SerializationTestUtils.java | 65 -- .../AbstractApplicationContextTests.java | 166 --- .../web/context/AbstractBeanFactoryTests.java | 337 ------ .../AbstractListableBeanFactoryTests.java | 71 -- .../web/context/ContextLoaderTests.java | 6 +- .../ResourceBundleMessageSourceTests.java | 281 ----- .../ContextLoaderTests-acc-context.xml | 2 +- .../context/WEB-INF/applicationContext.xml | 6 +- .../web/context/WEB-INF/context-addition.xml | 14 +- .../web/context/WEB-INF/contextInclude.xml | 2 +- .../web/context/WEB-INF/sessionContext.xml | 4 +- .../web/context/WEB-INF/test-servlet.xml | 16 +- .../web/context/WEB-INF/testNamespace.xml | 4 +- .../XmlWebApplicationContextTests.java | 5 +- .../support/ServletContextSupportTests.java | 4 +- .../servlet/ComplexWebApplicationContext.java | 4 +- .../web/servlet/DispatcherServletTests.java | 4 +- .../servlet/SimpleWebApplicationContext.java | 4 +- ...MvcConfigurationSupportExtensionTests.java | 4 +- .../mvc/CancellableFormControllerTests.java | 4 +- .../servlet/mvc/CommandControllerTests.java | 4 +- .../web/servlet/mvc/FormControllerTests.java | 6 +- .../mvc/WizardFormControllerTests.java | 4 +- .../ServletAnnotationControllerTests.java | 12 +- ...ExtendedServletRequestDataBinderTests.java | 4 +- ...ResolverMethodReturnValueHandlerTests.java | 4 +- ...MappingHandlerAdapterIntegrationTests.java | 4 +- .../RequestPartIntegrationTests.java | 4 +- ...vetModelAttributeMethodProcessorTests.java | 4 +- ...nnotationControllerHandlerMethodTests.java | 12 +- .../MultiActionControllerTests.java | 4 +- .../DefaultHandlerExceptionResolverTests.java | 4 +- .../RedirectAttributesModelMapTests.java | 4 +- .../web/servlet/tags/BindTagTests.java | 8 +- .../tags/form/AbstractFormTagTests.java | 4 +- .../web/servlet/tags/form/ButtonTagTests.java | 4 +- .../servlet/tags/form/CheckboxTagTests.java | 8 +- .../servlet/tags/form/CheckboxesTagTests.java | 8 +- .../web/servlet/tags/form/ErrorsTagTests.java | 4 +- .../tags/form/HiddenInputTagTests.java | 4 +- .../web/servlet/tags/form/InputTagTests.java | 4 +- .../web/servlet/tags/form/LabelTagTests.java | 4 +- .../servlet/tags/form/OptionTagEnumTests.java | 6 +- .../web/servlet/tags/form/OptionTagTests.java | 6 +- .../servlet/tags/form/OptionsTagTests.java | 4 +- .../tags/form/RadioButtonTagTests.java | 6 +- .../tags/form/RadioButtonsTagTests.java | 8 +- .../web/servlet/tags/form/SelectTagTests.java | 6 +- .../tags/form/TestBeanWithRealCountry.java | 4 +- .../servlet/tags/form/TextareaTagTests.java | 4 +- .../web/servlet/view/RedirectViewTests.java | 4 +- .../web/servlet/view/ViewResolverTests.java | 4 +- .../view/freemarker/FreeMarkerMacroTests.java | 4 +- .../view/velocity/VelocityMacroTests.java | 4 +- .../view/velocity/VelocityRenderTests.java | 4 +- .../web/context/WEB-INF/sessionContext.xml | 4 +- ...ceHandlerScopeIntegrationTests-context.xml | 8 +- ...NamespaceHandlerScopeIntegrationTests.java | 14 +- ...toProxyCreatorIntegrationTests-context.xml | 32 +- ...visorAutoProxyCreatorIntegrationTests.java | 59 +- ...ansactionalAnnotationIntegrationTests.java | 18 +- .../CallCountingTransactionManager.java | 65 -- ...TransactionManagementIntegrationTests.java | 4 +- .../advice/CountingAfterReturningAdvice.java | 36 - .../test/advice/CountingBeforeAdvice.java | 36 - src/test/java/test/beans/Colour.java | 36 - src/test/java/test/beans/INestedTestBean.java | 23 - src/test/java/test/beans/IOther.java | 24 - src/test/java/test/beans/ITestBean.java | 71 -- src/test/java/test/beans/IndexedTestBean.java | 145 --- src/test/java/test/beans/NestedTestBean.java | 61 -- src/test/java/test/beans/Pet.java | 54 - src/test/java/test/beans/TestBean.java | 457 --------- .../java/test/interceptor/NopInterceptor.java | 59 -- .../SerializableNopInterceptor.java | 48 - .../test/util/SerializationTestUtils.java | 100 -- 813 files changed, 2241 insertions(+), 27860 deletions(-) rename {spring-context/src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/advice/CountingAfterReturningAdvice.java (95%) rename spring-aop/src/test/java/{test/aop => org/springframework/tests/aop/advice}/CountingBeforeAdvice.java (95%) rename {src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/advice/MethodCounter.java (97%) rename {spring-context/src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/advice/MyThrowsHandler.java (93%) rename {spring-context/src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/advice/TimestampIntroductionAdvisor.java (89%) rename {spring-context/src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/interceptor/NopInterceptor.java (96%) rename {spring-context/src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/interceptor/SerializableNopInterceptor.java (95%) rename {spring-context/src/test/java/test => spring-aop/src/test/java/org/springframework/tests/aop}/interceptor/TimestampIntroductionInterceptor.java (89%) rename {spring-web/src/test/java/org/springframework => spring-aop/src/test/java/org/springframework/tests/sample}/beans/Person.java (82%) rename {spring-webmvc/src/test/java/org/springframework => spring-aop/src/test/java/org/springframework/tests/sample}/beans/SerializablePerson.java (96%) rename spring-aop/src/test/java/{test => org/springframework/tests/sample}/beans/subpkg/DeepBean.java (94%) delete mode 100644 spring-aop/src/test/java/test/aop/MethodCounter.java delete mode 100644 spring-aop/src/test/java/test/aop/NopInterceptor.java delete mode 100644 spring-aop/src/test/java/test/aop/SerializableNopInterceptor.java delete mode 100644 spring-aop/src/test/java/test/beans/Colour.java delete mode 100644 spring-aop/src/test/java/test/beans/DerivedTestBean.java delete mode 100644 spring-aop/src/test/java/test/beans/INestedTestBean.java delete mode 100644 spring-aop/src/test/java/test/beans/IOther.java delete mode 100644 spring-aop/src/test/java/test/beans/ITestBean.java delete mode 100644 spring-aop/src/test/java/test/beans/NestedTestBean.java delete mode 100644 spring-aop/src/test/java/test/beans/Person.java delete mode 100644 spring-aop/src/test/java/test/beans/SerializablePerson.java delete mode 100644 spring-aop/src/test/java/test/beans/TestBean.java delete mode 100644 spring-aop/src/test/java/test/parsing/CollectingReaderEventListener.java delete mode 100644 spring-aop/src/test/java/test/util/SerializationTestUtils.java delete mode 100644 spring-aop/src/test/java/test/util/TimeStamped.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-aspects/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractAnnotationTest.java rename spring-aspects/src/test/java/org/springframework/cache/aspectj/{AspectJAnnotationTest.java => AspectJAnnotationTests.java} (56%) delete mode 100644 spring-aspects/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java rename {spring-context => spring-beans}/src/test/java/org/springframework/beans/factory/access/beans1.xml (100%) rename {spring-context => spring-beans}/src/test/java/org/springframework/beans/factory/access/beans2.xml (100%) rename spring-beans/src/test/java/org/springframework/{beans/factory/xml => tests/beans}/CollectingReaderEventListener.java (98%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/BooleanTestBean.java (95%) rename {spring-context-support/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/Colour.java (95%) rename {spring-aop/src/test/java/test => spring-beans/src/test/java/org/springframework/tests/sample}/beans/CountingTestBean.java (94%) rename {spring-webmvc/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/CustomEnum.java (94%) rename spring-beans/src/test/java/org/springframework/{beans/factory/xml => tests/sample/beans}/DependenciesBean.java (95%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/DerivedTestBean.java (97%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/DummyBean.java (96%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/DummyFactory.java (97%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/GenericBean.java (95%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/GenericIntegerBean.java (93%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/GenericSetOfIntegerBean.java (94%) rename {spring-context/src/test/java/org/springframework/beans/factory => spring-beans/src/test/java/org/springframework/tests/sample/beans}/HasMap.java (75%) rename {spring-aspects/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/INestedTestBean.java (93%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/IOther.java (93%) rename {spring-web/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/ITestBean.java (90%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/IndexedTestBean.java (98%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/LifecycleBean.java (99%) rename {spring-context/src/test/java/org/springframework/beans/factory => spring-beans/src/test/java/org/springframework/tests/sample/beans}/MustBeInitialized.java (92%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/NestedTestBean.java (96%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/NumberTestBean.java (98%) rename spring-beans/src/test/java/{test => org/springframework/tests/sample}/beans/PackageLevelVisibleBean.java (94%) rename {spring-test/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/Pet.java (96%) rename {spring-aop/src/test/java/test => spring-beans/src/test/java/org/springframework/tests/sample}/beans/SideEffectBean.java (95%) rename {spring-context/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/TestBean.java (89%) rename {spring-context/src/test/java/org/springframework => spring-beans/src/test/java/org/springframework/tests/sample}/beans/factory/DummyFactory.java (87%) create mode 100644 spring-beans/src/test/java/org/springframework/tests/sample/beans/package-info.java delete mode 100644 spring-beans/src/test/java/org/springframework/util/SerializationTestUtils.java delete mode 100644 spring-beans/src/test/java/test/beans/Colour.java delete mode 100644 spring-beans/src/test/java/test/beans/CustomEnum.java delete mode 100644 spring-beans/src/test/java/test/beans/INestedTestBean.java delete mode 100644 spring-beans/src/test/java/test/beans/ITestBean.java delete mode 100644 spring-beans/src/test/java/test/beans/TestBean.java delete mode 100644 spring-beans/src/test/java/test/util/TestResourceUtils.java delete mode 100644 spring-context-support/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-context-support/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-context-support/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-context-support/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-context-support/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-context-support/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-context-support/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/FieldAccessBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/Person.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/SerializablePerson.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/LifecycleBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocatorTests.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/access/TestBean.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/access/ref1.xml delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java delete mode 100644 spring-context/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java delete mode 100644 spring-context/src/test/java/org/springframework/mock/env/MockPropertySource.java delete mode 100644 spring-context/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java delete mode 100644 spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java delete mode 100644 spring-context/src/test/java/org/springframework/mock/jndi/package-info.java rename spring-context/src/test/java/org/springframework/{beans/factory/config => tests/context}/SimpleMapScope.java (95%) rename spring-context/src/test/java/org/springframework/{scheduling => tests/context}/TestMethodInvokingTask.java (96%) rename {spring-tx/src/test/java/org/springframework => spring-context/src/test/java/org/springframework/tests}/mock/jndi/ExpectedLookupTemplate.java (98%) rename spring-context/src/test/java/org/springframework/{ => tests}/mock/jndi/SimpleNamingContext.java (98%) rename {spring-tx/src/test/java/org/springframework => spring-context/src/test/java/org/springframework/tests}/mock/jndi/SimpleNamingContextBuilder.java (99%) rename spring-context/src/test/java/{test/beans/SideEffectBean.java => org/springframework/tests/mock/jndi/package-info.java} (62%) rename spring-context/src/test/java/org/springframework/{ => tests/sample}/beans/BeanWithObjectProperty.java (94%) rename spring-context/src/test/java/{test => org/springframework/tests/sample}/beans/Employee.java (89%) rename spring-context/src/test/java/{test => org/springframework/tests/sample}/beans/FactoryMethods.java (95%) rename {spring-webmvc/src/test/java/org/springframework => spring-context/src/test/java/org/springframework/tests/sample}/beans/FieldAccessBean.java (95%) rename spring-context/src/test/java/org/springframework/{ => tests/sample}/beans/ResourceTestBean.java (97%) delete mode 100644 spring-context/src/test/java/org/springframework/util/SerializationTestUtils.java delete mode 100644 spring-context/src/test/java/test/advice/CountingBeforeAdvice.java delete mode 100644 spring-context/src/test/java/test/advice/MethodCounter.java delete mode 100644 spring-context/src/test/java/test/beans/Colour.java delete mode 100644 spring-context/src/test/java/test/beans/CustomScope.java delete mode 100644 spring-context/src/test/java/test/beans/DependsOnTestBean.java delete mode 100644 spring-context/src/test/java/test/beans/INestedTestBean.java delete mode 100644 spring-context/src/test/java/test/beans/IOther.java delete mode 100644 spring-context/src/test/java/test/beans/ITestBean.java delete mode 100644 spring-context/src/test/java/test/beans/IndexedTestBean.java delete mode 100644 spring-context/src/test/java/test/beans/NestedTestBean.java delete mode 100644 spring-context/src/test/java/test/beans/TestBean.java rename spring-core/src/test/java/org/springframework/{beans/factory/annotation => core/type}/TestAutowired.java (95%) rename spring-core/src/test/java/org/springframework/{beans/factory/annotation => core/type}/TestQualifier.java (95%) rename {spring-aop/src/test/java/test/util => spring-core/src/test/java/org/springframework/tests}/TestResourceUtils.java (91%) rename {spring-context/src/test/java/test/util => spring-core/src/test/java/org/springframework/tests}/TimeStamped.java (96%) delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-jdbc/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-jms/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-jms/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletInputStream.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/HeaderValueHolder.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterChain.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockFilterConfig.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletRequest.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockHttpSession.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletConfig.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/MockServletContext.java delete mode 100644 spring-orm-hibernate4/src/test/java/org/springframework/mock/web/PassThroughFilterChain.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-orm/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java delete mode 100644 spring-orm/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java delete mode 100644 spring-orm/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java delete mode 100644 spring-orm/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java delete mode 100644 spring-orm/src/test/java/org/springframework/transaction/MockJtaTransaction.java delete mode 100644 spring-orm/src/test/java/org/springframework/util/SerializationTestUtils.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/Employee.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-test/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-tx/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java delete mode 100644 spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java rename {spring-test/src/test/java/org/springframework/test => spring-tx/src/test/java/org/springframework/tests}/transaction/CallCountingTransactionManager.java (97%) rename spring-tx/src/test/java/org/springframework/{ => tests}/transaction/MockJtaTransaction.java (96%) delete mode 100644 spring-tx/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java delete mode 100644 spring-tx/src/test/java/org/springframework/util/SerializationTestUtils.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/BeanWithObjectProperty.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/FieldAccessBean.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/SerializablePerson.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-web/src/test/java/org/springframework/beans/factory/DummyFactory.java delete mode 100644 spring-web/src/test/java/org/springframework/http/client/FreePortScanner.java rename {spring-webmvc/src/test/java/org/springframework/http/client => spring-web/src/test/java/org/springframework/tests/web}/FreePortScanner.java (98%) delete mode 100644 spring-web/src/test/java/org/springframework/util/SerializationTestUtils.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/DummyFactory.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/LifecycleBean.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/MustBeInitialized.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/context/AbstractApplicationContextTests.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/HeaderValueHolder.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpSession.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockMultipartFile.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java delete mode 100644 spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockServletContext.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/BeanWithObjectProperty.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/Colour.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/DerivedTestBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/GenericBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/INestedTestBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/IOther.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/ITestBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/IndexedTestBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/NestedTestBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/Person.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/Pet.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/TestBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/factory/DummyFactory.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/factory/LifecycleBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/beans/factory/MustBeInitialized.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/ui/jasperreports/ProductBean.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/util/SerializationTestUtils.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/context/AbstractApplicationContextTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/context/AbstractBeanFactoryTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/context/AbstractListableBeanFactoryTests.java delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/context/ResourceBundleMessageSourceTests.java delete mode 100644 src/test/java/org/springframework/transaction/CallCountingTransactionManager.java delete mode 100644 src/test/java/test/advice/CountingAfterReturningAdvice.java delete mode 100644 src/test/java/test/advice/CountingBeforeAdvice.java delete mode 100644 src/test/java/test/beans/Colour.java delete mode 100644 src/test/java/test/beans/INestedTestBean.java delete mode 100644 src/test/java/test/beans/IOther.java delete mode 100644 src/test/java/test/beans/ITestBean.java delete mode 100644 src/test/java/test/beans/IndexedTestBean.java delete mode 100644 src/test/java/test/beans/NestedTestBean.java delete mode 100644 src/test/java/test/beans/Pet.java delete mode 100644 src/test/java/test/beans/TestBean.java delete mode 100644 src/test/java/test/interceptor/NopInterceptor.java delete mode 100644 src/test/java/test/interceptor/SerializableNopInterceptor.java delete mode 100644 src/test/java/test/util/SerializationTestUtils.java diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java index cf96bf3f06..429350b00d 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,10 +33,10 @@ import org.springframework.aop.Pointcut; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DefaultPointcutAdvisor; -import test.beans.IOther; -import test.beans.ITestBean; -import test.beans.TestBean; -import test.beans.subpkg.DeepBean; +import org.springframework.tests.sample.beans.IOther; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.subpkg.DeepBean; /** * @author Rob Harrop @@ -66,7 +66,7 @@ public final class AspectJExpressionPointcutTests { @Test public void testMatchExplicit() { - String expression = "execution(int test.beans.TestBean.getAge())"; + String expression = "execution(int org.springframework.tests.sample.beans.TestBean.getAge())"; Pointcut pointcut = getPointcut(expression); ClassFilter classFilter = pointcut.getClassFilter(); @@ -128,8 +128,8 @@ public final class AspectJExpressionPointcutTests { * @throws SecurityException */ private void testThisOrTarget(String which) throws SecurityException, NoSuchMethodException { - String matchesTestBean = which + "(test.beans.TestBean)"; - String matchesIOther = which + "(test.beans.IOther)"; + String matchesTestBean = which + "(org.springframework.tests.sample.beans.TestBean)"; + String matchesIOther = which + "(org.springframework.tests.sample.beans.IOther)"; AspectJExpressionPointcut testBeanPc = new AspectJExpressionPointcut(); testBeanPc.setExpression(matchesTestBean); @@ -156,7 +156,7 @@ public final class AspectJExpressionPointcutTests { } private void testWithinPackage(boolean matchSubpackages) throws SecurityException, NoSuchMethodException { - String withinBeansPackage = "within(test.beans."; + String withinBeansPackage = "within(org.springframework.tests.sample.beans."; // Subpackages are matched by ** if (matchSubpackages) { withinBeansPackage += "."; @@ -214,7 +214,7 @@ public final class AspectJExpressionPointcutTests { @Test public void testMatchWithArgs() throws Exception { - String expression = "execution(void test.beans.TestBean.setSomeNumber(Number)) && args(Double)"; + String expression = "execution(void org.springframework.tests.sample.beans.TestBean.setSomeNumber(Number)) && args(Double)"; Pointcut pointcut = getPointcut(expression); ClassFilter classFilter = pointcut.getClassFilter(); @@ -235,7 +235,7 @@ public final class AspectJExpressionPointcutTests { @Test public void testSimpleAdvice() { - String expression = "execution(int test.beans.TestBean.getAge())"; + String expression = "execution(int org.springframework.tests.sample.beans.TestBean.getAge())"; CallCountingInterceptor interceptor = new CallCountingInterceptor(); @@ -254,7 +254,7 @@ public final class AspectJExpressionPointcutTests { @Test public void testDynamicMatchingProxy() { - String expression = "execution(void test.beans.TestBean.setSomeNumber(Number)) && args(Double)"; + String expression = "execution(void org.springframework.tests.sample.beans.TestBean.setSomeNumber(Number)) && args(Double)"; CallCountingInterceptor interceptor = new CallCountingInterceptor(); @@ -273,7 +273,7 @@ public final class AspectJExpressionPointcutTests { @Test public void testInvalidExpression() { - String expression = "execution(void test.beans.TestBean.setSomeNumber(Number) && args(Double)"; + String expression = "execution(void org.springframework.tests.sample.beans.TestBean.setSomeNumber(Number) && args(Double)"; try { getPointcut(expression).getClassFilter(); // call to getClassFilter forces resolution @@ -315,7 +315,7 @@ public final class AspectJExpressionPointcutTests { @Test public void testWithUnsupportedPointcutPrimitive() throws Exception { - String expression = "call(int test.beans.TestBean.getAge())"; + String expression = "call(int org.springframework.tests.sample.beans.TestBean.getAge())"; try { getPointcut(expression).getClassFilter(); // call to getClassFilter forces resolution... diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java index ac6dc31a2a..057ad77309 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutMatchingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.*; import org.junit.Test; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Tests for matching of bean() pointcut designator. diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java index 8c84e801b8..551756eea7 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,8 @@ import org.aspectj.lang.reflect.SourceLocation; import org.aspectj.runtime.reflect.Factory; import static org.junit.Assert.*; import org.junit.Test; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.framework.AopContext; diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java index b8c336b0fb..13635c2c6d 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import org.junit.Test; import test.annotation.EmptySpringAnnotation; import test.annotation.transaction.Tx; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** @@ -70,7 +70,7 @@ public final class TigerAspectJExpressionPointcutTests { @Test public void testMatchGenericArgument() { - String expression = "execution(* set*(java.util.List) )"; + String expression = "execution(* set*(java.util.List) )"; AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut(); ajexp.setExpression(expression); diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java index fea874179e..0275360441 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TypePatternClassFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,11 +22,11 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import test.beans.CountingTestBean; -import test.beans.IOther; -import test.beans.ITestBean; -import test.beans.TestBean; -import test.beans.subpkg.DeepBean; +import org.springframework.tests.sample.beans.CountingTestBean; +import org.springframework.tests.sample.beans.IOther; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.subpkg.DeepBean; /** * Unit tests for the {@link TypePatternClassFilter} class. @@ -45,7 +45,7 @@ public final class TypePatternClassFilterTests { @Test public void testValidPatternMatching() { - TypePatternClassFilter tpcf = new TypePatternClassFilter("test.beans.*"); + TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.*"); assertTrue("Must match: in package", tpcf.matches(TestBean.class)); assertTrue("Must match: in package", tpcf.matches(ITestBean.class)); assertTrue("Must match: in package", tpcf.matches(IOther.class)); @@ -56,7 +56,7 @@ public final class TypePatternClassFilterTests { @Test public void testSubclassMatching() { - TypePatternClassFilter tpcf = new TypePatternClassFilter("test.beans.ITestBean+"); + TypePatternClassFilter tpcf = new TypePatternClassFilter("org.springframework.tests.sample.beans.ITestBean+"); assertTrue("Must match: in package", tpcf.matches(TestBean.class)); assertTrue("Must match: in package", tpcf.matches(ITestBean.class)); assertTrue("Must match: in package", tpcf.matches(CountingTestBean.class)); diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java index ae3ac04918..273869e8a0 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,8 +58,8 @@ import test.aop.DefaultLockable; import test.aop.Lockable; import test.aop.PerTargetAspect; import test.aop.TwoAdviceAspect; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Abstract tests for AspectJAdvisorFactory. @@ -650,7 +650,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { } - @Aspect("pertypewithin(test.beans.IOther+)") + @Aspect("pertypewithin(org.springframework.tests.sample.beans.IOther+)") public static class PerTypeWithinAspect { public int count; @@ -979,7 +979,7 @@ abstract class AbstractMakeModifiable { @Aspect class MakeITestBeanModifiable extends AbstractMakeModifiable { - @DeclareParents(value = "test.beans.ITestBean+", + @DeclareParents(value = "org.springframework.tests.sample.beans.ITestBean+", defaultImpl=ModifiableImpl.class) public static MutableModifable mixin; diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java index d15b0a11ca..66d5e0f739 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/ArgumentBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ import org.aspectj.lang.annotation.Pointcut; import org.junit.Test; import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Adrian Colyer diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java index 88beb1455a..966d289eb1 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectJPointcutAdvisorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.aop.aspectj.AspectJExpressionPointcutTests; import org.springframework.aop.framework.AopConfigException; import test.aop.PerTargetAspect; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java index 93aebbfa67..16d6f0e9e7 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AspectProxyFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,14 +16,16 @@ package org.springframework.aop.aspectj.annotation; +import static org.junit.Assert.assertEquals; + import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; +import org.springframework.util.SerializationTestUtils; + import test.aop.PerThisAspect; -import test.util.SerializationTestUtils; /** * @author Rob Harrop diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java index 6b7d3ff096..f1ff305aad 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.aop.aspectj.autoproxy; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; @@ -30,8 +30,7 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.factory.xml.XmlReaderContext; - -import test.parsing.CollectingReaderEventListener; +import org.springframework.tests.beans.CollectingReaderEventListener; /** * @author Rob Harrop diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests-context.xml b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests-context.xml index 939493b2eb..984f5ada7b 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests-context.xml +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests-context.xml @@ -20,7 +20,7 @@ - + diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java index 0d86588b8c..fec13dbbed 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,10 @@ package org.springframework.aop.config; -import static org.junit.Assert.*; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.HashSet; import java.util.Set; @@ -32,8 +34,7 @@ import org.springframework.beans.factory.parsing.CompositeComponentDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; - -import test.parsing.CollectingReaderEventListener; +import org.springframework.tests.beans.CollectingReaderEventListener; /** * @author Rob Harrop diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutDuplication.xml b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutDuplication.xml index 472b91f718..cd01ffd532 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutDuplication.xml +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutDuplication.xml @@ -14,7 +14,7 @@ - + diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutMissing.xml b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutMissing.xml index 7654895cce..850fbc15d1 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutMissing.xml +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests-pointcutMissing.xml @@ -14,7 +14,7 @@ - + diff --git a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java index 19ea1742c0..7320dd553c 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/config/AopNamespaceHandlerPointcutErrorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.aop.config; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; diff --git a/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java b/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java index 3dbd38f98c..9e0b3d14eb 100644 --- a/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/config/TopLevelAopTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.aop.config; import static org.junit.Assert.assertTrue; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java index dca823663d..e2abdda799 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import java.util.List; import org.junit.Test; import org.springframework.aop.SpringProxy; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/IntroductionBenchmarkTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/IntroductionBenchmarkTests.java index 03b971fed0..eaaf2d8d42 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/IntroductionBenchmarkTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/IntroductionBenchmarkTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import org.junit.Test; import org.springframework.aop.support.DelegatingIntroductionInterceptor; import org.springframework.util.StopWatch; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Benchmarks for introductions. diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java index 4e81553444..139ef6c415 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/MethodInvocationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.junit.Test; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java index 7f5a4bc437..d9d43527de 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.aop.framework; import static org.junit.Assert.assertEquals; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java index ddf48d28d8..7f85602888 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/ProxyFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +16,33 @@ package org.springframework.aop.framework; +import static org.hamcrest.CoreMatchers.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import javax.accessibility.Accessible; -import javax.swing.*; +import javax.swing.JFrame; +import javax.swing.RootPaneContainer; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; import org.junit.Ignore; import org.junit.Test; -import test.aop.CountingBeforeAdvice; -import test.aop.NopInterceptor; -import test.beans.IOther; -import test.beans.ITestBean; -import test.beans.TestBean; -import test.util.TimeStamped; - import org.springframework.aop.Advisor; import org.springframework.aop.interceptor.DebugInterceptor; import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.DefaultIntroductionAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.DelegatingIntroductionInterceptor; +import org.springframework.tests.TimeStamped; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.IOther; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Also tests AdvisedSupport and ProxyCreatorSupport superclasses. @@ -190,7 +195,7 @@ public final class ProxyFactoryTests { TestBeanSubclass raw = new TestBeanSubclass(); ProxyFactory factory = new ProxyFactory(raw); //System.out.println("Proxied interfaces are " + StringUtils.arrayToDelimitedString(factory.getProxiedInterfaces(), ",")); - assertEquals("Found correct number of interfaces", 3, factory.getProxiedInterfaces().length); + assertEquals("Found correct number of interfaces", 5, factory.getProxiedInterfaces().length); ITestBean tb = (ITestBean) factory.getProxy(); assertThat("Picked up secondary interface", tb, instanceOf(IOther.class)); diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java index fe72f96325..633705f068 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,23 @@ package org.springframework.aop.framework.adapter; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.rmi.RemoteException; + import javax.transaction.TransactionRolledbackException; import org.aopalliance.intercept.MethodInvocation; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - import org.junit.Test; -import test.aop.MethodCounter; - import org.springframework.aop.ThrowsAdvice; +import org.springframework.tests.aop.advice.MethodCounter; + /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java index 964fac9efa..db2751f513 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ConcurrencyThrottleInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,17 @@ package org.springframework.aop.interceptor; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; - import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; - -import test.beans.DerivedTestBean; -import test.beans.ITestBean; -import test.beans.TestBean; -import test.util.SerializationTestUtils; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; /** * @author Juergen Hoeller diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java index 170f5b34bc..3b0bd31e53 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeBeanNameAdvisorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.NamedBean; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests-context.xml b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests-context.xml index bea92760ce..5f00163fb5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests-context.xml +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests-context.xml @@ -5,8 +5,8 @@ Tests for throws advice. --> - - + + @@ -14,8 +14,8 @@ INSTANCE - - + + @@ -25,5 +25,5 @@ exposeInvocation,countingBeforeAdvice,nopInterceptor - - + + diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java index 632c5bad07..5405d09831 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,15 @@ package org.springframework.aop.interceptor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.aopalliance.intercept.MethodInvocation; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; - -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Non-XML tests are in AbstractAopProxyTests diff --git a/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java index ccbe9502bf..84c4decb19 100644 --- a/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/scope/ScopedProxyAutowireTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.aop.scope; import static org.junit.Assert.assertSame; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java index b230ed7260..03cf0b719e 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/AbstractRegexpMethodPointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,16 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.Before; import org.junit.Test; - -import test.beans.TestBean; -import test.util.SerializationTestUtils; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java index 505697408c..01be11617e 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/AopUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; @@ -26,10 +28,10 @@ import org.springframework.aop.MethodMatcher; import org.springframework.aop.Pointcut; import org.springframework.aop.interceptor.ExposeInvocationInterceptor; import org.springframework.aop.target.EmptyTargetSource; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; -import test.aop.NopInterceptor; -import test.beans.TestBean; -import test.util.SerializationTestUtils; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java index 42992fb57c..51f18dde21 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ClassFiltersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import org.junit.Test; import org.springframework.aop.ClassFilter; import org.springframework.core.NestedRuntimeException; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java index 1c250e966d..35828d28e0 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ClassUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.aop.support; import junit.framework.TestCase; import org.springframework.aop.framework.ProxyFactory; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; /** diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java index 2ca2acd665..513885ed21 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ComposablePointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.springframework.aop.MethodMatcher; import org.springframework.aop.Pointcut; import org.springframework.core.NestedRuntimeException; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java index 6288f7674a..be21c52d2a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/ControlFlowPointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,16 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import org.junit.Test; import org.springframework.aop.Pointcut; import org.springframework.aop.framework.ProxyFactory; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.aop.NopInterceptor; -import test.beans.ITestBean; -import test.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java index 1b7c8d60b3..1872a457f9 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -27,16 +29,15 @@ import org.junit.Test; import org.springframework.aop.IntroductionAdvisor; import org.springframework.aop.IntroductionInterceptor; import org.springframework.aop.framework.ProxyFactory; - -import test.aop.SerializableNopInterceptor; -import test.beans.INestedTestBean; -import test.beans.ITestBean; -import test.beans.NestedTestBean; -import test.beans.Person; -import test.beans.SerializablePerson; -import test.beans.TestBean; -import test.util.SerializationTestUtils; -import test.util.TimeStamped; +import org.springframework.tests.TimeStamped; +import org.springframework.tests.aop.interceptor.SerializableNopInterceptor; +import org.springframework.tests.sample.beans.INestedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.NestedTestBean; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.SerializablePerson; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java b/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java index 5b3ceb039b..8f06791335 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/MethodMatchersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,18 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import org.junit.Test; import org.springframework.aop.MethodMatcher; - -import test.beans.IOther; -import test.beans.ITestBean; -import test.beans.TestBean; -import test.util.SerializationTestUtils; +import org.springframework.tests.sample.beans.IOther; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; /** * @author Juergen Hoeller diff --git a/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java index 8b89281e76..5edde823db 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/NameMatchMethodPointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,20 @@ package org.springframework.aop.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.aop.interceptor.SerializableNopInterceptor; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.SerializablePerson; +import org.springframework.util.SerializationTestUtils; -import test.aop.NopInterceptor; -import test.aop.SerializableNopInterceptor; -import test.beans.Person; -import test.beans.SerializablePerson; -import test.util.SerializationTestUtils; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java b/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java index 1ed7cd8430..b24dccc2c9 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/PointcutsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.junit.Test; import org.springframework.aop.ClassFilter; import org.springframework.aop.Pointcut; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests-context.xml b/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests-context.xml index 1e3ae07f26..cbd660d7fe 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests-context.xml +++ b/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests-context.xml @@ -4,12 +4,12 @@ - + custom 666 - + @@ -21,19 +21,19 @@ - test.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean - settersAdvisor + settersAdvisor - test.beans.Person + org.springframework.tests.sample.beans.Person - + serializableSettersAdvised - settersAdvisor + settersAdvisor @@ -48,11 +48,11 @@ - test.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean true - - settersAndAbsquatulateAdvisor + + settersAndAbsquatulateAdvisor - + diff --git a/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java b/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java index b55f2bb9f9..4a3d04cbd8 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/RegexpMethodPointcutAdvisorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,20 +17,20 @@ package org.springframework.aop.support; import static org.junit.Assert.assertEquals; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.aop.interceptor.SerializableNopInterceptor; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; -import test.aop.NopInterceptor; -import test.aop.SerializableNopInterceptor; -import test.beans.ITestBean; -import test.beans.Person; -import test.beans.TestBean; -import test.util.SerializationTestUtils; /** * @author Rod Johnson diff --git a/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests-context.xml b/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests-context.xml index 75be80560e..07e9e4d3d9 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests-context.xml +++ b/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests-context.xml @@ -3,7 +3,7 @@ - + diff --git a/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests.java b/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests.java index e70d2c7baa..af6b44c0ca 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,15 +17,14 @@ package org.springframework.aop.target; import static org.junit.Assert.assertTrue; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; - -import test.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; /** * @author Rob Harrop diff --git a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests-context.xml b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests-context.xml index 04cc623d30..33f30be78c 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests-context.xml +++ b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests-context.xml @@ -4,15 +4,15 @@ - + 10 - + 20 - - @@ -23,5 +23,4 @@ - - \ No newline at end of file + diff --git a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java index cb897b602f..a4bb0c2554 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/HotSwappableTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.aop.target; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.After; import org.junit.Before; @@ -30,12 +30,12 @@ import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; +import org.springframework.tests.aop.interceptor.SerializableNopInterceptor; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.SerializablePerson; +import org.springframework.tests.sample.beans.SideEffectBean; +import org.springframework.util.SerializationTestUtils; -import test.aop.SerializableNopInterceptor; -import test.beans.Person; -import test.beans.SerializablePerson; -import test.beans.SideEffectBean; -import test.util.SerializationTestUtils; /** diff --git a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-customTarget.xml b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-customTarget.xml index 9bfe5dfd96..f633c66d5b 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-customTarget.xml +++ b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-customTarget.xml @@ -3,7 +3,7 @@ - + 10 diff --git a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-singleton.xml b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-singleton.xml index 74b1fe0ec2..10ef6a35ae 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-singleton.xml +++ b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests-singleton.xml @@ -3,7 +3,7 @@ - + 10 diff --git a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java index 57cedd275b..b5bb4a1751 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/LazyInitTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.aop.target; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.Set; @@ -27,8 +27,7 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; - -import test.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; /** * @author Juergen Hoeller diff --git a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java index ea2eef2ae1..91e1d087f5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeBasedTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,17 @@ package org.springframework.aop.target; -import static org.junit.Assert.*; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import org.junit.Test; import org.springframework.aop.TargetSource; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; - -import test.beans.SerializablePerson; -import test.beans.TestBean; -import test.util.SerializationTestUtils; +import org.springframework.tests.sample.beans.SerializablePerson; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.SerializationTestUtils; /** * Unit tests relating to the abstract {@link AbstractPrototypeBasedTargetSource} diff --git a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests-context.xml b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests-context.xml index b271b1f556..961269efde 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests-context.xml +++ b/spring-aop/src/test/java/org/springframework/aop/target/PrototypeTargetSourceTests-context.xml @@ -4,22 +4,22 @@ - - 10 - - - + 10 - + + 10 + + + prototypeTest - - - + + + - debugInterceptor,test + debugInterceptor,test @@ -20,7 +20,7 @@ getStatsMixin - + @@ -33,23 +33,22 @@ - - + + Rod - - + + Kerry - - + + test - + - - \ No newline at end of file + diff --git a/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java b/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java index 1a6d5be3e3..b8976f1958 100644 --- a/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/target/ThreadLocalTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,16 +19,15 @@ package org.springframework.aop.target; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; - -import test.beans.ITestBean; -import test.beans.SideEffectBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.SideEffectBean; /** diff --git a/spring-context/src/test/java/test/advice/CountingAfterReturningAdvice.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java similarity index 95% rename from spring-context/src/test/java/test/advice/CountingAfterReturningAdvice.java rename to spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java index a8a3a01e3a..5b206516af 100644 --- a/spring-context/src/test/java/test/advice/CountingAfterReturningAdvice.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.advice; +package org.springframework.tests.aop.advice; import java.lang.reflect.Method; diff --git a/spring-aop/src/test/java/test/aop/CountingBeforeAdvice.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingBeforeAdvice.java similarity index 95% rename from spring-aop/src/test/java/test/aop/CountingBeforeAdvice.java rename to spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingBeforeAdvice.java index 91a49faa0f..2e34d50262 100644 --- a/spring-aop/src/test/java/test/aop/CountingBeforeAdvice.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingBeforeAdvice.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.aop; +package org.springframework.tests.aop.advice; import java.lang.reflect.Method; diff --git a/src/test/java/test/advice/MethodCounter.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/MethodCounter.java similarity index 97% rename from src/test/java/test/advice/MethodCounter.java rename to spring-aop/src/test/java/org/springframework/tests/aop/advice/MethodCounter.java index e0e45d6f14..931b0ec668 100644 --- a/src/test/java/test/advice/MethodCounter.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/MethodCounter.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.advice; +package org.springframework.tests.aop.advice; import java.io.Serializable; import java.lang.reflect.Method; diff --git a/spring-context/src/test/java/test/advice/MyThrowsHandler.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java similarity index 93% rename from spring-context/src/test/java/test/advice/MyThrowsHandler.java rename to spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java index abe79f9dc3..96edd1280c 100644 --- a/spring-context/src/test/java/test/advice/MyThrowsHandler.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java @@ -1,7 +1,7 @@ /** * */ -package test.advice; +package org.springframework.tests.aop.advice; import java.io.IOException; import java.lang.reflect.Method; diff --git a/spring-context/src/test/java/test/advice/TimestampIntroductionAdvisor.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/TimestampIntroductionAdvisor.java similarity index 89% rename from spring-context/src/test/java/test/advice/TimestampIntroductionAdvisor.java rename to spring-aop/src/test/java/org/springframework/tests/aop/advice/TimestampIntroductionAdvisor.java index bdcb2f2c9e..0fa9d4b4da 100644 --- a/spring-context/src/test/java/test/advice/TimestampIntroductionAdvisor.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/TimestampIntroductionAdvisor.java @@ -14,12 +14,12 @@ * limitations under the License. */ -package test.advice; +package org.springframework.tests.aop.advice; import org.springframework.aop.support.DelegatingIntroductionInterceptor; import org.springframework.aop.support.DefaultIntroductionAdvisor; +import org.springframework.tests.aop.interceptor.TimestampIntroductionInterceptor; -import test.interceptor.TimestampIntroductionInterceptor; /** * diff --git a/spring-context/src/test/java/test/interceptor/NopInterceptor.java b/spring-aop/src/test/java/org/springframework/tests/aop/interceptor/NopInterceptor.java similarity index 96% rename from spring-context/src/test/java/test/interceptor/NopInterceptor.java rename to spring-aop/src/test/java/org/springframework/tests/aop/interceptor/NopInterceptor.java index b1cdf832a4..d152719261 100644 --- a/spring-context/src/test/java/test/interceptor/NopInterceptor.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/interceptor/NopInterceptor.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package test.interceptor; +package org.springframework.tests.aop.interceptor; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; diff --git a/spring-context/src/test/java/test/interceptor/SerializableNopInterceptor.java b/spring-aop/src/test/java/org/springframework/tests/aop/interceptor/SerializableNopInterceptor.java similarity index 95% rename from spring-context/src/test/java/test/interceptor/SerializableNopInterceptor.java rename to spring-aop/src/test/java/org/springframework/tests/aop/interceptor/SerializableNopInterceptor.java index d8d179f7e4..8c72878c9d 100644 --- a/spring-context/src/test/java/test/interceptor/SerializableNopInterceptor.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/interceptor/SerializableNopInterceptor.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.interceptor; +package org.springframework.tests.aop.interceptor; import java.io.Serializable; diff --git a/spring-context/src/test/java/test/interceptor/TimestampIntroductionInterceptor.java b/spring-aop/src/test/java/org/springframework/tests/aop/interceptor/TimestampIntroductionInterceptor.java similarity index 89% rename from spring-context/src/test/java/test/interceptor/TimestampIntroductionInterceptor.java rename to spring-aop/src/test/java/org/springframework/tests/aop/interceptor/TimestampIntroductionInterceptor.java index eb9789edb3..de4dfecff6 100644 --- a/spring-context/src/test/java/test/interceptor/TimestampIntroductionInterceptor.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/interceptor/TimestampIntroductionInterceptor.java @@ -14,15 +14,14 @@ * limitations under the License. */ -package test.interceptor; +package org.springframework.tests.aop.interceptor; import org.springframework.aop.support.DelegatingIntroductionInterceptor; - -import test.util.TimeStamped; +import org.springframework.tests.TimeStamped; @SuppressWarnings("serial") public class TimestampIntroductionInterceptor extends DelegatingIntroductionInterceptor - implements TimeStamped { + implements TimeStamped { private long ts; diff --git a/spring-web/src/test/java/org/springframework/beans/Person.java b/spring-aop/src/test/java/org/springframework/tests/sample/beans/Person.java similarity index 82% rename from spring-web/src/test/java/org/springframework/beans/Person.java rename to spring-aop/src/test/java/org/springframework/tests/sample/beans/Person.java index 7c66f4b451..38e0903e2e 100644 --- a/spring-web/src/test/java/org/springframework/beans/Person.java +++ b/spring-aop/src/test/java/org/springframework/tests/sample/beans/Person.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; /** * @@ -23,14 +23,16 @@ package org.springframework.beans; public interface Person { String getName(); + void setName(String name); + int getAge(); + void setAge(int i); /** - * Test for non-property method matching. - * If the parameter is a Throwable, it will be thrown rather than - * returned. + * Test for non-property method matching. If the parameter is a Throwable, it will be + * thrown rather than returned. */ Object echo(Object o) throws Throwable; -} \ No newline at end of file +} diff --git a/spring-webmvc/src/test/java/org/springframework/beans/SerializablePerson.java b/spring-aop/src/test/java/org/springframework/tests/sample/beans/SerializablePerson.java similarity index 96% rename from spring-webmvc/src/test/java/org/springframework/beans/SerializablePerson.java rename to spring-aop/src/test/java/org/springframework/tests/sample/beans/SerializablePerson.java index dbe365f493..2730d50c8e 100644 --- a/spring-webmvc/src/test/java/org/springframework/beans/SerializablePerson.java +++ b/spring-aop/src/test/java/org/springframework/tests/sample/beans/SerializablePerson.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; import java.io.Serializable; diff --git a/spring-aop/src/test/java/test/beans/subpkg/DeepBean.java b/spring-aop/src/test/java/org/springframework/tests/sample/beans/subpkg/DeepBean.java similarity index 94% rename from spring-aop/src/test/java/test/beans/subpkg/DeepBean.java rename to spring-aop/src/test/java/org/springframework/tests/sample/beans/subpkg/DeepBean.java index b18646f4d0..45546b4cfd 100644 --- a/spring-aop/src/test/java/test/beans/subpkg/DeepBean.java +++ b/spring-aop/src/test/java/org/springframework/tests/sample/beans/subpkg/DeepBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans.subpkg; +package org.springframework.tests.sample.beans.subpkg; import org.springframework.aop.aspectj.AspectJExpressionPointcutTests; diff --git a/spring-aop/src/test/java/test/aop/MethodCounter.java b/spring-aop/src/test/java/test/aop/MethodCounter.java deleted file mode 100644 index ae673bd168..0000000000 --- a/spring-aop/src/test/java/test/aop/MethodCounter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.aop; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.HashMap; - -/** - * Abstract superclass for counting advices etc. - * - * @author Rod Johnson - * @author Chris Beams - */ -@SuppressWarnings("serial") -public class MethodCounter implements Serializable { - - /** Method name --> count, does not understand overloading */ - private HashMap map = new HashMap(); - - private int allCount; - - protected void count(Method m) { - count(m.getName()); - } - - protected void count(String methodName) { - Integer i = map.get(methodName); - i = (i != null) ? new Integer(i.intValue() + 1) : new Integer(1); - map.put(methodName, i); - ++allCount; - } - - public int getCalls(String methodName) { - Integer i = map.get(methodName); - return (i != null ? i.intValue() : 0); - } - - public int getCalls() { - return allCount; - } - - /** - * A bit simplistic: just wants the same class. - * Doesn't worry about counts. - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object other) { - return (other != null && other.getClass() == this.getClass()); - } - - public int hashCode() { - return getClass().hashCode(); - } - -} diff --git a/spring-aop/src/test/java/test/aop/NopInterceptor.java b/spring-aop/src/test/java/test/aop/NopInterceptor.java deleted file mode 100644 index 20b9ece08f..0000000000 --- a/spring-aop/src/test/java/test/aop/NopInterceptor.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.aop; - -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; - -/** - * Trivial interceptor that can be introduced in a chain to display it. - * - * @author Rod Johnson - */ -public class NopInterceptor implements MethodInterceptor { - - private int count; - - /** - * @see org.aopalliance.intercept.MethodInterceptor#invoke(MethodInvocation) - */ - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - increment(); - return invocation.proceed(); - } - - public int getCount() { - return this.count; - } - - protected void increment() { - ++count; - } - - public boolean equals(Object other) { - if (!(other instanceof NopInterceptor)) { - return false; - } - if (this == other) { - return true; - } - return this.count == ((NopInterceptor) other).count; - } - -} diff --git a/spring-aop/src/test/java/test/aop/SerializableNopInterceptor.java b/spring-aop/src/test/java/test/aop/SerializableNopInterceptor.java deleted file mode 100644 index 064df39ab5..0000000000 --- a/spring-aop/src/test/java/test/aop/SerializableNopInterceptor.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.aop; - -import java.io.Serializable; - - - -/** - * Subclass of NopInterceptor that is serializable and - * can be used to test proxy serialization. - * - * @author Rod Johnson - * @author Chris Beams - */ -@SuppressWarnings("serial") -public class SerializableNopInterceptor extends NopInterceptor implements Serializable { - - /** - * We must override this field and the related methods as - * otherwise count won't be serialized from the non-serializable - * NopInterceptor superclass. - */ - private int count; - - @Override - public int getCount() { - return this.count; - } - - @Override - protected void increment() { - ++count; - } - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/Colour.java b/spring-aop/src/test/java/test/beans/Colour.java deleted file mode 100644 index 8793fd3f94..0000000000 --- a/spring-aop/src/test/java/test/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2007 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 test.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/DerivedTestBean.java b/spring-aop/src/test/java/test/beans/DerivedTestBean.java deleted file mode 100644 index 225ae1a300..0000000000 --- a/spring-aop/src/test/java/test/beans/DerivedTestBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-aop/src/test/java/test/beans/INestedTestBean.java b/spring-aop/src/test/java/test/beans/INestedTestBean.java deleted file mode 100644 index 56c9d829ee..0000000000 --- a/spring-aop/src/test/java/test/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/IOther.java b/spring-aop/src/test/java/test/beans/IOther.java deleted file mode 100644 index f3c6263261..0000000000 --- a/spring-aop/src/test/java/test/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/ITestBean.java b/spring-aop/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 74f371b054..0000000000 --- a/spring-aop/src/test/java/test/beans/ITestBean.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2002-2007 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 test.beans; - -import java.io.IOException; - -/** - * Interface used for {@link test.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/NestedTestBean.java b/spring-aop/src/test/java/test/beans/NestedTestBean.java deleted file mode 100644 index edc145ad7d..0000000000 --- a/spring-aop/src/test/java/test/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/Person.java b/spring-aop/src/test/java/test/beans/Person.java deleted file mode 100644 index 974d7d9b77..0000000000 --- a/spring-aop/src/test/java/test/beans/Person.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -/** - * - * @author Rod Johnson - */ -public interface Person { - - String getName(); - void setName(String name); - int getAge(); - void setAge(int i); - - /** - * Test for non-property method matching. - * If the parameter is a Throwable, it will be thrown rather than - * returned. - */ - Object echo(Object o) throws Throwable; -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/beans/SerializablePerson.java b/spring-aop/src/test/java/test/beans/SerializablePerson.java deleted file mode 100644 index 3aa60f1fdc..0000000000 --- a/spring-aop/src/test/java/test/beans/SerializablePerson.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.io.Serializable; - -import org.springframework.util.ObjectUtils; - -/** - * Serializable implementation of the Person interface. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class SerializablePerson implements Person, Serializable { - - private String name; - private int age; - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public Object echo(Object o) throws Throwable { - if (o instanceof Throwable) { - throw (Throwable) o; - } - return o; - } - - public boolean equals(Object other) { - if (!(other instanceof SerializablePerson)) { - return false; - } - SerializablePerson p = (SerializablePerson) other; - return p.age == age && ObjectUtils.nullSafeEquals(name, p.name); - } - -} diff --git a/spring-aop/src/test/java/test/beans/TestBean.java b/spring-aop/src/test/java/test/beans/TestBean.java deleted file mode 100644 index 3f50f93836..0000000000 --- a/spring-aop/src/test/java/test/beans/TestBean.java +++ /dev/null @@ -1,431 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-aop/src/test/java/test/parsing/CollectingReaderEventListener.java b/spring-aop/src/test/java/test/parsing/CollectingReaderEventListener.java deleted file mode 100644 index 5aa69c1fa8..0000000000 --- a/spring-aop/src/test/java/test/parsing/CollectingReaderEventListener.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.parsing; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.springframework.beans.factory.parsing.AliasDefinition; -import org.springframework.beans.factory.parsing.ComponentDefinition; -import org.springframework.beans.factory.parsing.DefaultsDefinition; -import org.springframework.beans.factory.parsing.ImportDefinition; -import org.springframework.beans.factory.parsing.ReaderEventListener; - -/** - * @author Rob Harrop - * @author Juergen Hoeller - * @author Chris Beams - */ -public class CollectingReaderEventListener implements ReaderEventListener { - - private final List defaults = new LinkedList(); - - private final Map componentDefinitions = new LinkedHashMap(8); - - private final Map aliasMap = new LinkedHashMap(8); - - private final List imports = new LinkedList(); - - - @Override - public void defaultsRegistered(DefaultsDefinition defaultsDefinition) { - this.defaults.add(defaultsDefinition); - } - - public List getDefaults() { - return Collections.unmodifiableList(this.defaults); - } - - @Override - public void componentRegistered(ComponentDefinition componentDefinition) { - this.componentDefinitions.put(componentDefinition.getName(), componentDefinition); - } - - public ComponentDefinition getComponentDefinition(String name) { - return (ComponentDefinition) this.componentDefinitions.get(name); - } - - public ComponentDefinition[] getComponentDefinitions() { - Collection collection = this.componentDefinitions.values(); - return collection.toArray(new ComponentDefinition[collection.size()]); - } - - @Override - @SuppressWarnings("unchecked") - public void aliasRegistered(AliasDefinition aliasDefinition) { - List aliases = (List) this.aliasMap.get(aliasDefinition.getBeanName()); - if(aliases == null) { - aliases = new ArrayList(); - this.aliasMap.put(aliasDefinition.getBeanName(), aliases); - } - aliases.add(aliasDefinition); - } - - public List getAliases(String beanName) { - List aliases = (List) this.aliasMap.get(beanName); - return aliases == null ? null : Collections.unmodifiableList(aliases); - } - - @Override - public void importProcessed(ImportDefinition importDefinition) { - this.imports.add(importDefinition); - } - - public List getImports() { - return Collections.unmodifiableList(this.imports); - } - -} diff --git a/spring-aop/src/test/java/test/util/SerializationTestUtils.java b/spring-aop/src/test/java/test/util/SerializationTestUtils.java deleted file mode 100644 index e9bc9fee04..0000000000 --- a/spring-aop/src/test/java/test/util/SerializationTestUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.util; - -import java.awt.*; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import static org.junit.Assert.*; -import org.junit.Test; -import test.beans.TestBean; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * Contains {@link org.junit.Test} methods to test itself. - * - * @author Rod Johnson - * @author Chris Beams - */ -public final class SerializationTestUtils { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - return o2; - } - - - @Test(expected=NotSerializableException.class) - public void testWithNonSerializableObject() throws IOException { - TestBean o = new TestBean(); - assertFalse(o instanceof Serializable); - assertFalse(isSerializable(o)); - - testSerialization(o); - } - - @Test - public void testWithSerializableObject() throws Exception { - int x = 5; - int y = 10; - Point p = new Point(x, y); - assertTrue(p instanceof Serializable); - - testSerialization(p); - - assertTrue(isSerializable(p)); - - Point p2 = (Point) serializeAndDeserialize(p); - assertNotSame(p, p2); - assertEquals(x, (int) p2.getX()); - assertEquals(y, (int) p2.getY()); - } - -} diff --git a/spring-aop/src/test/java/test/util/TimeStamped.java b/spring-aop/src/test/java/test/util/TimeStamped.java deleted file mode 100644 index 4fedb8998b..0000000000 --- a/spring-aop/src/test/java/test/util/TimeStamped.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.util; - -/** - * This interface can be implemented by cacheable objects or cache entries, - * to enable the freshness of objects to be checked. - * - * @author Rod Johnson - */ -public interface TimeStamped { - - /** - * Return the timestamp for this object. - * @return long the timestamp for this object, - * as returned by System.currentTimeMillis() - */ - long getTimeStamp(); - -} diff --git a/spring-aspects/src/test/java/org/springframework/beans/Colour.java b/spring-aspects/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-aspects/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-aspects/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index a10846ba95..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-aspects/src/test/java/org/springframework/beans/IOther.java b/spring-aspects/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-aspects/src/test/java/org/springframework/beans/ITestBean.java b/spring-aspects/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index 478999c05d..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-aspects/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-aspects/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index d7af36ed64..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-aspects/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-aspects/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 88b450b917..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-aspects/src/test/java/org/springframework/beans/TestBean.java b/spring-aspects/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index ac8e5ea485..0000000000 --- a/spring-aspects/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - public int getAge() { - return age; - } - - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String[] getStringArray() { - return stringArray; - } - - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see org.springframework.beans.ITestBean#exceptional(Throwable) - */ - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see org.springframework.beans.ITestBean#returnsThis() - */ - public Object returnsThis() { - return this; - } - - /** - * @see org.springframework.beans.IOther#absquatulate() - */ - public void absquatulate() { - } - - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java index 73f37a8f9e..6ff04cf7b8 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import junit.framework.TestCase; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.UnsatisfiedDependencyException; import org.springframework.beans.factory.annotation.Autowire; diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/beanConfigurerTests-beans.xml b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/beanConfigurerTests-beans.xml index 89aa3964ea..bd6439bb54 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/beanConfigurerTests-beans.xml +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/beanConfigurerTests-beans.xml @@ -37,7 +37,7 @@ autowire-candidate="false"/> - + diff --git a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractAnnotationTest.java b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractAnnotationTest.java deleted file mode 100644 index 3771a21b9f..0000000000 --- a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AbstractAnnotationTest.java +++ /dev/null @@ -1,596 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.cache.aspectj; - -import static org.junit.Assert.*; - -import java.util.Collection; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.cache.Cache; -import org.springframework.cache.CacheManager; -import org.springframework.cache.config.AnnotatedClassCacheableService; -import org.springframework.cache.config.CacheableService; -import org.springframework.context.ApplicationContext; - -/** - * Abstract annotation test (containing several reusable methods). - * - * @author Costin Leau - * @author Chris Beams - */ -public abstract class AbstractAnnotationTest { - - protected ApplicationContext ctx; - - protected CacheableService cs; - - protected CacheableService ccs; - - protected CacheManager cm; - - /** @return a refreshed application context */ - protected abstract ApplicationContext getApplicationContext(); - - @Before - public void setup() { - ctx = getApplicationContext(); - cs = ctx.getBean("service", CacheableService.class); - ccs = ctx.getBean("classService", CacheableService.class); - cm = ctx.getBean(CacheManager.class); - Collection cn = cm.getCacheNames(); - assertTrue(cn.contains("default")); - } - - public void testCacheable(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - Object r3 = service.cache(o1); - - assertSame(r1, r2); - assertSame(r1, r3); - } - - public void testEvict(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - - assertSame(r1, r2); - service.invalidate(o1); - Object r3 = service.cache(o1); - Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); - } - - public void testEvictEarly(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - - assertSame(r1, r2); - try { - service.evictEarly(o1); - } catch (RuntimeException ex) { - // expected - } - - Object r3 = service.cache(o1); - Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); - } - - public void testEvictException(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - - assertSame(r1, r2); - try { - service.evictWithException(o1); - } catch (RuntimeException ex) { - // expected - } - // exception occurred, eviction skipped, data should still be in the cache - Object r3 = service.cache(o1); - assertSame(r1, r3); - } - - public void testEvictWKey(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - - assertSame(r1, r2); - service.evict(o1, null); - Object r3 = service.cache(o1); - Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); - } - - public void testEvictWKeyEarly(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - - assertSame(r1, r2); - - try { - service.invalidateEarly(o1, null); - } catch (Exception ex) { - // expected - } - Object r3 = service.cache(o1); - Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); - } - - public void testEvictAll(CacheableService service) throws Exception { - Object o1 = new Object(); - - Object r1 = service.cache(o1); - Object r2 = service.cache(o1); - - Object o2 = new Object(); - Object r10 = service.cache(o2); - - assertSame(r1, r2); - assertNotSame(r1, r10); - service.evictAll(new Object()); - Cache cache = cm.getCache("default"); - assertNull(cache.get(o1)); - assertNull(cache.get(o2)); - - Object r3 = service.cache(o1); - Object r4 = service.cache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); - } - - public void testConditionalExpression(CacheableService service) throws Exception { - Object r1 = service.conditional(4); - Object r2 = service.conditional(4); - - assertNotSame(r1, r2); - - Object r3 = service.conditional(3); - Object r4 = service.conditional(3); - - assertSame(r3, r4); - } - - public void testKeyExpression(CacheableService service) throws Exception { - Object r1 = service.key(5, 1); - Object r2 = service.key(5, 2); - - assertSame(r1, r2); - - Object r3 = service.key(1, 5); - Object r4 = service.key(2, 5); - - assertNotSame(r3, r4); - } - - public void testNullValue(CacheableService service) throws Exception { - Object key = new Object(); - assertNull(service.nullValue(key)); - int nr = service.nullInvocations().intValue(); - assertNull(service.nullValue(key)); - assertEquals(nr, service.nullInvocations().intValue()); - assertNull(service.nullValue(new Object())); - assertEquals(nr + 1, service.nullInvocations().intValue()); - } - - public void testMethodName(CacheableService service, String keyName) throws Exception { - Object key = new Object(); - Object r1 = service.name(key); - assertSame(r1, service.name(key)); - Cache cache = cm.getCache("default"); - // assert the method name is used - assertNotNull(cache.get(keyName)); - } - - public void testCheckedThrowable(CacheableService service) throws Exception { - String arg = UUID.randomUUID().toString(); - try { - service.throwChecked(arg); - fail("Excepted exception"); - } catch (Exception ex) { - assertEquals(arg, ex.getMessage()); - } - } - - public void testUncheckedThrowable(CacheableService service) throws Exception { - try { - service.throwUnchecked(Long.valueOf(1)); - fail("Excepted exception"); - } catch (RuntimeException ex) { - assertTrue("Excepted different exception type and got " + ex.getClass(), - ex instanceof UnsupportedOperationException); - // expected - } - } - - public void testNullArg(CacheableService service) { - Object r1 = service.cache(null); - assertSame(r1, service.cache(null)); - } - - public void testCacheUpdate(CacheableService service) { - Object o = new Object(); - Cache cache = cm.getCache("default"); - assertNull(cache.get(o)); - Object r1 = service.update(o); - assertSame(r1, cache.get(o).get()); - - o = new Object(); - assertNull(cache.get(o)); - Object r2 = service.update(o); - assertSame(r2, cache.get(o).get()); - } - - public void testConditionalCacheUpdate(CacheableService service) { - Integer one = Integer.valueOf(1); - Integer three = Integer.valueOf(3); - - Cache cache = cm.getCache("default"); - assertEquals(one, Integer.valueOf(service.conditionalUpdate(one).toString())); - assertNull(cache.get(one)); - - assertEquals(three, Integer.valueOf(service.conditionalUpdate(three).toString())); - assertEquals(three, Integer.valueOf(cache.get(three).get().toString())); - } - - public void testMultiCache(CacheableService service) { - Object o1 = new Object(); - Object o2 = new Object(); - - Cache primary = cm.getCache("primary"); - Cache secondary = cm.getCache("secondary"); - - assertNull(primary.get(o1)); - assertNull(secondary.get(o1)); - Object r1 = service.multiCache(o1); - assertSame(r1, primary.get(o1).get()); - assertSame(r1, secondary.get(o1).get()); - - Object r2 = service.multiCache(o1); - Object r3 = service.multiCache(o1); - - assertSame(r1, r2); - assertSame(r1, r3); - - assertNull(primary.get(o2)); - assertNull(secondary.get(o2)); - Object r4 = service.multiCache(o2); - assertSame(r4, primary.get(o2).get()); - assertSame(r4, secondary.get(o2).get()); - } - - public void testMultiEvict(CacheableService service) { - Object o1 = new Object(); - - Object r1 = service.multiCache(o1); - Object r2 = service.multiCache(o1); - - Cache primary = cm.getCache("primary"); - Cache secondary = cm.getCache("secondary"); - - assertSame(r1, r2); - assertSame(r1, primary.get(o1).get()); - assertSame(r1, secondary.get(o1).get()); - - service.multiEvict(o1); - assertNull(primary.get(o1)); - assertNull(secondary.get(o1)); - - Object r3 = service.multiCache(o1); - Object r4 = service.multiCache(o1); - assertNotSame(r1, r3); - assertSame(r3, r4); - - assertSame(r3, primary.get(o1).get()); - assertSame(r4, secondary.get(o1).get()); - } - - public void testMultiPut(CacheableService service) { - Object o = Integer.valueOf(1); - - Cache primary = cm.getCache("primary"); - Cache secondary = cm.getCache("secondary"); - - assertNull(primary.get(o)); - assertNull(secondary.get(o)); - Object r1 = service.multiUpdate(o); - assertSame(r1, primary.get(o).get()); - assertSame(r1, secondary.get(o).get()); - - o = Integer.valueOf(2); - assertNull(primary.get(o)); - assertNull(secondary.get(o)); - Object r2 = service.multiUpdate(o); - assertSame(r2, primary.get(o).get()); - assertSame(r2, secondary.get(o).get()); - } - - public void testMultiCacheAndEvict(CacheableService service) { - String methodName = "multiCacheAndEvict"; - - Cache primary = cm.getCache("primary"); - Cache secondary = cm.getCache("secondary"); - Object key = Integer.valueOf(1); - - secondary.put(key, key); - - assertNull(secondary.get(methodName)); - assertSame(key, secondary.get(key).get()); - - Object r1 = service.multiCacheAndEvict(key); - assertSame(r1, service.multiCacheAndEvict(key)); - - // assert the method name is used - assertSame(r1, primary.get(methodName).get()); - assertNull(secondary.get(methodName)); - assertNull(secondary.get(key)); - } - - public void testMultiConditionalCacheAndEvict(CacheableService service) { - Cache primary = cm.getCache("primary"); - Cache secondary = cm.getCache("secondary"); - Object key = Integer.valueOf(1); - - secondary.put(key, key); - - assertNull(primary.get(key)); - assertSame(key, secondary.get(key).get()); - - Object r1 = service.multiConditionalCacheAndEvict(key); - Object r3 = service.multiConditionalCacheAndEvict(key); - - assertTrue(!r1.equals(r3)); - assertNull(primary.get(key)); - - Object key2 = Integer.valueOf(3); - Object r2 = service.multiConditionalCacheAndEvict(key2); - assertSame(r2, service.multiConditionalCacheAndEvict(key2)); - - // assert the method name is used - assertSame(r2, primary.get(key2).get()); - assertNull(secondary.get(key2)); - } - - @Test - public void testCacheable() throws Exception { - testCacheable(cs); - } - - @Test - public void testInvalidate() throws Exception { - testEvict(cs); - } - - @Test - public void testEarlyInvalidate() throws Exception { - testEvictEarly(cs); - } - - @Test - public void testEvictWithException() throws Exception { - testEvictException(cs); - } - - @Test - public void testEvictAll() throws Exception { - testEvictAll(cs); - } - - @Test - public void testInvalidateWithKey() throws Exception { - testEvictWKey(cs); - } - - @Test - public void testEarlyInvalidateWithKey() throws Exception { - testEvictWKeyEarly(cs); - } - - @Test - public void testConditionalExpression() throws Exception { - testConditionalExpression(cs); - } - - @Test - public void testKeyExpression() throws Exception { - testKeyExpression(cs); - } - - @Test - public void testClassCacheCacheable() throws Exception { - testCacheable(ccs); - } - - @Test - public void testClassCacheInvalidate() throws Exception { - testEvict(ccs); - } - - @Test - public void testClassEarlyInvalidate() throws Exception { - testEvictEarly(ccs); - } - - @Test - public void testClassEvictAll() throws Exception { - testEvictAll(ccs); - } - - @Test - public void testClassEvictWithException() throws Exception { - testEvictException(ccs); - } - - @Test - public void testClassCacheInvalidateWKey() throws Exception { - testEvictWKey(ccs); - } - - @Test - public void testClassEarlyInvalidateWithKey() throws Exception { - testEvictWKeyEarly(ccs); - } - - @Test - public void testNullValue() throws Exception { - testNullValue(cs); - } - - @Test - public void testClassNullValue() throws Exception { - Object key = new Object(); - assertNull(ccs.nullValue(key)); - int nr = ccs.nullInvocations().intValue(); - assertNull(ccs.nullValue(key)); - assertEquals(nr, ccs.nullInvocations().intValue()); - assertNull(ccs.nullValue(new Object())); - // the check method is also cached - assertEquals(nr, ccs.nullInvocations().intValue()); - assertEquals(nr + 1, AnnotatedClassCacheableService.nullInvocations.intValue()); - } - - @Test - public void testMethodName() throws Exception { - testMethodName(cs, "name"); - } - - @Test - public void testClassMethodName() throws Exception { - testMethodName(ccs, "namedefault"); - } - - @Test - public void testNullArg() throws Exception { - testNullArg(cs); - } - - @Test - public void testClassNullArg() throws Exception { - testNullArg(ccs); - } - - @Test - public void testCheckedException() throws Exception { - testCheckedThrowable(cs); - } - - @Test - public void testClassCheckedException() throws Exception { - testCheckedThrowable(ccs); - } - - @Test - public void testUncheckedException() throws Exception { - testUncheckedThrowable(cs); - } - - @Test - public void testClassUncheckedException() throws Exception { - testUncheckedThrowable(ccs); - } - - @Test - public void testUpdate() { - testCacheUpdate(cs); - } - - @Test - public void testClassUpdate() { - testCacheUpdate(ccs); - } - - @Test - public void testConditionalUpdate() { - testConditionalCacheUpdate(cs); - } - - @Test - public void testClassConditionalUpdate() { - testConditionalCacheUpdate(ccs); - } - - @Test - public void testMultiCache() { - testMultiCache(cs); - } - - @Test - public void testClassMultiCache() { - testMultiCache(ccs); - } - - @Test - public void testMultiEvict() { - testMultiEvict(cs); - } - - @Test - public void testClassMultiEvict() { - testMultiEvict(ccs); - } - - @Test - public void testMultiPut() { - testMultiPut(cs); - } - - @Test - public void testClassMultiPut() { - testMultiPut(ccs); - } - - @Test - public void testMultiCacheAndEvict() { - testMultiCacheAndEvict(cs); - } - - @Test - public void testClassMultiCacheAndEvict() { - testMultiCacheAndEvict(ccs); - } - - @Test - public void testMultiConditionalCacheAndEvict() { - testMultiConditionalCacheAndEvict(cs); - } - - @Test - public void testClassMultiConditionalCacheAndEvict() { - testMultiConditionalCacheAndEvict(ccs); - } -} \ No newline at end of file diff --git a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTest.java b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java similarity index 56% rename from spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTest.java rename to spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java index df23767475..43af45e80d 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTest.java +++ b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java @@ -16,8 +16,15 @@ package org.springframework.cache.aspectj; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; + import org.junit.Assert; import org.junit.Test; +import org.springframework.cache.Cache; +import org.springframework.cache.config.AbstractAnnotationTests; +import org.springframework.cache.config.CacheableService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; @@ -25,7 +32,7 @@ import org.springframework.context.support.GenericXmlApplicationContext; /** * @author Costin Leau */ -public class AspectJAnnotationTest extends AbstractAnnotationTest { +public class AspectJAnnotationTests extends AbstractAnnotationTests { @Override @@ -38,4 +45,30 @@ public class AspectJAnnotationTest extends AbstractAnnotationTest { AnnotationCacheAspect aspect = ctx.getBean("org.springframework.cache.config.internalCacheAspect", AnnotationCacheAspect.class); Assert.assertSame(ctx.getBean("keyGenerator"), aspect.getKeyGenerator()); } + + public void testMultiEvict(CacheableService service) { + Object o1 = new Object(); + + Object r1 = service.multiCache(o1); + Object r2 = service.multiCache(o1); + + Cache primary = cm.getCache("primary"); + Cache secondary = cm.getCache("secondary"); + + assertSame(r1, r2); + assertSame(r1, primary.get(o1).get()); + assertSame(r1, secondary.get(o1).get()); + + service.multiEvict(o1); + assertNull(primary.get(o1)); + assertNull(secondary.get(o1)); + + Object r3 = service.multiCache(o1); + Object r4 = service.multiCache(o1); + assertNotSame(r1, r3); + assertSame(r3, r4); + + assertSame(r3, primary.get(o1).get()); + assertSame(r4, secondary.get(o1).get()); + } } diff --git a/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java index 95edbcd9d6..6d83d91c02 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java +++ b/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,83 +33,100 @@ public class DefaultCacheableService implements CacheableService { private final AtomicLong counter = new AtomicLong(); private final AtomicLong nullInvocations = new AtomicLong(); + @Override @Cacheable("default") public Long cache(Object arg1) { return counter.getAndIncrement(); } + @Override @CacheEvict("default") public void invalidate(Object arg1) { } + @Override @CacheEvict("default") public void evictWithException(Object arg1) { throw new RuntimeException("exception thrown - evict should NOT occur"); } + @Override @CacheEvict(value = "default", allEntries = true) public void evictAll(Object arg1) { } + @Override @CacheEvict(value = "default", beforeInvocation = true) public void evictEarly(Object arg1) { throw new RuntimeException("exception thrown - evict should still occur"); } + @Override @CacheEvict(value = "default", key = "#p0") public void evict(Object arg1, Object arg2) { } + @Override @CacheEvict(value = "default", key = "#p0", beforeInvocation = true) public void invalidateEarly(Object arg1, Object arg2) { throw new RuntimeException("exception thrown - evict should still occur"); } + @Override @Cacheable(value = "default", condition = "#classField == 3") public Long conditional(int classField) { return counter.getAndIncrement(); } + @Override @Cacheable(value = "default", key = "#p0") public Long key(Object arg1, Object arg2) { return counter.getAndIncrement(); } + @Override @Cacheable(value = "default", key = "#root.methodName") public Long name(Object arg1) { return counter.getAndIncrement(); } + @Override @Cacheable(value = "default", key = "#root.methodName + #root.method.name + #root.targetClass + #root.target") public Long rootVars(Object arg1) { return counter.getAndIncrement(); } + @Override @CachePut("default") public Long update(Object arg1) { return counter.getAndIncrement(); } + @Override @CachePut(value = "default", condition = "#arg.equals(3)") public Long conditionalUpdate(Object arg) { return Long.valueOf(arg.toString()); } + @Override @Cacheable("default") public Long nullValue(Object arg1) { nullInvocations.incrementAndGet(); return null; } + @Override public Number nullInvocations() { return nullInvocations.get(); } + @Override @Cacheable("default") public Long throwChecked(Object arg1) throws Exception { throw new Exception(arg1.toString()); } + @Override @Cacheable("default") public Long throwUnchecked(Object arg1) { throw new UnsupportedOperationException(arg1.toString()); @@ -117,28 +134,34 @@ public class DefaultCacheableService implements CacheableService { // multi annotations + @Override @Caching(cacheable = { @Cacheable("primary"), @Cacheable("secondary") }) public Long multiCache(Object arg1) { return counter.getAndIncrement(); } + @Override +//FIXME @Caching(evict = { @CacheEvict("primary"), @CacheEvict(value = "secondary", key = "#p0"), @CacheEvict(value = "primary", key = "#p0 + 'A'") }) @Caching(evict = { @CacheEvict("primary"), @CacheEvict(value = "secondary", key = "#p0") }) public Long multiEvict(Object arg1) { return counter.getAndIncrement(); } + @Override @Caching(cacheable = { @Cacheable(value = "primary", key = "#root.methodName") }, evict = { @CacheEvict("secondary") }) public Long multiCacheAndEvict(Object arg1) { return counter.getAndIncrement(); } + @Override @Caching(cacheable = { @Cacheable(value = "primary", condition = "#p0 == 3") }, evict = { @CacheEvict("secondary") }) public Long multiConditionalCacheAndEvict(Object arg1) { return counter.getAndIncrement(); } + @Override @Caching(put = { @CachePut("primary"), @CachePut("secondary") }) public Long multiUpdate(Object arg1) { return Long.valueOf(arg1.toString()); } -} \ No newline at end of file +} diff --git a/spring-aspects/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java b/spring-aspects/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java deleted file mode 100644 index 969cf90a8f..0000000000 --- a/spring-aspects/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.transaction; - -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -import org.springframework.transaction.support.DefaultTransactionStatus; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -@SuppressWarnings("serial") -public class CallCountingTransactionManager extends AbstractPlatformTransactionManager { - - public TransactionDefinition lastDefinition; - public int begun; - public int commits; - public int rollbacks; - public int inflight; - - protected Object doGetTransaction() { - return new Object(); - } - - protected void doBegin(Object transaction, TransactionDefinition definition) { - this.lastDefinition = definition; - ++begun; - ++inflight; - } - - protected void doCommit(DefaultTransactionStatus status) { - ++commits; - --inflight; - } - - protected void doRollback(DefaultTransactionStatus status) { - ++rollbacks; - --inflight; - } - - public void clear() { - begun = commits = rollbacks = inflight = 0; - } - -} diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests-context.xml b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests-context.xml index 6af0f02db3..0d08cdcb56 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests-context.xml +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests-context.xml @@ -3,7 +3,7 @@ - + diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java index be562b2585..70892e3949 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import java.lang.reflect.Method; import junit.framework.AssertionFailedError; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.transaction.interceptor.TransactionAttribute; diff --git a/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java b/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java index a7a38f2c48..97e77c5740 100644 --- a/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java +++ b/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,8 +37,7 @@ public class ComponentBeanDefinitionParserTest { @BeforeClass public static void setUpBeforeClass() throws Exception { bf = new DefaultListableBeanFactory(); - new XmlBeanDefinitionReader(bf).loadBeanDefinitions( - new ClassPathResource("com/foo/component-config.xml")); + new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("com/foo/component-config.xml")); } @AfterClass diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java index f49f63182c..9d53409e73 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,10 +29,10 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceEditor; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.DerivedTestBean; -import test.beans.ITestBean; -import test.beans.TestBean; /** * Unit tests for {@link BeanUtils}. diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java index 3946cccb25..8c7d8da1e8 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperEnumTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,8 @@ package org.springframework.beans; import org.junit.Test; -import test.beans.CustomEnum; -import test.beans.GenericBean; +import org.springframework.tests.sample.beans.CustomEnum; +import org.springframework.tests.sample.beans.GenericBean; import static org.junit.Assert.*; diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java index a1752458c4..3d310bdc68 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,15 +30,15 @@ import java.util.Set; import static org.junit.Assert.*; import org.junit.Test; -import test.beans.GenericBean; -import test.beans.GenericIntegerBean; -import test.beans.GenericSetOfIntegerBean; -import test.beans.TestBean; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; +import org.springframework.tests.sample.beans.GenericBean; +import org.springframework.tests.sample.beans.GenericIntegerBean; +import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java index 29e282c0a2..9d4e022a64 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -51,6 +51,11 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.beans.support.DerivedFromProtectedBaseBean; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import org.springframework.tests.sample.beans.BooleanTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.NumberTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.convert.ConversionFailedException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.support.DefaultConversionService; @@ -58,11 +63,6 @@ import org.springframework.core.convert.support.GenericConversionService; import org.springframework.util.StopWatch; import org.springframework.util.StringUtils; -import test.beans.BooleanTestBean; -import test.beans.ITestBean; -import test.beans.IndexedTestBean; -import test.beans.NumberTestBean; -import test.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java index 4675d22dbf..a4fe92acc9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ import java.beans.PropertyDescriptor; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; -import test.beans.TestBean; import org.springframework.core.OverridingClassLoader; +import org.springframework.tests.sample.beans.TestBean; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; @@ -44,7 +44,7 @@ public final class CachedIntrospectionResultsTests { assertTrue(CachedIntrospectionResults.classCache.containsKey(TestBean.class)); ClassLoader child = new OverridingClassLoader(getClass().getClassLoader()); - Class tbClass = child.loadClass("test.beans.TestBean"); + Class tbClass = child.loadClass("org.springframework.tests.sample.beans.TestBean"); assertFalse(CachedIntrospectionResults.classCache.containsKey(tbClass)); CachedIntrospectionResults.acceptClassLoader(child); bw = new BeanWrapperImpl(tbClass); diff --git a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java index 44062a9107..aaf6e56092 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,9 @@ import java.lang.reflect.Method; import org.junit.Test; import org.springframework.core.JdkVersion; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; -import test.beans.TestBean; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.lessThan; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-leaf.xml b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-leaf.xml index bf756e1bbc..71586ad8d3 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-leaf.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-leaf.xml @@ -3,7 +3,7 @@ - + custom 25 diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-middle.xml b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-middle.xml index 2d12405074..c5fa5b2858 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-middle.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-middle.xml @@ -4,17 +4,16 @@ - + custom 666 - + - + + + - - - \ No newline at end of file diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-root.xml b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-root.xml index ff33aa0212..28f8d65277 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-root.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests-root.xml @@ -6,19 +6,19 @@ - + - + - + custom 25 - + - + false diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java index d05f7ba577..553f9cef46 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/BeanFactoryUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.beans.factory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.Arrays; import java.util.List; @@ -33,12 +33,12 @@ import org.springframework.beans.factory.support.StaticListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.cglib.proxy.NoOp; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.util.ObjectUtils; -import test.beans.DummyFactory; -import test.beans.ITestBean; -import test.beans.IndexedTestBean; -import test.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java index 96eeb3b01f..5ec91dddee 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/ConcurrentBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.beans.factory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import static test.util.TestResourceUtils.qualifiedResource; import java.text.DateFormat; import java.text.ParseException; @@ -39,6 +38,10 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.core.io.Resource; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; + +import static org.springframework.tests.TestResourceUtils.qualifiedResource; /** * @author Guillaume Poirier diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 0e474fadae..acf9f65a05 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,17 @@ package org.springframework.beans.factory; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.Closeable; import java.lang.reflect.Field; import java.net.MalformedURLException; @@ -32,19 +43,13 @@ import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; + import javax.security.auth.Subject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Ignore; import org.junit.Test; -import test.beans.DerivedTestBean; -import test.beans.DummyFactory; -import test.beans.ITestBean; -import test.beans.LifecycleBean; -import test.beans.NestedTestBean; -import test.beans.TestBean; - import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.NotWritablePropertyException; @@ -70,21 +75,25 @@ import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.factory.xml.ConstructorDependenciesBean; -import org.springframework.beans.factory.xml.DependenciesBean; import org.springframework.beans.propertyeditors.CustomNumberEditor; -import org.springframework.tests.Assume; -import org.springframework.tests.TestGroup; import org.springframework.core.MethodParameter; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; +import org.springframework.tests.sample.beans.DependenciesBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.LifecycleBean; +import org.springframework.tests.sample.beans.NestedTestBean; +import org.springframework.tests.sample.beans.SideEffectBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.util.StopWatch; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - /** * Tests properties population and autowire behavior. * @@ -2600,29 +2609,6 @@ public class DefaultListableBeanFactoryTests { } } - /** - * Bean that changes state on a business invocation, so that - * we can check whether it's been invoked - * @author Rod Johnson - */ - private static class SideEffectBean { - - private int count; - - public void setCount(int count) { - this.count = count; - } - - public int getCount() { - return this.count; - } - - public void doWork() { - ++count; - } - - } - private static class KnowsIfInstantiated { private static boolean instantiated; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java index bccb33a978..62c85b60b2 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.beans.factory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/SharedBeanRegistryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/SharedBeanRegistryTests.java index c5f365f799..e422accf4b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/SharedBeanRegistryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/SharedBeanRegistryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,9 @@ import java.util.Arrays; import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.DerivedTestBean; -import test.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/beans/factory/access/beans1.xml b/spring-beans/src/test/java/org/springframework/beans/factory/access/beans1.xml similarity index 100% rename from spring-context/src/test/java/org/springframework/beans/factory/access/beans1.xml rename to spring-beans/src/test/java/org/springframework/beans/factory/access/beans1.xml diff --git a/spring-context/src/test/java/org/springframework/beans/factory/access/beans2.xml b/spring-beans/src/test/java/org/springframework/beans/factory/access/beans2.xml similarity index 100% rename from spring-context/src/test/java/org/springframework/beans/factory/access/beans2.xml rename to spring-beans/src/test/java/org/springframework/beans/factory/access/beans2.xml diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java index 5acfcca8b6..7181f0b8a1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,12 +43,12 @@ import org.springframework.beans.factory.support.AutowireCandidateQualifier; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.NestedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import test.beans.ITestBean; -import test.beans.IndexedTestBean; -import test.beans.NestedTestBean; -import test.beans.TestBean; /** * Unit tests for {@link AutowiredAnnotationBeanPostProcessor}. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java index f9295e4ee6..4fbb7b8cb1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/CustomAutowireConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.beans.factory.annotation; import static org.junit.Assert.assertEquals; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinitionHolder; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java index 4cfba96615..a18a25e05a 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,6 @@ import javax.inject.Named; import javax.inject.Provider; import org.junit.Test; -import test.beans.ITestBean; -import test.beans.IndexedTestBean; -import test.beans.NestedTestBean; -import test.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; @@ -38,6 +34,10 @@ import org.springframework.beans.factory.support.AutowireCandidateQualifier; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.beans.factory.support.RootBeanDefinition; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.NestedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; import static org.junit.Assert.*; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java index c5c49d9b3b..252ee0ddb8 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomEditorConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import java.util.Map; import static org.junit.Assert.*; import org.junit.Test; -import test.beans.TestBean; import org.springframework.beans.FatalBeanException; import org.springframework.beans.MutablePropertyValues; @@ -36,6 +35,7 @@ import org.springframework.beans.PropertyEditorRegistry; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.propertyeditors.CustomDateEditor; +import org.springframework.tests.sample.beans.TestBean; /** * Unit tests for {@link CustomEditorConfigurer}. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests-context.xml index b9c8625b2f..2e2d9fd435 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests-context.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests-context.xml @@ -3,7 +3,7 @@ - + diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java index d5569c3fd3..66226340aa 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/FieldRetrievingFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.beans.factory.config; import static org.junit.Assert.assertEquals; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.sql.Connection; @@ -25,8 +25,8 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * Unit tests for {@link FieldRetrievingFactoryBean}. @@ -119,7 +119,7 @@ public final class FieldRetrievingFactoryBeanTests { @Test public void testWithConstantOnClassWithPackageLevelVisibility() throws Exception { FieldRetrievingFactoryBean fr = new FieldRetrievingFactoryBean(); - fr.setBeanName("test.beans.PackageLevelVisibleBean.CONSTANT"); + fr.setBeanName("org.springframework.tests.sample.beans.PackageLevelVisibleBean.CONSTANT"); fr.afterPropertiesSet(); assertEquals("Wuby", fr.getObject()); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java index a7faf0cc08..dc56161776 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.Date; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java index 409e3f8325..cc43afb4da 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertiesFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.beans.factory.config; import static org.junit.Assert.*; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.Properties; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests-context.xml index b33b3c9c65..490aab8790 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests-context.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests-context.xml @@ -3,19 +3,19 @@ - + 10 - + 11 - + 98 - + 99 @@ -23,7 +23,7 @@ - + 12 @@ -46,10 +46,10 @@ tb spouse - test.beans.TestBean + org.springframework.tests.sample.beans.TestBean - + diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java index 6ec0c706e6..ce21ee9095 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPathFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,15 +20,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.ITestBean; -import test.beans.TestBean; /** * Unit tests for {@link PropertyPathFactoryBean}. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java index c0c65711bc..63e49fb18b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyPlaceholderConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,8 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java index ab67af35a3..1212913cb1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.springframework.beans.factory.support.BeanDefinitionBuilder.genericBeanDefinition; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.Collections; import java.util.HashMap; @@ -48,9 +48,9 @@ import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.ManagedSet; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.IndexedTestBean; -import test.beans.TestBean; /** * Unit tests for various {@link PropertyResourceConfigurer} implementations including: diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests-context.xml index f6f4f4a0a2..1c1978456c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests-context.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests-context.xml @@ -5,6 +5,6 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd"> - + diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java index 861cafa68d..0a561dd336 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/SimpleScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.beans.factory.config; import static org.junit.Assert.*; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.LinkedList; import java.util.List; @@ -28,8 +28,8 @@ import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * Simple test to illustrate and verify scope usage. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests-context.xml index d0c5227844..c2cc486e9d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests-context.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests-context.xml @@ -6,7 +6,7 @@ - + @@ -14,9 +14,9 @@ - + - + @@ -26,5 +26,5 @@ - + \ No newline at end of file diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java index 82a35dc064..20bdd50654 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.beans.factory.parsing; import static org.junit.Assert.*; -import static test.util.TestResourceUtils.qualifiedResource; +import static org.springframework.tests.TestResourceUtils.qualifiedResource; import java.util.ArrayList; import java.util.List; @@ -27,8 +27,8 @@ import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java index 365ae6b958..48bd97d15b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,8 @@ import java.util.Arrays; import junit.framework.TestCase; import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java index c761254fda..11aed3fa64 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanDefinitionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import junit.framework.TestCase; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java index b3516282d4..1afd0c5281 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,10 +45,13 @@ import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.UrlResource; -import test.beans.GenericBean; -import test.beans.GenericIntegerBean; -import test.beans.GenericSetOfIntegerBean; -import test.beans.TestBean; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; +import org.springframework.tests.sample.beans.GenericBean; +import org.springframework.tests.sample.beans.GenericIntegerBean; +import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; +import org.springframework.tests.sample.beans.TestBean; + /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java index 2e4025d304..f9f1beba04 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import junit.framework.TestCase; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.RuntimeBeanReference; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java index 51e8dd7012..d62e43d060 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ package org.springframework.beans.factory.support; import junit.framework.TestCase; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/genericBeanTests.xml b/spring-beans/src/test/java/org/springframework/beans/factory/support/genericBeanTests.xml index 6c9d11f210..3e9a6577b5 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/genericBeanTests.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/genericBeanTests.xml @@ -3,7 +3,7 @@ - + @@ -43,7 +43,7 @@ autowire="constructor"> - + @@ -53,7 +53,7 @@ - + diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java index ded4bb5eae..625e8c7085 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/wiring/BeanConfigurerSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import junit.framework.TestCase; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rick Evans diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java index 490d0a7e1b..4510487801 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,13 +27,13 @@ import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanIsNotAFactoryException; import org.springframework.beans.factory.BeanNotOfRequiredTypeException; -import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.ConfigurableBeanFactory; +import org.springframework.tests.sample.beans.LifecycleBean; +import org.springframework.tests.sample.beans.MustBeInitialized; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; -import test.beans.DummyFactory; -import test.beans.LifecycleBean; -import test.beans.TestBean; /** * Subclasses must implement setUp() to initialize bean factory @@ -336,32 +336,3 @@ public abstract class AbstractBeanFactoryTests extends TestCase { } } - - -/** - * Simple test of BeanFactory initialization - * @author Rod Johnson - * @since 12.03.2003 - */ -class MustBeInitialized implements InitializingBean { - - private boolean inited; - - /** - * @see InitializingBean#afterPropertiesSet() - */ - @Override - public void afterPropertiesSet() throws Exception { - this.inited = true; - } - - /** - * Dummy business method that will fail unless the factory - * managed the bean's lifecycle correctly - */ - public void businessMethod() { - if (!this.inited) - throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object"); - } - -} diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java index 6a04c54074..4c1ac580bb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractListableBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ package org.springframework.beans.factory.xml; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.ListableBeanFactory; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rod Johnson @@ -51,13 +51,13 @@ public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFacto public void assertTestBeanCount(int count) { String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); - assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " + + assertTrue("We should have " + count + " beans for class org.springframework.tests.sample.beans.TestBean, not " + defNames.length, defNames.length == count); int countIncludingFactoryBeans = count + 2; String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true); assertTrue("We should have " + countIncludingFactoryBeans + - " beans for class org.springframework.beans.TestBean, not " + names.length, + " beans for class org.springframework.tests.sample.beans.TestBean, not " + names.length, names.length == countIncludingFactoryBeans); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java index 9cc414ee65..ae6232f40f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AutowireWithExclusionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java index 72de2d65d1..a9294e05fd 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionMergingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import junit.framework.TestCase; import org.springframework.beans.factory.support.BeanDefinitionReader; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * Unit and integration tests for the collection merging support. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java index f57b78d259..3a88ab9fa8 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectionsWithDefaultTypesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import java.util.Map; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ConstructorDependenciesBean.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ConstructorDependenciesBean.java index 6a31f91e1a..082fc418b0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/ConstructorDependenciesBean.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/ConstructorDependenciesBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,9 @@ package org.springframework.beans.factory.xml; import java.io.Serializable; -import test.beans.IndexedTestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.TestBean; + /** * Simple bean used to check constructor dependency checking. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CountingFactory.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CountingFactory.java index 75bcc94d84..7b02d0bed2 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CountingFactory.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/CountingFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,8 @@ package org.springframework.beans.factory.xml; import org.springframework.beans.factory.FactoryBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DummyReferencer.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DummyReferencer.java index d1449fdb0b..a0d4f722e1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DummyReferencer.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DummyReferencer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,8 @@ package org.springframework.beans.factory.xml; -import test.beans.DummyFactory; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-multiLevel-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-multiLevel-context.xml index b897d98858..8e53cee293 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-multiLevel-context.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-multiLevel-context.xml @@ -4,12 +4,12 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> - + - + diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-sameLevel-context.xml b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-sameLevel-context.xml index e8bf2b4469..12a2fb0860 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-sameLevel-context.xml +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests-sameLevel-context.xml @@ -4,12 +4,12 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> - + - + diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java index 58c392ddca..bd92b0c391 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/DuplicateBeanIdTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import static org.junit.Assert.fail; import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java index 62f4e654b6..ff691358a4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/EventPublicationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import org.springframework.beans.factory.parsing.ImportDefinition; import org.springframework.beans.factory.parsing.PassThroughSourceExtractor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.beans.CollectingReaderEventListener; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java index 696ab6c0af..0d67448bc0 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,12 +23,12 @@ import java.util.Properties; import static org.junit.Assert.*; import org.junit.Test; -import test.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java index 1623cf3ac5..a5ef87cb1f 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,8 @@ package org.springframework.beans.factory.xml; import java.util.Collections; import java.util.List; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; + /** * Test class for Spring's ability to create objects using static diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/InstanceFactory.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/InstanceFactory.java index 25ab86c641..6c8872054e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/InstanceFactory.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/InstanceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.beans.factory.xml; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Test class for Spring's ability to create objects using diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java index a6feaedcec..5b9ddc18e6 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import org.junit.Test; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * Tests for propagating enclosing beans element defaults to nested beans elements. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java index 8344d0b529..17552b1d59 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SchemaValidationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import org.xml.sax.SAXParseException; import org.springframework.beans.BeansException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java index f941602888..601afa44fb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ import org.junit.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.DummyBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.DummyBean; -import test.beans.TestBean; /** * @author Costin Leau diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java index badce0656b..45e89564e7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,9 +22,9 @@ import org.junit.Test; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.ITestBean; -import test.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/TestBeanCreator.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/TestBeanCreator.java index 438a4b7e9e..849da031cc 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/TestBeanCreator.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/TestBeanCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.beans.factory.xml; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Test class for Spring's ability to create diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java index d042952a88..3bb04d4c59 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/UtilNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,6 @@ import java.util.TreeMap; import java.util.Arrays; import junit.framework.TestCase; -import test.beans.CustomEnum; -import test.beans.TestBean; import org.springframework.beans.factory.config.FieldRetrievingFactoryBean; import org.springframework.beans.factory.config.PropertiesFactoryBean; @@ -34,6 +32,9 @@ import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.beans.CollectingReaderEventListener; +import org.springframework.tests.sample.beans.CustomEnum; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rob Harrop diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java index 18f616eb14..6960653ea6 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanCollectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.HashSet; -import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -34,7 +33,6 @@ import java.util.Properties; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; -import java.util.concurrent.CopyOnWriteArraySet; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; @@ -44,8 +42,9 @@ import org.springframework.beans.factory.config.MapFactoryBean; import org.springframework.beans.factory.config.SetFactoryBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.HasMap; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * Tests for collections in XML bean definitions. @@ -452,94 +451,3 @@ public class XmlBeanCollectionTests { } } } - - -/** - * Bean exposing a map. Used for bean factory tests. - * - * @author Rod Johnson - * @since 05.06.2003 - */ -class HasMap { - - private Map map; - - private IdentityHashMap identityMap; - - private Set set; - - private CopyOnWriteArraySet concurrentSet; - - private Properties props; - - private Object[] objectArray; - - private Class[] classArray; - - private Integer[] intArray; - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public IdentityHashMap getIdentityMap() { - return identityMap; - } - - public void setIdentityMap(IdentityHashMap identityMap) { - this.identityMap = identityMap; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public CopyOnWriteArraySet getConcurrentSet() { - return concurrentSet; - } - - public void setConcurrentSet(CopyOnWriteArraySet concurrentSet) { - this.concurrentSet = concurrentSet; - } - - public Properties getProps() { - return props; - } - - public void setProps(Properties props) { - this.props = props; - } - - public Object[] getObjectArray() { - return objectArray; - } - - public void setObjectArray(Object[] objectArray) { - this.objectArray = objectArray; - } - - public Class[] getClassArray() { - return classArray; - } - - public void setClassArray(Class[] classArray) { - this.classArray = classArray; - } - - public Integer[] getIntegerArray() { - return intArray; - } - - public void setIntegerArray(Integer[] is) { - intArray = is; - } - -} diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java index 76baf7366f..c5da99f0e4 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlBeanDefinitionReaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,8 @@ import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.InputStreamResource; import org.springframework.core.io.Resource; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.TestBean; /** * @author Rick Evans diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java index 5b6e88a155..2fd60f7a0e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/XmlListableBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,11 +28,11 @@ import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.LifecycleBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; -import test.beans.DummyFactory; -import test.beans.ITestBean; -import test.beans.LifecycleBean; -import test.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java index ca477008cd..d205291620 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,12 +44,12 @@ import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; +import org.springframework.tests.sample.beans.BooleanTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.NumberTestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.beans.BooleanTestBean; -import test.beans.ITestBean; -import test.beans.IndexedTestBean; -import test.beans.NumberTestBean; -import test.beans.TestBean; /** * Unit tests for the various PropertyEditors in Spring. @@ -592,9 +592,9 @@ public class CustomEditorTests { @Test public void testClassEditorWithArray() { PropertyEditor classEditor = new ClassEditor(); - classEditor.setAsText("test.beans.TestBean[]"); + classEditor.setAsText("org.springframework.tests.sample.beans.TestBean[]"); assertEquals(TestBean[].class, classEditor.getValue()); - assertEquals("test.beans.TestBean[]", classEditor.getAsText()); + assertEquals("org.springframework.tests.sample.beans.TestBean[]", classEditor.getAsText()); } /* diff --git a/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java index ef03607658..14c2882026 100644 --- a/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,18 @@ package org.springframework.beans.support; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import java.util.ArrayList; import java.util.List; + import junit.framework.TestCase; -import test.beans.TestBean; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectingReaderEventListener.java b/spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java similarity index 98% rename from spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectingReaderEventListener.java rename to spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java index 1924dac82e..8779f9ed5e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/CollectingReaderEventListener.java +++ b/spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans.factory.xml; +package org.springframework.tests.beans; import java.util.ArrayList; import java.util.Collection; diff --git a/spring-beans/src/test/java/test/beans/BooleanTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/BooleanTestBean.java similarity index 95% rename from spring-beans/src/test/java/test/beans/BooleanTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/BooleanTestBean.java index 4ea2f67d3b..92484b7d1a 100644 --- a/spring-beans/src/test/java/test/beans/BooleanTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/BooleanTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** * @author Juergen Hoeller diff --git a/spring-context-support/src/test/java/org/springframework/beans/Colour.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/Colour.java similarity index 95% rename from spring-context-support/src/test/java/org/springframework/beans/Colour.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/Colour.java index a992a2ebfc..a4a7d9740b 100644 --- a/spring-context-support/src/test/java/org/springframework/beans/Colour.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/Colour.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; import org.springframework.core.enums.ShortCodedLabeledEnum; diff --git a/spring-aop/src/test/java/test/beans/CountingTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/CountingTestBean.java similarity index 94% rename from spring-aop/src/test/java/test/beans/CountingTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/CountingTestBean.java index 5065764765..e5f6947de5 100644 --- a/spring-aop/src/test/java/test/beans/CountingTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/CountingTestBean.java @@ -1,7 +1,3 @@ -/* - * $Id$ - */ - /* * Copyright 2002-2005 the original author or authors. * @@ -18,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** diff --git a/spring-webmvc/src/test/java/org/springframework/beans/CustomEnum.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/CustomEnum.java similarity index 94% rename from spring-webmvc/src/test/java/org/springframework/beans/CustomEnum.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/CustomEnum.java index 1e43492191..66a863772f 100644 --- a/spring-webmvc/src/test/java/org/springframework/beans/CustomEnum.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/CustomEnum.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; /** * @author Juergen Hoeller diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DependenciesBean.java similarity index 95% rename from spring-beans/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/DependenciesBean.java index 8bed2eeeab..b17d1028cc 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DependenciesBean.java @@ -14,13 +14,11 @@ * limitations under the License. */ -package org.springframework.beans.factory.xml; +package org.springframework.tests.sample.beans; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; -import test.beans.TestBean; - /** * Simple bean used to test dependency checking. * diff --git a/spring-beans/src/test/java/test/beans/DerivedTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DerivedTestBean.java similarity index 97% rename from spring-beans/src/test/java/test/beans/DerivedTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/DerivedTestBean.java index c0f63181ab..91416208a2 100644 --- a/spring-beans/src/test/java/test/beans/DerivedTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DerivedTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import java.io.Serializable; diff --git a/spring-beans/src/test/java/test/beans/DummyBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DummyBean.java similarity index 96% rename from spring-beans/src/test/java/test/beans/DummyBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/DummyBean.java index a8428c7f78..cb5767eef5 100644 --- a/spring-beans/src/test/java/test/beans/DummyBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DummyBean.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** * @author Costin Leau diff --git a/spring-beans/src/test/java/test/beans/DummyFactory.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DummyFactory.java similarity index 97% rename from spring-beans/src/test/java/test/beans/DummyFactory.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/DummyFactory.java index 60f7966d9a..dc08778c53 100644 --- a/spring-beans/src/test/java/test/beans/DummyFactory.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/DummyFactory.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; @@ -24,6 +24,7 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.tests.sample.beans.TestBean; /** diff --git a/spring-beans/src/test/java/test/beans/GenericBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericBean.java similarity index 95% rename from spring-beans/src/test/java/test/beans/GenericBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericBean.java index 12ff808dc8..c192382a1b 100644 --- a/spring-beans/src/test/java/test/beans/GenericBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import java.util.ArrayList; import java.util.Collection; @@ -37,6 +37,8 @@ public class GenericBean { private Set numberSet; + private Set testBeanSet; + private List resourceList; private List testBeanList; @@ -69,6 +71,7 @@ public class GenericBean { private List genericListProperty; + public GenericBean() { } @@ -121,6 +124,14 @@ public class GenericBean { this.numberSet = numberSet; } + public Set getTestBeanSet() { + return testBeanSet; + } + + public void setTestBeanSet(Set testBeanSet) { + this.testBeanSet = testBeanSet; + } + public List getResourceList() { return resourceList; } @@ -284,4 +295,4 @@ public class GenericBean { return new GenericBean(someFlag, collectionMap); } -} \ No newline at end of file +} diff --git a/spring-beans/src/test/java/test/beans/GenericIntegerBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericIntegerBean.java similarity index 93% rename from spring-beans/src/test/java/test/beans/GenericIntegerBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericIntegerBean.java index 43b6465df0..b7465b1bfa 100644 --- a/spring-beans/src/test/java/test/beans/GenericIntegerBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericIntegerBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** diff --git a/spring-beans/src/test/java/test/beans/GenericSetOfIntegerBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericSetOfIntegerBean.java similarity index 94% rename from spring-beans/src/test/java/test/beans/GenericSetOfIntegerBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericSetOfIntegerBean.java index 021c0cd1c1..a0fee60195 100644 --- a/spring-beans/src/test/java/test/beans/GenericSetOfIntegerBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/GenericSetOfIntegerBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import java.util.Set; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/HasMap.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/HasMap.java similarity index 75% rename from spring-context/src/test/java/org/springframework/beans/factory/HasMap.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/HasMap.java index 73fe70276e..4639050b2a 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/HasMap.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/HasMap.java @@ -14,11 +14,13 @@ * limitations under the License. */ -package org.springframework.beans.factory; +package org.springframework.tests.sample.beans; +import java.util.IdentityHashMap; import java.util.Map; import java.util.Properties; import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; /** * Bean exposing a map. Used for bean factory tests. @@ -40,6 +42,10 @@ public class HasMap { private Integer[] intArray; + private IdentityHashMap identityMap; + + private CopyOnWriteArraySet concurrentSet; + private HasMap() { } @@ -91,4 +97,20 @@ public class HasMap { intArray = is; } + public IdentityHashMap getIdentityMap() { + return identityMap; + } + + public void setIdentityMap(IdentityHashMap identityMap) { + this.identityMap = identityMap; + } + + public CopyOnWriteArraySet getConcurrentSet() { + return concurrentSet; + } + + public void setConcurrentSet(CopyOnWriteArraySet concurrentSet) { + this.concurrentSet = concurrentSet; + } + } diff --git a/spring-aspects/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/INestedTestBean.java similarity index 93% rename from spring-aspects/src/test/java/org/springframework/beans/INestedTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/INestedTestBean.java index e0ae5f20a3..58c4b9d502 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/INestedTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/INestedTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; public interface INestedTestBean { diff --git a/spring-beans/src/test/java/test/beans/IOther.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/IOther.java similarity index 93% rename from spring-beans/src/test/java/test/beans/IOther.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/IOther.java index f3c6263261..694f32d275 100644 --- a/spring-beans/src/test/java/test/beans/IOther.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/IOther.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; public interface IOther { diff --git a/spring-web/src/test/java/org/springframework/beans/ITestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/ITestBean.java similarity index 90% rename from spring-web/src/test/java/org/springframework/beans/ITestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/ITestBean.java index 526c3dacfb..b467348a93 100644 --- a/spring-web/src/test/java/org/springframework/beans/ITestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/ITestBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2007 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. @@ -14,12 +14,12 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; import java.io.IOException; /** - * Interface used for {@link org.springframework.beans.TestBean}. + * Interface used for {@link org.springframework.tests.sample.beans.TestBean}. * *

Two methods are the same as on Person, but if this * extends person it breaks quite a few tests.. @@ -84,4 +84,4 @@ public interface ITestBean { void unreliableFileOperation() throws IOException; -} \ No newline at end of file +} diff --git a/spring-beans/src/test/java/test/beans/IndexedTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/IndexedTestBean.java similarity index 98% rename from spring-beans/src/test/java/test/beans/IndexedTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/IndexedTestBean.java index bd2a72662f..d319bbd0ed 100644 --- a/spring-beans/src/test/java/test/beans/IndexedTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/IndexedTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import java.util.ArrayList; import java.util.Collection; diff --git a/spring-beans/src/test/java/test/beans/LifecycleBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/LifecycleBean.java similarity index 99% rename from spring-beans/src/test/java/test/beans/LifecycleBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/LifecycleBean.java index cd1dcd6e5e..1a81d10340 100644 --- a/spring-beans/src/test/java/test/beans/LifecycleBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/LifecycleBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/MustBeInitialized.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/MustBeInitialized.java similarity index 92% rename from spring-context/src/test/java/org/springframework/beans/factory/MustBeInitialized.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/MustBeInitialized.java index 959861e6b4..cc83d69d83 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/MustBeInitialized.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/MustBeInitialized.java @@ -14,7 +14,9 @@ * limitations under the License. */ -package org.springframework.beans.factory; +package org.springframework.tests.sample.beans; + +import org.springframework.beans.factory.InitializingBean; /** * Simple test of BeanFactory initialization diff --git a/spring-beans/src/test/java/test/beans/NestedTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/NestedTestBean.java similarity index 96% rename from spring-beans/src/test/java/test/beans/NestedTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/NestedTestBean.java index edc145ad7d..844c5ea692 100644 --- a/spring-beans/src/test/java/test/beans/NestedTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/NestedTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** * Simple nested test bean used for testing bean factories, AOP framework etc. diff --git a/spring-beans/src/test/java/test/beans/NumberTestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/NumberTestBean.java similarity index 98% rename from spring-beans/src/test/java/test/beans/NumberTestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/NumberTestBean.java index cdd80bd27b..489c933509 100644 --- a/spring-beans/src/test/java/test/beans/NumberTestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/NumberTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; import java.math.BigDecimal; import java.math.BigInteger; diff --git a/spring-beans/src/test/java/test/beans/PackageLevelVisibleBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/PackageLevelVisibleBean.java similarity index 94% rename from spring-beans/src/test/java/test/beans/PackageLevelVisibleBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/PackageLevelVisibleBean.java index eeb4b7325d..142a5da2d2 100644 --- a/spring-beans/src/test/java/test/beans/PackageLevelVisibleBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/PackageLevelVisibleBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** * @see org.springframework.beans.factory.config.FieldRetrievingFactoryBeanTests diff --git a/spring-test/src/test/java/org/springframework/beans/Pet.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/Pet.java similarity index 96% rename from spring-test/src/test/java/org/springframework/beans/Pet.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/Pet.java index eb78f612fb..61563f0dd8 100644 --- a/spring-test/src/test/java/org/springframework/beans/Pet.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/Pet.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; /** * @author Rob Harrop diff --git a/spring-aop/src/test/java/test/beans/SideEffectBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/SideEffectBean.java similarity index 95% rename from spring-aop/src/test/java/test/beans/SideEffectBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/SideEffectBean.java index 621ecbc3a2..9477a5e548 100644 --- a/spring-aop/src/test/java/test/beans/SideEffectBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/SideEffectBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** * Bean that changes state on a business invocation, so that diff --git a/spring-context/src/test/java/org/springframework/beans/TestBean.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/TestBean.java similarity index 89% rename from spring-context/src/test/java/org/springframework/beans/TestBean.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/TestBean.java index c050b64856..cb276da9cb 100644 --- a/spring-context/src/test/java/org/springframework/beans/TestBean.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/TestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; import java.io.IOException; import java.util.ArrayList; @@ -58,7 +58,7 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt private boolean jedi; - private ITestBean[] spouses; + protected ITestBean[] spouses; private String touchy; @@ -66,6 +66,12 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt private Integer[] someIntegerArray; + private Integer[][] nestedIntegerArray; + + private int[] someIntArray; + + private int[][] nestedIntArray; + private Date date = new Date(); private Float myFloat = new Float(0.0); @@ -257,6 +263,36 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt this.someIntegerArray = someIntegerArray; } + @Override + public Integer[][] getNestedIntegerArray() { + return nestedIntegerArray; + } + + @Override + public void setNestedIntegerArray(Integer[][] nestedIntegerArray) { + this.nestedIntegerArray = nestedIntegerArray; + } + + @Override + public int[] getSomeIntArray() { + return someIntArray; + } + + @Override + public void setSomeIntArray(int[] someIntArray) { + this.someIntArray = someIntArray; + } + + @Override + public int[][] getNestedIntArray() { + return nestedIntArray; + } + + @Override + public void setNestedIntArray(int[][] nestedIntArray) { + this.nestedIntArray = nestedIntArray; + } + public Date getDate() { return date; } @@ -382,7 +418,7 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt /** - * @see org.springframework.beans.ITestBean#exceptional(Throwable) + * @see org.springframework.tests.sample.beans.ITestBean#exceptional(Throwable) */ @Override public void exceptional(Throwable t) throws Throwable { @@ -396,7 +432,7 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt throw new IOException(); } /** - * @see org.springframework.beans.ITestBean#returnsThis() + * @see org.springframework.tests.sample.beans.ITestBean#returnsThis() */ @Override public Object returnsThis() { @@ -404,7 +440,7 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt } /** - * @see org.springframework.beans.IOther#absquatulate() + * @see org.springframework.tests.sample.beans.IOther#absquatulate() */ @Override public void absquatulate() { @@ -454,4 +490,4 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt return this.name; } -} \ No newline at end of file +} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/DummyFactory.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/factory/DummyFactory.java similarity index 87% rename from spring-context/src/test/java/org/springframework/beans/factory/DummyFactory.java rename to spring-beans/src/test/java/org/springframework/tests/sample/beans/factory/DummyFactory.java index f9c4f27382..b562f569fa 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/DummyFactory.java +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/factory/DummyFactory.java @@ -14,11 +14,18 @@ * limitations under the License. */ -package org.springframework.beans.factory; +package org.springframework.tests.sample.beans.factory; import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; +import org.springframework.beans.factory.BeanNameAware; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.tests.sample.beans.TestBean; + /** * Simple factory to allow testing of FactoryBean support in AbstractBeanFactory. @@ -29,6 +36,7 @@ import org.springframework.beans.factory.config.AutowireCapableBeanFactory; * factories get this lifecycle callback if they want. * * @author Rod Johnson + * @author Chris Beams * @since 10.03.2003 */ public class DummyFactory @@ -72,7 +80,7 @@ public class DummyFactory /** * Return if the bean managed by this factory is a singleton. - * @see org.springframework.beans.factory.FactoryBean#isSingleton() + * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { @@ -146,7 +154,7 @@ public class DummyFactory /** * Return the managed object, supporting both singleton * and prototype mode. - * @see org.springframework.beans.factory.FactoryBean#getObject() + * @see FactoryBean#getObject() */ @Override public Object getObject() throws BeansException { @@ -164,7 +172,7 @@ public class DummyFactory } @Override - public Class getObjectType() { + public Class getObjectType() { return TestBean.class; } @@ -176,4 +184,4 @@ public class DummyFactory } } -} +} \ No newline at end of file diff --git a/spring-beans/src/test/java/org/springframework/tests/sample/beans/package-info.java b/spring-beans/src/test/java/org/springframework/tests/sample/beans/package-info.java new file mode 100644 index 0000000000..575bd1933f --- /dev/null +++ b/spring-beans/src/test/java/org/springframework/tests/sample/beans/package-info.java @@ -0,0 +1,4 @@ +/** + * General purpose sample beans that can be used with tests. + */ +package org.springframework.tests.sample.beans; diff --git a/spring-beans/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-beans/src/test/java/org/springframework/util/SerializationTestUtils.java deleted file mode 100644 index 9ae4f54ec2..0000000000 --- a/spring-beans/src/test/java/org/springframework/util/SerializationTestUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2002-2009 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * - * @author Rod Johnson - */ -public class SerializationTestUtils { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - return o2; - } - -} diff --git a/spring-beans/src/test/java/test/beans/Colour.java b/spring-beans/src/test/java/test/beans/Colour.java deleted file mode 100644 index 533d0df36e..0000000000 --- a/spring-beans/src/test/java/test/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-beans/src/test/java/test/beans/CustomEnum.java b/spring-beans/src/test/java/test/beans/CustomEnum.java deleted file mode 100644 index d7404bc678..0000000000 --- a/spring-beans/src/test/java/test/beans/CustomEnum.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2002-2007 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 test.beans; - -/** - * @author Juergen Hoeller - */ -public enum CustomEnum { - - VALUE_1, VALUE_2; - - public String toString() { - return "CustomEnum: " + name(); - } - -} \ No newline at end of file diff --git a/spring-beans/src/test/java/test/beans/INestedTestBean.java b/spring-beans/src/test/java/test/beans/INestedTestBean.java deleted file mode 100644 index 56c9d829ee..0000000000 --- a/spring-beans/src/test/java/test/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-beans/src/test/java/test/beans/ITestBean.java b/spring-beans/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 9397b17550..0000000000 --- a/spring-beans/src/test/java/test/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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 test.beans; - -import java.io.IOException; - -/** - * Interface used for {@link test.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-beans/src/test/java/test/beans/TestBean.java b/spring-beans/src/test/java/test/beans/TestBean.java deleted file mode 100644 index 5b94f078b5..0000000000 --- a/spring-beans/src/test/java/test/beans/TestBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-beans/src/test/java/test/util/TestResourceUtils.java b/spring-beans/src/test/java/test/util/TestResourceUtils.java deleted file mode 100644 index 4843151231..0000000000 --- a/spring-beans/src/test/java/test/util/TestResourceUtils.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.util; - -import static java.lang.String.format; - -import org.springframework.core.io.ClassPathResource; - -/** - * Convenience utilities for common operations with test resources. - * - * @author Chris Beams - */ -public class TestResourceUtils { - - /** - * Loads a {@link ClassPathResource} qualified by the simple name of clazz, - * and relative to the package for clazz. - * - *

Example: given a clazz 'com.foo.BarTests' and a resourceSuffix of 'context.xml', - * this method will return a ClassPathResource representing com/foo/BarTests-context.xml - * - *

Intended for use loading context configuration XML files within JUnit tests. - * - * @param clazz - * @param resourceSuffix - */ - public static ClassPathResource qualifiedResource(Class clazz, String resourceSuffix) { - return new ClassPathResource(format("%s-%s", clazz.getSimpleName(), resourceSuffix), clazz); - } - -} diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/support/multiConstructorArgs.properties b/spring-beans/src/test/resources/org/springframework/beans/factory/support/multiConstructorArgs.properties index 5beaf6d598..8d5f74fc31 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/support/multiConstructorArgs.properties +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/support/multiConstructorArgs.properties @@ -1,3 +1,3 @@ -testBean.(class)=test.beans.TestBean +testBean.(class)=org.springframework.tests.sample.beans.TestBean testBean.$0=Rob Harrop -testBean.$1=23 \ No newline at end of file +testBean.$1=23 diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/support/refConstructorArg.properties b/spring-beans/src/test/resources/org/springframework/beans/factory/support/refConstructorArg.properties index c33326c857..4d3723c7de 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/support/refConstructorArg.properties +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/support/refConstructorArg.properties @@ -1,5 +1,5 @@ -sally.(class)=test.beans.TestBean +sally.(class)=org.springframework.tests.sample.beans.TestBean sally.name=Sally -rob.(class)=test.beans.TestBean -rob.$0(ref)=sally \ No newline at end of file +rob.(class)=org.springframework.tests.sample.beans.TestBean +rob.$0(ref)=sally diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/support/simpleConstructorArg.properties b/spring-beans/src/test/resources/org/springframework/beans/factory/support/simpleConstructorArg.properties index be6700e142..d0f1eea326 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/support/simpleConstructorArg.properties +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/support/simpleConstructorArg.properties @@ -1,2 +1,2 @@ -testBean.(class)=test.beans.TestBean -testBean.$0=Rob Harrop \ No newline at end of file +testBean.(class)=org.springframework.tests.sample.beans.TestBean +testBean.$0=Rob Harrop diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests-merge-context.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests-merge-context.xml index 12dbc60792..2edadb511e 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests-merge-context.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/NestedBeansElementAttributeRecursionTests-merge-context.xml @@ -5,7 +5,7 @@ http://www.springframework.org/schema/beans/spring-beans-3.1.xsd" default-merge="false"> - + alpha diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-constructor-with-exclusion.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-constructor-with-exclusion.xml index 6363230a06..2fcb117954 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-constructor-with-exclusion.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-constructor-with-exclusion.xml @@ -3,9 +3,9 @@ - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-exclusion.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-exclusion.xml index 3f32de8aee..a2e966aab9 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-exclusion.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-exclusion.xml @@ -3,9 +3,9 @@ - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-inclusion.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-inclusion.xml index e32686f27f..9b93a16810 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-inclusion.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-inclusion.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" default-autowire-candidates=""> - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-selective-inclusion.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-selective-inclusion.xml index 2883bd2383..089517cd42 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-selective-inclusion.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/autowire-with-selective-inclusion.xml @@ -4,9 +4,9 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd" default-autowire-candidates="props*,*ly"> - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/beanEvents.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/beanEvents.xml index 22168ca8c8..7e262a0a0d 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/beanEvents.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/beanEvents.xml @@ -10,22 +10,22 @@ - + - + - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionMerging.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionMerging.xml index a614172a89..d8fc1db88e 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionMerging.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionMerging.xml @@ -3,7 +3,7 @@ - + Rob Harrop @@ -23,12 +23,12 @@ - + - + Rob Harrop @@ -47,14 +47,14 @@ - + - + @@ -76,7 +76,7 @@ - + @@ -84,7 +84,7 @@ - + Sall @@ -103,7 +103,7 @@ - + Rob Harrop @@ -123,12 +123,12 @@ - + - + Rob Harrop @@ -147,14 +147,14 @@ - + - + @@ -176,7 +176,7 @@ - + @@ -184,7 +184,7 @@ - + Sall diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collections.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collections.xml index 44bd0b92dc..974ae6c3d9 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collections.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collections.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"> - + Jenny 30 @@ -11,8 +11,8 @@ - - + + Simple bean, without any collections. @@ -22,8 +22,8 @@ 27 - - + + Rod 32 @@ -34,8 +34,8 @@ - - + + Jenny 30 @@ -44,13 +44,13 @@ - + David 27 - + Rod 32 @@ -64,7 +64,7 @@ - + loner 26 @@ -74,7 +74,7 @@ - + @@ -89,7 +89,7 @@ - + @@ -102,26 +102,26 @@ - + verbose - - + + - + - + - - + + @@ -131,7 +131,7 @@ - + @@ -158,7 +158,7 @@ - + @@ -177,7 +177,7 @@ - + @@ -186,7 +186,7 @@ - + @@ -217,15 +217,15 @@ - - + + - + bar @@ -235,7 +235,7 @@ - + bar @@ -245,7 +245,7 @@ - + @@ -254,15 +254,15 @@ - + - - - + + + bar @@ -270,8 +270,8 @@ - - + + @@ -280,7 +280,7 @@ - + one @@ -288,8 +288,8 @@ - - + + java.lang.String @@ -297,8 +297,8 @@ - - + + 0 diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionsWithDefaultTypes.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionsWithDefaultTypes.xml index 7cd04cc145..8a31ff8696 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionsWithDefaultTypes.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/collectionsWithDefaultTypes.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - + 1 @@ -28,7 +28,7 @@ - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/factory-methods.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/factory-methods.xml index f97701759b..4ff20b3d59 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/factory-methods.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/factory-methods.xml @@ -102,7 +102,7 @@ - + Juergen @@ -127,7 +127,7 @@ - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/schemaValidated.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/schemaValidated.xml index 33cbb8dd8d..7802a4c935 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/schemaValidated.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/schemaValidated.xml @@ -3,16 +3,16 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> - + - + - + - - + + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTests.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTests.xml index f245c964dd..d961644301 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTests.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTests.xml @@ -5,43 +5,43 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + - + - + - + - + - + - + \ No newline at end of file diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTestsWithErrors.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTestsWithErrors.xml index 7c10f7a32f..1773a1c9c6 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTestsWithErrors.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simpleConstructorNamespaceHandlerTestsWithErrors.xml @@ -4,7 +4,7 @@ xmlns:p="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTests.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTests.xml index e44a8c961c..8dd70708d3 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTests.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTests.xml @@ -8,20 +8,20 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> - + - + - + - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTestsWithErrors.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTestsWithErrors.xml index d82595bac7..384171fdc0 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTestsWithErrors.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerTestsWithErrors.xml @@ -8,10 +8,10 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> - + - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/test.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/test.xml index 9d1d1f7adb..933e66b7d0 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/test.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/test.xml @@ -3,7 +3,7 @@ - + I have no properties and I'm happy without them. @@ -12,7 +12,7 @@ - + aliased @@ -20,17 +20,17 @@ - + aliased - + aliased - + @@ -40,7 +40,7 @@ - + Rod 31 @@ -52,29 +52,29 @@ - + Kerry 34 - + Kathy 28 - + typeMismatch 34x - + - true @@ -85,10 +85,10 @@ - + - + false @@ -113,14 +113,14 @@ - + listenerVeto 66 - + - + this is a ]]> diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/testUtilNamespace.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/testUtilNamespace.xml index 8426c5d95e..25f20439fa 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/testUtilNamespace.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/testUtilNamespace.xml @@ -17,7 +17,7 @@ name "/> - + @@ -26,13 +26,13 @@ - + - + @@ -67,7 +67,7 @@ Rob Harrop - + foo @@ -89,13 +89,13 @@ - + - + @@ -111,13 +111,13 @@ min - + - + @@ -147,7 +147,7 @@ - + diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithDtd.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithDtd.xml index fab962d4dd..3cca869dbf 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithDtd.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithDtd.xml @@ -9,5 +9,5 @@ This is a top level block comment - + \ No newline at end of file diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithXsd.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithXsd.xml index 324fb483ff..20aa0f5374 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithXsd.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/validateWithXsd.xml @@ -7,5 +7,5 @@ This is a top level block comment the parser now --> - + \ No newline at end of file diff --git a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/withMeta.xml b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/withMeta.xml index 7cb0723a4c..05c47afa53 100644 --- a/spring-beans/src/test/resources/org/springframework/beans/factory/xml/withMeta.xml +++ b/spring-beans/src/test/resources/org/springframework/beans/factory/xml/withMeta.xml @@ -4,15 +4,15 @@ xmlns:spring="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> - + - + - + diff --git a/spring-context-support/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-context-support/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-context-support/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/beans/IOther.java b/spring-context-support/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-context-support/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/beans/ITestBean.java b/spring-context-support/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-context-support/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-context-support/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770e..0000000000 --- a/spring-context-support/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-context-support/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-context-support/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/beans/TestBean.java b/spring-context-support/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 6d71de7576..0000000000 --- a/spring-context-support/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see org.springframework.beans.ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see org.springframework.beans.ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see org.springframework.beans.IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java b/spring-context-support/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java deleted file mode 100644 index a95a2408b5..0000000000 --- a/spring-context-support/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2002-2005 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.scheduling; - -/** - * @author Juergen Hoeller - * @since 09.10.2004 - */ -public class TestMethodInvokingTask { - - public int counter = 0; - - private Object lock = new Object(); - - public void doSomething() { - this.counter++; - } - - public void doWait() { - this.counter++; - // wait until stop is called - synchronized (this.lock) { - try { - this.lock.wait(); - } - catch (InterruptedException e) { - // fall through - } - } - } - - public void stop() { - synchronized(this.lock) { - this.lock.notify(); - } - } - -} \ No newline at end of file diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java index dfe6d48aa7..5c0cc1c0e3 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java @@ -51,7 +51,8 @@ import org.quartz.Trigger; import org.quartz.TriggerListener; import org.quartz.impl.SchedulerRepository; import org.quartz.spi.JobFactory; -import org.springframework.beans.TestBean; +import org.springframework.tests.context.TestMethodInvokingTask; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.RootBeanDefinition; @@ -63,7 +64,6 @@ import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.core.task.TaskExecutor; import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.scheduling.TestMethodInvokingTask; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java index 0e9f634bd4..364d541592 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import org.junit.Test; import org.springframework.aop.aspectj.AdviceBindingTestAspect.AdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.xml index 9a55cc823e..66d0e85228 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterAdviceBindingTests.xml @@ -19,6 +19,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java index a2f1054e9e..c04a54f8e6 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,8 @@ import org.junit.Test; import org.springframework.aop.aspectj.AfterReturningAdviceBindingTestAspect.AfterReturningAdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.xml index 197afbf069..97c02b3452 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterReturningAdviceBindingTests.xml @@ -18,7 +18,7 @@ + pointcut="execution(org.springframework.tests.sample.beans.ITestBean[] *(..))"/> @@ -30,6 +30,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java index e57c4df217..0760507924 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import static org.mockito.Mockito.verify; import org.junit.Before; import org.junit.Test; import org.springframework.aop.aspectj.AfterThrowingAdviceBindingTestAspect.AfterThrowingAdviceBindingCollaborator; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.xml index 9152fe1853..77dd0c3624 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AfterThrowingAdviceBindingTests.xml @@ -37,6 +37,6 @@ - + \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java index 67195904dc..879e846b2b 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,8 +26,8 @@ import org.junit.Test; import org.springframework.aop.aspectj.AroundAdviceBindingTestAspect.AroundAdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.xml index 91ca7c6540..2198e32f49 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceBindingTests.xml @@ -17,6 +17,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.xml index 7f94710183..e00fa847a7 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AroundAdviceCircularTests.xml @@ -17,11 +17,11 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java index 5b606689ac..585d180695 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.aspectj.lang.ProceedingJoinPoint; import org.junit.Before; import org.junit.Test; import org.springframework.aop.MethodBeforeAdvice; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.Ordered; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.xml index 6dae894ae6..038614eccf 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectAndAdvicePrecedenceTests.xml @@ -85,6 +85,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java index b88de9c97d..2b363cab83 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.xml index 8a23b5ad4d..9ec75d75aa 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutAdvisorTests.xml @@ -5,11 +5,11 @@ - + + value="execution(org.springframework.tests.sample.beans.ITestBean[] org.springframework.tests.sample.beans.ITestBean.*(..))"/> diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java index e43cc57988..4ab6a83064 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import org.aspectj.lang.annotation.Before; import org.junit.Test; import org.springframework.aop.aspectj.annotation.AspectJProxyFactory; import org.springframework.aop.framework.Advised; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.xml index 987a8b852c..b446755d57 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutAtAspectTests.xml @@ -6,10 +6,10 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> - - - - + + + + - \ No newline at end of file + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java index 53a81f6e5a..7c22506048 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.junit.Before; import org.junit.Test; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.framework.Advised; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.xml index 66ccb58495..42dafc3e90 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeanNamePointcutTests.xml @@ -21,13 +21,13 @@ - + - + - + - + @@ -53,9 +53,9 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java index 4df2dc3633..94e6e43f8a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import org.junit.Test; import org.springframework.aop.aspectj.AdviceBindingTestAspect.AdviceBindingCollaborator; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.xml index d12031f34e..4aac362c73 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/BeforeAdviceBindingTests.xml @@ -26,7 +26,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java index 59a3136fdc..145617f07a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java @@ -22,8 +22,8 @@ import org.junit.Before; import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.xml index d8b4887fe6..fc449b6943 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.xml @@ -8,7 +8,7 @@ @@ -17,11 +17,11 @@ pointcut="execution(* set*(*)) and this(mixin)" arg-names="mixin" /> - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.java index 0e7435362a..f9d810c626 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** @@ -39,7 +39,7 @@ public final class ImplicitJPArgumentMatchingAtAspectJTests { @Aspect static class CounterAtAspectJAspect { - @Around(value="execution(* org.springframework.beans.TestBean.*(..)) and this(bean) and args(argument)", + @Around(value="execution(* org.springframework.tests.sample.beans.TestBean.*(..)) and this(bean) and args(argument)", argNames="bean,argument") public void increment(ProceedingJoinPoint pjp, TestBean bean, Object argument) throws Throwable { pjp.proceed(); diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.xml index 01bd862dd1..c88962cd53 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingAtAspectJTests.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingTests.xml index 1c10ec952f..6a4a56e7f0 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/ImplicitJPArgumentMatchingTests.xml @@ -8,12 +8,12 @@ + expression="execution(* org.springframework.tests.sample.beans.TestBean.*(..)) and this(bean) and args(argument)"/> - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests-ambiguous.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests-ambiguous.xml index 3268b8ccec..f8ca001d0d 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests-ambiguous.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests-ambiguous.xml @@ -15,6 +15,6 @@ - + \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.xml index 57f3f9dd4d..94725cb5e3 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/OverloadedAdviceTests.xml @@ -16,6 +16,6 @@ - + \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests-context.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests-context.xml index 7d84660400..6490decb21 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests-context.xml @@ -13,7 +13,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java index 361809558b..9b6a0b6174 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectImplementingInterfaceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.*; import org.aspectj.lang.ProceedingJoinPoint; import org.junit.Test; import org.springframework.aop.framework.Advised; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java index f609c08b3e..7ca3e87e15 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorAndLazyInitTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ package org.springframework.aop.aspectj.autoproxy; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspects.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspects.xml index 3eedc35b00..da15419d11 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspects.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspects.xml @@ -23,11 +23,11 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsPlusAdvisor.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsPlusAdvisor.xml index 8a399d0361..2b23fab302 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsPlusAdvisor.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsPlusAdvisor.xml @@ -9,17 +9,17 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithAbstractBean.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithAbstractBean.xml index c1c8376b30..88907c1b6c 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithAbstractBean.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithAbstractBean.xml @@ -20,7 +20,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithOrdering.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithOrdering.xml index a299f40e30..53c2a50c66 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithOrdering.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-aspectsWithOrdering.xml @@ -17,7 +17,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-pertarget.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-pertarget.xml index e02baf027b..efb221722a 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-pertarget.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-pertarget.xml @@ -10,12 +10,12 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-perthis.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-perthis.xml index 408c547739..25f545b542 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-perthis.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-perthis.xml @@ -7,7 +7,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspect.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspect.xml index a916c5a1e5..e00377721c 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspect.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspect.xml @@ -7,7 +7,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspectPrototype.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspectPrototype.xml index 047ef0daaf..9505a844d7 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspectPrototype.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-twoAdviceAspectPrototype.xml @@ -8,7 +8,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesInclude.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesInclude.xml index c6da3d6ea8..16293b388e 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesInclude.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesInclude.xml @@ -18,7 +18,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesJoinPointAspect.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesJoinPointAspect.xml index 44bc1872f6..462d8bcdc6 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesJoinPointAspect.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests-usesJoinPointAspect.xml @@ -7,7 +7,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java index e26835163f..2306641f0e 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,6 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeFalse; import java.lang.reflect.Method; @@ -41,11 +40,11 @@ import org.springframework.aop.config.AopConfigUtils; import org.springframework.aop.framework.ProxyConfig; import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor; -import org.springframework.beans.INestedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.NestedTestBean; +import org.springframework.tests.sample.beans.INestedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.NestedTestBean; import org.springframework.beans.PropertyValue; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.MethodInvokingFactoryBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests-context.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests-context.xml index d585ce9621..b35902d133 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests-context.xml @@ -6,7 +6,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java index 0c6b68d805..b5c5b065d5 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AtAspectJAfterThrowingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.*; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Aspect; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.aop.support.AopUtils; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -63,7 +63,7 @@ class ExceptionHandlingAspect { public IOException lastException; - @AfterThrowing(pointcut = "within(org.springframework.beans.ITestBean+)", throwing = "ex") + @AfterThrowing(pointcut = "within(org.springframework.tests.sample.beans.ITestBean+)", throwing = "ex") public void handleIOException(IOException ex) { handled++; lastException = ex; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-aspectj.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-aspectj.xml index 8b0975e8a9..759e4c8944 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-aspectj.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-aspectj.xml @@ -22,7 +22,7 @@ class="org.springframework.aop.aspectj.autoproxy.benchmark.TraceAspect" > - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-springAop.xml b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-springAop.xml index d6c4ccccee..453d22ccaf 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-springAop.xml +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests-springAop.xml @@ -31,7 +31,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java index a988324a00..c750e8ae57 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/benchmark/BenchmarkTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.StaticMethodMatcherPointcut; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.util.StopWatch; diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java index 24ce7bcf1f..ea160ca113 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/generic/AfterReturningGenericTypeMatchingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,10 @@ import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; -import test.beans.Employee; +import org.springframework.tests.sample.beans.Employee; /** * Tests ensuring that after-returning advice for generic parameters bound to diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-error.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-error.xml index 1761a3552e..7abc4287b7 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-error.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-error.xml @@ -15,11 +15,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-ok.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-ok.xml index 68681cf9fb..a68195265d 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-ok.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerAdviceTypeTests-ok.xml @@ -16,11 +16,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-error.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-error.xml index 2a83b2078a..f2b1e06472 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-error.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-error.xml @@ -12,11 +12,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-ok.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-ok.xml index 88cad34d9a..4e098059b5 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-ok.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerArgNamesTests-ok.xml @@ -12,11 +12,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests-context.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests-context.xml index 38f9d7b620..855bda381c 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests-context.xml @@ -19,11 +19,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java index 417512a71e..3632c97803 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.aop.framework.Advised; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; /** * @author Rob Harrop diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-error.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-error.xml index 1f84e8edac..9df36d7a38 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-error.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-error.xml @@ -11,11 +11,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-ok.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-ok.xml index 3fe28a8663..c923829099 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-ok.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerReturningTests-ok.xml @@ -11,11 +11,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests-context.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests-context.xml index 90ead2afe5..5fc378d78f 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests-context.xml @@ -19,11 +19,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java index 09d3dacd84..4896d143b2 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,20 @@ package org.springframework.aop.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import org.aspectj.lang.ProceedingJoinPoint; import org.junit.Before; import org.junit.Test; -import test.advice.CountingBeforeAdvice; - import org.springframework.aop.Advisor; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; - -import static org.junit.Assert.*; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Unit tests for aop namespace. diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-error.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-error.xml index 73ed03922c..1ddb6b9a00 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-error.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-error.xml @@ -11,11 +11,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-ok.xml b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-ok.xml index 8508052736..051d281260 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-ok.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerThrowingTests-ok.xml @@ -11,11 +11,11 @@ - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/config/PrototypeProxyTests-context.xml b/spring-context/src/test/java/org/springframework/aop/config/PrototypeProxyTests-context.xml index 0ca26dd953..b1327c8bdb 100644 --- a/spring-context/src/test/java/org/springframework/aop/config/PrototypeProxyTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/config/PrototypeProxyTests-context.xml @@ -5,22 +5,22 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> - + - + - + - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java index 51b63bd7d6..9fd4e9fa07 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.aop.framework; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; @@ -29,25 +37,13 @@ import java.util.List; import java.util.Map; import junit.framework.TestCase; + import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.junit.After; import org.junit.Before; import org.junit.Test; -import test.advice.CountingAfterReturningAdvice; -import test.advice.CountingBeforeAdvice; -import test.advice.MethodCounter; -import test.advice.MyThrowsHandler; -import test.interceptor.NopInterceptor; -import test.interceptor.SerializableNopInterceptor; -import test.interceptor.TimestampIntroductionInterceptor; -import test.mixin.LockMixin; -import test.mixin.LockMixinAdvisor; -import test.mixin.Lockable; -import test.mixin.LockedException; -import test.util.TimeStamped; - import org.springframework.aop.Advisor; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.DynamicIntroductionAdvice; @@ -66,15 +62,26 @@ import org.springframework.aop.support.Pointcuts; import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor; import org.springframework.aop.target.HotSwappableTargetSource; import org.springframework.aop.target.SingletonTargetSource; -import org.springframework.beans.IOther; -import org.springframework.beans.ITestBean; -import org.springframework.beans.Person; -import org.springframework.beans.SerializablePerson; -import org.springframework.beans.TestBean; +import org.springframework.tests.TimeStamped; +import org.springframework.tests.aop.advice.CountingAfterReturningAdvice; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.aop.advice.MethodCounter; +import org.springframework.tests.aop.advice.MyThrowsHandler; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.aop.interceptor.SerializableNopInterceptor; +import org.springframework.tests.aop.interceptor.TimestampIntroductionInterceptor; +import org.springframework.tests.sample.beans.IOther; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.SerializablePerson; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; import org.springframework.util.StopWatch; -import static org.junit.Assert.*; +import test.mixin.LockMixin; +import test.mixin.LockMixinAdvisor; +import test.mixin.Lockable; +import test.mixin.LockedException; /** * @author Rod Johnson diff --git a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java index d600115868..9b423759f7 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,30 +17,31 @@ package org.springframework.aop.framework; import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.Serializable; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; - import org.junit.Test; - -import org.springframework.cglib.core.CodeGenerationException; - import org.springframework.aop.ClassFilter; import org.springframework.aop.MethodMatcher; import org.springframework.aop.Pointcut; import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.DefaultPointcutAdvisor; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.cglib.core.CodeGenerationException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; -import test.advice.CountingBeforeAdvice; -import test.interceptor.NopInterceptor; import test.mixin.LockMixinAdvisor; /** diff --git a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java index 911e4d5154..77101f6cc9 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/JdkDynamicProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,9 @@ import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.interceptor.ExposeInvocationInterceptor; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.IOther; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.IOther; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @since 13.03.2003 diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-autowiring.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-autowiring.xml index 27e7988a7a..3cda6a7921 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-autowiring.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-autowiring.xml @@ -3,12 +3,12 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-context.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-context.xml index 8c0a313a7c..7675fe6e0e 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-context.xml @@ -4,19 +4,19 @@ - + custom 666 - + - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean - debugInterceptor + debugInterceptor - + - org.springframework.beans.ITestBean - + org.springframework.tests.sample.beans.ITestBean + global*,test - + - + - org.springframework.beans.ITestBean - + org.springframework.tests.sample.beans.ITestBean + false test - + - org.springframework.beans.ITestBean - + org.springframework.tests.sample.beans.ITestBean + false test - + true @@ -74,7 +74,7 @@ testCircleTarget1 - + custom 666 @@ -85,18 +85,18 @@ testCircleTarget2 - + custom 666 - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean pointcutForVoid test - + - + org.springframework.context.ApplicationListener debugInterceptor,global*,target2 @@ -137,10 +137,10 @@ - + - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean false @@ -155,7 +155,7 @@ - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean test.mixin.Lockable diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-double-targetsource.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-double-targetsource.xml index 795cea6418..dde1f91017 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-double-targetsource.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-double-targetsource.xml @@ -10,13 +10,13 @@ - + Eve - + Adam @@ -27,12 +27,12 @@ - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean countingBeforeAdvice,adamTargetSource @@ -42,7 +42,7 @@ - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean adam diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-frozen.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-frozen.xml index 45a4c2707b..d0f5a89896 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-frozen.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-frozen.xml @@ -4,25 +4,25 @@ - + custom 666 - - - - - - + + + - org.springframework.beans.ITestBean - - - debugInterceptor + > + org.springframework.tests.sample.beans.ITestBean + + + debugInterceptor true true - + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-inner-bean-target.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-inner-bean-target.xml index 92faa57c4f..e59244c49c 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-inner-bean-target.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-inner-bean-target.xml @@ -9,31 +9,30 @@ - + - + + > - + innerBeanTarget - + nopInterceptor - - - - - - - \ No newline at end of file + + + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-invalid.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-invalid.xml index de65fec0fe..fd46c5552f 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-invalid.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-invalid.xml @@ -5,7 +5,7 @@ - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean @@ -14,7 +14,7 @@ Must have target after *. --> - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean global* diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-notlast-targetsource.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-notlast-targetsource.xml index 92ef595c55..47cd14f94d 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-notlast-targetsource.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-notlast-targetsource.xml @@ -9,12 +9,12 @@ - + Adam - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean adam,countingBeforeAdvice diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-prototype.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-prototype.xml index f437df5edf..291385ce50 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-prototype.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-prototype.xml @@ -7,15 +7,15 @@ - + 10 - + 10 - + debugInterceptor,test diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-serialization.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-serialization.xml index 4131b85d78..396bfada12 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-serialization.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-serialization.xml @@ -6,35 +6,35 @@ --> - + - + - serializableNopInterceptor - org.springframework.beans.Person + serializableNopInterceptor + org.springframework.tests.sample.beans.Person - + serializableSingleton - + serializablePrototype - serializableNopInterceptor,prototypeTarget - org.springframework.beans.Person + serializableNopInterceptor,prototypeTarget + org.springframework.tests.sample.beans.Person false nopInterceptor - + - + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-targetsource.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-targetsource.xml index 4e9ab797ad..07f2825c1f 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-targetsource.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-targetsource.xml @@ -8,18 +8,18 @@ - + Adam - - + + - + - + - org.springframework.beans.ITestBean + class="org.springframework.aop.framework.ProxyFactoryBean"> + org.springframework.tests.sample.beans.ITestBean nopInterceptor,unsupportedInterceptor - - - + + + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-throws-advice.xml b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-throws-advice.xml index 1efb2ae305..036dac321f 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-throws-advice.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests-throws-advice.xml @@ -9,18 +9,18 @@ - - - - - - - + - + + + + + + + countingBeforeAdvice,nopInterceptor,throwsAdvice,target - + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java index b6e0f6853e..f55c1a41b3 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/ProxyFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,9 +47,6 @@ import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.DefaultIntroductionAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.aop.support.DynamicMethodMatcherPointcut; -import org.springframework.beans.ITestBean; -import org.springframework.beans.Person; -import org.springframework.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.FactoryBean; @@ -60,16 +57,19 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationListener; import org.springframework.context.TestListener; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.TimeStamped; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.aop.advice.MyThrowsHandler; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.aop.interceptor.TimestampIntroductionInterceptor; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.SideEffectBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.SerializationTestUtils; -import test.advice.CountingBeforeAdvice; -import test.advice.MyThrowsHandler; -import test.beans.SideEffectBean; -import test.interceptor.NopInterceptor; -import test.interceptor.TimestampIntroductionInterceptor; import test.mixin.Lockable; import test.mixin.LockedException; -import test.util.TimeStamped; /** * @since 13.03.2003 diff --git a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-with-bpp.xml b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-with-bpp.xml index 0aa3b46d64..a58e040b67 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-with-bpp.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-with-bpp.xml @@ -3,7 +3,7 @@ - + @@ -12,7 +12,7 @@ - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean simpleBeforeAdviceAdvisor,testBeanTarget diff --git a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-without-bpp.xml b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-without-bpp.xml index 3671800330..69bd476f3b 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-without-bpp.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests-without-bpp.xml @@ -3,7 +3,7 @@ - + @@ -12,7 +12,7 @@ - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean simpleBeforeAdviceAdvisor,testBeanTarget diff --git a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java index 57e8de8112..e708c9f179 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import org.junit.Test; import org.springframework.aop.Advisor; import org.springframework.aop.BeforeAdvice; import org.springframework.aop.framework.Advised; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests-common-interceptors.xml b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests-common-interceptors.xml index 286f8c840d..c64c7e6ef7 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests-common-interceptors.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests-common-interceptors.xml @@ -20,7 +20,7 @@ - + - + Rod - + Rod - + Rod diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java index 83598caf9b..bf1fc8b5a7 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ package org.springframework.aop.framework.autoproxy; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; @@ -29,13 +31,13 @@ import org.springframework.aop.target.CommonsPoolTargetSource; import org.springframework.aop.target.LazyInitTargetSource; import org.springframework.aop.target.PrototypeTargetSource; import org.springframework.aop.target.ThreadLocalTargetSource; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.CountingTestBean; +import org.springframework.tests.sample.beans.ITestBean; -import test.advice.CountingBeforeAdvice; -import test.interceptor.NopInterceptor; import test.mixin.Lockable; /** @@ -204,18 +206,6 @@ public final class AdvisorAutoProxyCreatorTests { } - -class CountingTestBean extends TestBean { - - public static int count = 0; - - public CountingTestBean() { - count++; - } - -} - - class SelectivePrototypeTargetSourceCreator extends AbstractBeanFactoryBasedTargetSourceCreator { @Override diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java index 4019d568d0..d9a838ee2a 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/AutoProxyCreatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +24,11 @@ import org.junit.Test; import org.springframework.aop.TargetSource; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; -import org.springframework.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.DummyFactory; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.RootBeanDefinition; diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests-context.xml b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests-context.xml index 53d945697e..d53272f0d5 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests-context.xml @@ -24,6 +24,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java index 11805c6d5b..4921629248 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorInitTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import java.lang.reflect.Method; import org.junit.Test; import org.springframework.aop.MethodBeforeAdvice; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.ClassPathXmlApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests-context.xml b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests-context.xml index 0f4b265b72..c9727ea856 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests-context.xml +++ b/spring-context/src/test/java/org/springframework/aop/framework/autoproxy/BeanNameAutoProxyCreatorTests-context.xml @@ -59,7 +59,7 @@ - + - + - + prototypePerson diff --git a/spring-context/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceTests.java b/spring-context/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceTests.java index c0a695c452..5ec8db261f 100644 --- a/spring-context/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceTests.java +++ b/spring-context/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,15 +28,15 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.aop.framework.Advised; -import org.springframework.beans.Person; -import org.springframework.beans.SerializablePerson; +import org.springframework.tests.sample.beans.Person; +import org.springframework.tests.sample.beans.SerializablePerson; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.util.SerializationTestUtils; -import test.beans.SideEffectBean; +import org.springframework.tests.sample.beans.SideEffectBean; /** * Tests for pooling invoker interceptor. diff --git a/spring-context/src/test/java/org/springframework/beans/Colour.java b/spring-context/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-context/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index c5360de531..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/FieldAccessBean.java b/spring-context/src/test/java/org/springframework/beans/FieldAccessBean.java deleted file mode 100644 index 61f911902c..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/FieldAccessBean.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * @author Juergen Hoeller - * @since 07.03.2006 - */ -public class FieldAccessBean { - - public String name; - - protected int age; - - private TestBean spouse; - - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - public TestBean getSpouse() { - return spouse; - } - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-context/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/IOther.java b/spring-context/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/ITestBean.java b/spring-context/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-context/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index 9f90cf15bb..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList<>(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet<>(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap<>(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList<>(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-context/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/Person.java b/spring-context/src/test/java/org/springframework/beans/Person.java deleted file mode 100644 index 7c66f4b451..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/Person.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * - * @author Rod Johnson - */ -public interface Person { - - String getName(); - void setName(String name); - int getAge(); - void setAge(int i); - - /** - * Test for non-property method matching. - * If the parameter is a Throwable, it will be thrown rather than - * returned. - */ - Object echo(Object o) throws Throwable; -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/SerializablePerson.java b/spring-context/src/test/java/org/springframework/beans/SerializablePerson.java deleted file mode 100644 index dbe365f493..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/SerializablePerson.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.util.ObjectUtils; - -/** - * Serializable implementation of the Person interface. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class SerializablePerson implements Person, Serializable { - - private String name; - private int age; - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public Object echo(Object o) throws Throwable { - if (o instanceof Throwable) { - throw (Throwable) o; - } - return o; - } - - public boolean equals(Object other) { - if (!(other instanceof SerializablePerson)) { - return false; - } - SerializablePerson p = (SerializablePerson) other; - return p.age == age && ObjectUtils.nullSafeEquals(name, p.name); - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java deleted file mode 100644 index d6911ee72f..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import java.beans.PropertyEditorSupport; -import java.util.StringTokenizer; - -import junit.framework.TestCase; - -import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyBatchUpdateException; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; - -/** - * Subclasses must implement setUp() to initialize bean factory - * and any other variables they need. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractBeanFactoryTests extends TestCase { - - protected abstract BeanFactory getBeanFactory(); - - /** - * Roderick beans inherits from rod, overriding name only. - */ - public void testInheritance() { - assertTrue(getBeanFactory().containsBean("rod")); - assertTrue(getBeanFactory().containsBean("roderick")); - TestBean rod = (TestBean) getBeanFactory().getBean("rod"); - TestBean roderick = (TestBean) getBeanFactory().getBean("roderick"); - assertTrue("not == ", rod != roderick); - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick")); - assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge()); - } - - public void testGetBeanWithNullArg() { - try { - getBeanFactory().getBean((String) null); - fail("Can't get null bean"); - } - catch (IllegalArgumentException ex) { - // OK - } - } - - /** - * Test that InitializingBean objects receive the afterPropertiesSet() callback - */ - public void testInitializingBeanCallback() { - MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized"); - // The dummy business method will throw an exception if the - // afterPropertiesSet() callback wasn't invoked - mbi.businessMethod(); - } - - /** - * Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the - * afterPropertiesSet() callback before BeanFactoryAware callbacks - */ - public void testLifecycleCallbacks() { - LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle"); - assertEquals("lifecycle", lb.getBeanName()); - // The dummy business method will throw an exception if the - // necessary callbacks weren't invoked in the right order. - lb.businessMethod(); - assertTrue("Not destroyed", !lb.isDestroyed()); - } - - public void testFindsValidInstance() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - TestBean rod = (TestBean) o; - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testGetInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetInstanceByNonmatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass()); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testGetSharedInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetSharedInstanceByMatchingClassNoCatch() { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - - public void testGetSharedInstanceByNonmatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testSharedInstancesAreEqual() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean1 is a TestBean", o instanceof TestBean); - Object o1 = getBeanFactory().getBean("rod"); - assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean); - assertTrue("Object equals applies", o == o1); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testPrototypeInstancesAreIndependent() { - TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy"); - TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy"); - assertTrue("ref equal DOES NOT apply", tb1 != tb2); - assertTrue("object equal true", tb1.equals(tb2)); - tb1.setAge(1); - tb2.setAge(2); - assertTrue("1 age independent = 1", tb1.getAge() == 1); - assertTrue("2 age independent = 2", tb2.getAge() == 2); - assertTrue("object equal now false", !tb1.equals(tb2)); - } - - public void testNotThere() { - assertFalse(getBeanFactory().containsBean("Mr Squiggle")); - try { - Object o = getBeanFactory().getBean("Mr Squiggle"); - fail("Can't find missing bean"); - } - catch (BeansException ex) { - //ex.printStackTrace(); - //fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testValidEmpty() { - try { - Object o = getBeanFactory().getBean("validEmpty"); - assertTrue("validEmpty bean is a TestBean", o instanceof TestBean); - TestBean ve = (TestBean) o; - assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null); - } - catch (BeansException ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on valid empty"); - } - } - - public void xtestTypeMismatch() { - try { - Object o = getBeanFactory().getBean("typeMismatch"); - fail("Shouldn't succeed with type mismatch"); - } - catch (BeanCreationException wex) { - assertEquals("typeMismatch", wex.getBeanName()); - assertTrue(wex.getCause() instanceof PropertyBatchUpdateException); - PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause(); - // Further tests - assertTrue("Has one error ", ex.getExceptionCount() == 1); - assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null); - assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x")); - } - } - - public void testGrandparentDefinitionFoundInBeanFactory() throws Exception { - TestBean dad = (TestBean) getBeanFactory().getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testFactorySingleton() throws Exception { - assertTrue(getBeanFactory().isSingleton("&singletonFactory")); - assertTrue(getBeanFactory().isSingleton("singletonFactory")); - TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME)); - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton references ==", tb == tb2); - assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null); - } - - public void testFactoryPrototype() throws Exception { - assertTrue(getBeanFactory().isSingleton("&prototypeFactory")); - assertFalse(getBeanFactory().isSingleton("prototypeFactory")); - TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME)); - TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue("Prototype references !=", tb != tb2); - } - - /** - * Check that we can get the factory bean itself. - * This is only possible if we're dealing with a factory - * @throws Exception - */ - public void testGetFactoryItself() throws Exception { - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue(factory != null); - } - - /** - * Check that afterPropertiesSet gets called on factory - * @throws Exception - */ - public void testFactoryIsInitialized() throws Exception { - TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized()); - } - - /** - * It should be illegal to dereference a normal bean - * as a factory - */ - public void testRejectsFactoryGetOnNormalBean() { - try { - getBeanFactory().getBean("&rod"); - fail("Shouldn't permit factory get on normal bean"); - } - catch (BeanIsNotAFactoryException ex) { - // Ok - } - } - - // TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory) - // and rename this class - public void testAliasing() { - BeanFactory bf = getBeanFactory(); - if (!(bf instanceof ConfigurableBeanFactory)) { - return; - } - ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf; - - String alias = "rods alias"; - try { - cbf.getBean(alias); - fail("Shouldn't permit factory get on normal bean"); - } - catch (NoSuchBeanDefinitionException ex) { - // Ok - assertTrue(alias.equals(ex.getBeanName())); - } - - // Create alias - cbf.registerAlias("rod", alias); - Object rod = getBeanFactory().getBean("rod"); - Object aliasRod = getBeanFactory().getBean(alias); - assertTrue(rod == aliasRod); - } - - - public static class TestBeanEditor extends PropertyEditorSupport { - - @Override - public void setAsText(String text) { - TestBean tb = new TestBean(); - StringTokenizer st = new StringTokenizer(text, "_"); - tb.setName(st.nextToken()); - tb.setAge(Integer.parseInt(st.nextToken())); - setValue(tb); - } - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java deleted file mode 100644 index 855f23af39..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.TestBean; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests { - - /** Subclasses must initialize this */ - protected ListableBeanFactory getListableBeanFactory() { - BeanFactory bf = getBeanFactory(); - if (!(bf instanceof ListableBeanFactory)) { - throw new IllegalStateException("ListableBeanFactory required"); - } - return (ListableBeanFactory) bf; - } - - /** - * Subclasses can override this. - */ - public void testCount() { - assertCount(13); - } - - protected final void assertCount(int count) { - String[] defnames = getListableBeanFactory().getBeanDefinitionNames(); - assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count); - } - - public void assertTestBeanCount(int count) { - String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); - assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " + - defNames.length, defNames.length == count); - - int countIncludingFactoryBeans = count + 2; - String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true); - assertTrue("We should have " + countIncludingFactoryBeans + - " beans for class org.springframework.beans.TestBean, not " + names.length, - names.length == countIncludingFactoryBeans); - } - - public void testGetDefinitionsForNoSuchClass() { - String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class); - assertTrue("No string definitions", defnames.length == 0); - } - - /** - * Check that count refers to factory class, not bean class. (We don't know - * what type factories may return, and it may even change over time.) - */ - public void testGetCountForFactoryClass() { - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); - - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); - } - - public void testContainsBeanDefinition() { - assertTrue(getListableBeanFactory().containsBeanDefinition("rod")); - assertTrue(getListableBeanFactory().containsBeanDefinition("roderick")); - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/LifecycleBean.java b/spring-context/src/test/java/org/springframework/beans/factory/LifecycleBean.java deleted file mode 100644 index 013a65a0e4..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/LifecycleBean.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; - -/** - * Simple test of BeanFactory initialization and lifecycle callbacks. - * - * @author Rod Johnson - * @author Colin Sampaleanu - * @since 12.03.2003 - */ -public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { - - protected boolean initMethodDeclared = false; - - protected String beanName; - - protected BeanFactory owningFactory; - - protected boolean postProcessedBeforeInit; - - protected boolean inited; - - protected boolean initedViaDeclaredInitMethod; - - protected boolean postProcessedAfterInit; - - protected boolean destroyed; - - - public void setInitMethodDeclared(boolean initMethodDeclared) { - this.initMethodDeclared = initMethodDeclared; - } - - public boolean isInitMethodDeclared() { - return initMethodDeclared; - } - - @Override - public void setBeanName(String name) { - this.beanName = name; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.owningFactory = beanFactory; - } - - public void postProcessBeforeInit() { - if (this.inited || this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet"); - } - if (this.postProcessedBeforeInit) { - throw new RuntimeException("Factory called postProcessBeforeInit twice"); - } - this.postProcessedBeforeInit = true; - } - - @Override - public void afterPropertiesSet() { - if (this.owningFactory == null) { - throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean"); - } - if (!this.postProcessedBeforeInit) { - throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean"); - } - if (this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet"); - } - if (this.inited) { - throw new RuntimeException("Factory called afterPropertiesSet twice"); - } - this.inited = true; - } - - public void declaredInitMethod() { - if (!this.inited) { - throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method"); - } - - if (this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called declared init method twice"); - } - this.initedViaDeclaredInitMethod = true; - } - - public void postProcessAfterInit() { - if (!this.inited) { - throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet"); - } - if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method"); - } - if (this.postProcessedAfterInit) { - throw new RuntimeException("Factory called postProcessAfterInit twice"); - } - this.postProcessedAfterInit = true; - } - - /** - * Dummy business method that will fail unless the factory - * managed the bean's lifecycle correctly - */ - public void businessMethod() { - if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) || - !this.postProcessedAfterInit) { - throw new RuntimeException("Factory didn't initialize lifecycle object correctly"); - } - } - - @Override - public void destroy() { - if (this.destroyed) { - throw new IllegalStateException("Already destroyed"); - } - this.destroyed = true; - } - - public boolean isDestroyed() { - return destroyed; - } - - - public static class PostProcessor implements BeanPostProcessor { - - @Override - public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessBeforeInit(); - } - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessAfterInit(); - } - return bean; - } - } - -} \ No newline at end of file diff --git a/spring-context/src/test/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocatorTests.java b/spring-context/src/test/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocatorTests.java deleted file mode 100644 index 4b4d698056..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/access/SingletonBeanFactoryLocatorTests.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.access; - -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.util.ClassUtils; - -/** - * @author Colin Sampaleanu - * @author Chris Beams - */ -public class SingletonBeanFactoryLocatorTests { - - @Test - public void testBasicFunctionality() { - SingletonBeanFactoryLocator facLoc = new SingletonBeanFactoryLocator( - "classpath*:" + ClassUtils.addResourcePathToPackagePath(getClass(), "ref1.xml")); - - basicFunctionalityTest(facLoc); - } - - /** - * Worker method so subclass can use it too. - */ - protected void basicFunctionalityTest(SingletonBeanFactoryLocator facLoc) { - BeanFactoryReference bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort"); - BeanFactory fac = bfr.getFactory(); - BeanFactoryReference bfr2 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr2.getFactory(); - // verify that the same instance is returned - TestBean tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("beans1.bean1")); - tb.setName("was beans1.bean1"); - BeanFactoryReference bfr3 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr3.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - BeanFactoryReference bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias"); - fac = bfr4.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - // Now verify that we can call release in any order. - // Unfortunately this doesn't validate complete release after the last one. - bfr2.release(); - bfr3.release(); - bfr.release(); - bfr4.release(); - } - - /** - * This test can run multiple times, but due to static keyed lookup of the locators, - * 2nd and subsequent calls will actuall get back same locator instance. This is not - * an issue really, since the contained beanfactories will still be loaded and released. - */ - @Test - public void testGetInstance() { - // Try with and without 'classpath*:' prefix, and with 'classpath:' prefix. - BeanFactoryLocator facLoc = SingletonBeanFactoryLocator.getInstance( - ClassUtils.addResourcePathToPackagePath(getClass(), "ref1.xml")); - getInstanceTest1(facLoc); - - facLoc = SingletonBeanFactoryLocator.getInstance( - "classpath*:/" + ClassUtils.addResourcePathToPackagePath(getClass(), "ref1.xml")); - getInstanceTest2(facLoc); - - // This will actually get another locator instance, as the key is the resource name. - facLoc = SingletonBeanFactoryLocator.getInstance( - "classpath:" + ClassUtils.addResourcePathToPackagePath(getClass(), "ref1.xml")); - getInstanceTest3(facLoc); - - } - - /** - * Worker method so subclass can use it too - */ - protected void getInstanceTest1(BeanFactoryLocator facLoc) { - BeanFactoryReference bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort"); - BeanFactory fac = bfr.getFactory(); - BeanFactoryReference bfr2 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr2.getFactory(); - // verify that the same instance is returned - TestBean tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("beans1.bean1")); - tb.setName("was beans1.bean1"); - BeanFactoryReference bfr3 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr3.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - - BeanFactoryReference bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias"); - fac = bfr4.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - - bfr.release(); - bfr3.release(); - bfr2.release(); - bfr4.release(); - } - - /** - * Worker method so subclass can use it too - */ - protected void getInstanceTest2(BeanFactoryLocator facLoc) { - BeanFactoryReference bfr; - BeanFactory fac; - BeanFactoryReference bfr2; - TestBean tb; - BeanFactoryReference bfr3; - BeanFactoryReference bfr4; - bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort"); - fac = bfr.getFactory(); - bfr2 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr2.getFactory(); - // verify that the same instance is returned - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("beans1.bean1")); - tb.setName("was beans1.bean1"); - bfr3 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr3.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias"); - fac = bfr4.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - bfr.release(); - bfr2.release(); - bfr4.release(); - bfr3.release(); - } - - /** - * Worker method so subclass can use it too - */ - protected void getInstanceTest3(BeanFactoryLocator facLoc) { - BeanFactoryReference bfr; - BeanFactory fac; - BeanFactoryReference bfr2; - TestBean tb; - BeanFactoryReference bfr3; - BeanFactoryReference bfr4; - bfr = facLoc.useBeanFactory("a.qualified.name.of.some.sort"); - fac = bfr.getFactory(); - bfr2 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr2.getFactory(); - // verify that the same instance is returned - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("beans1.bean1")); - tb.setName("was beans1.bean1"); - bfr3 = facLoc.useBeanFactory("another.qualified.name"); - fac = bfr3.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - bfr4 = facLoc.useBeanFactory("a.qualified.name.which.is.an.alias"); - fac = bfr4.getFactory(); - tb = (TestBean) fac.getBean("beans1.bean1"); - assertTrue(tb.getName().equals("was beans1.bean1")); - bfr4.release(); - bfr3.release(); - bfr2.release(); - bfr.release(); - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/access/TestBean.java b/spring-context/src/test/java/org/springframework/beans/factory/access/TestBean.java deleted file mode 100644 index f54299a03f..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/access/TestBean.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.access; - -import java.util.List; - -/** - * Scrap bean for use in tests. - * - * @author Colin Sampaleanu - */ -public class TestBean { - - private String name; - - private List list; - - private Object objRef; - - /** - * @return Returns the name. - */ - public String getName() { - return name; - } - - /** - * @param name The name to set. - */ - public void setName(String name) { - this.name = name; - } - - /** - * @return Returns the list. - */ - public List getList() { - return list; - } - - /** - * @param list The list to set. - */ - public void setList(List list) { - this.list = list; - } - - /** - * @return Returns the object. - */ - public Object getObjRef() { - return objRef; - } - - /** - * @param object The object to set. - */ - public void setObjRef(Object object) { - this.objRef = object; - } -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/access/ref1.xml b/spring-context/src/test/java/org/springframework/beans/factory/access/ref1.xml deleted file mode 100644 index 2dde7a31b3..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/access/ref1.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/spring-context/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java b/spring-context/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java deleted file mode 100644 index d42adc1daf..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.parsing; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -/** - * @author Rob Harrop - * @author Juergen Hoeller - */ -public class CollectingReaderEventListener implements ReaderEventListener { - - private final List defaults = new LinkedList(); - - private final Map componentDefinitions = new LinkedHashMap<>(8); - - private final Map> aliasMap = new LinkedHashMap<>(8); - - private final List imports = new LinkedList(); - - - @Override - public void defaultsRegistered(DefaultsDefinition defaultsDefinition) { - this.defaults.add(defaultsDefinition); - } - - public List getDefaults() { - return Collections.unmodifiableList(this.defaults); - } - - @Override - public void componentRegistered(ComponentDefinition componentDefinition) { - this.componentDefinitions.put(componentDefinition.getName(), componentDefinition); - } - - public ComponentDefinition getComponentDefinition(String name) { - return this.componentDefinitions.get(name); - } - - public ComponentDefinition[] getComponentDefinitions() { - Collection collection = this.componentDefinitions.values(); - return collection.toArray(new ComponentDefinition[collection.size()]); - } - - @Override - public void aliasRegistered(AliasDefinition aliasDefinition) { - List aliases = this.aliasMap.get(aliasDefinition.getBeanName()); - if(aliases == null) { - aliases = new ArrayList(); - this.aliasMap.put(aliasDefinition.getBeanName(), aliases); - } - aliases.add(aliasDefinition); - } - - public List getAliases(String beanName) { - List aliases = this.aliasMap.get(beanName); - return aliases == null ? null : Collections.unmodifiableList(aliases); - } - - @Override - public void importProcessed(ImportDefinition importDefinition) { - this.imports.add(importDefinition); - } - - public List getImports() { - return Collections.unmodifiableList(this.imports); - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java deleted file mode 100644 index 28c3bffa8f..0000000000 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/DependenciesBean.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.xml; - -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; - -/** - * Simple bean used to test dependency checking. - * - * Note: would be defined within {@link XmlBeanFactoryTestTypes}, but must be a public type - * in order to satisfy test dependencies. - * - * @author Rod Johnson - * @author Chris Beams - * @since 04.09.2003 - */ -public final class DependenciesBean implements BeanFactoryAware { - - private int age; - - private String name; - - private TestBean spouse; - - private BeanFactory beanFactory; - - - public void setAge(int age) { - this.age = age; - } - - public int getAge() { - return age; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setSpouse(TestBean spouse) { - this.spouse = spouse; - } - - public TestBean getSpouse() { - return spouse; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - -} diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests-context.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests-context.xml index 017af48520..9eaf910d08 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests-context.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests-context.xml @@ -22,7 +22,7 @@ interceptor - + Jenny 30 diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java index ed9fbbde83..96e2ab404a 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/LookupMethodWrappedByCglibProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import org.springframework.aop.interceptor.DebugInterceptor; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java index b1e6c818f0..c21ee9078f 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/SimplePropertyNamespaceHandlerWithExpressionLanguageTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.beans.factory.xml; import static org.junit.Assert.assertEquals; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java index 98f0450564..6f68b6bf60 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,14 +27,14 @@ import java.util.Set; import javax.sql.DataSource; import org.springframework.beans.BeansException; -import org.springframework.beans.ITestBean; -import org.springframework.beans.IndexedTestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.DummyFactory; +import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.support.MethodReplacer; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-autowire.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-autowire.xml index 4fcad300ba..43510574ba 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-autowire.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-autowire.xml @@ -3,22 +3,22 @@ - - - - @@ -38,12 +38,12 @@ - - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-child.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-child.xml index 654e76e7fb..fc90f7905c 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-child.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-child.xml @@ -8,13 +8,13 @@ - override - override @@ -42,7 +42,7 @@ - + myname diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-collections.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-collections.xml index 9a735571d8..7729dbc788 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-collections.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-collections.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> - + Jenny 30 @@ -11,8 +11,8 @@ - - + + Simple bean, without any collections. @@ -22,8 +22,8 @@ 27 - - + + Rod 32 @@ -34,8 +34,8 @@ - - + + Jenny 30 @@ -44,12 +44,12 @@ - + David 27 - + Rod 32 @@ -63,7 +63,7 @@ - + loner 26 @@ -73,8 +73,8 @@ - - + + @@ -84,7 +84,7 @@ - + @@ -97,26 +97,26 @@ - + verbose - - + + - + - + - - + + @@ -126,7 +126,7 @@ - + @@ -158,7 +158,7 @@ - + @@ -167,7 +167,7 @@ - + @@ -198,8 +198,8 @@ - - + + @@ -207,7 +207,7 @@ - + bar @@ -217,15 +217,15 @@ - + - - - + + + bar @@ -233,8 +233,8 @@ - - + + @@ -243,7 +243,7 @@ - + one @@ -251,8 +251,8 @@ - - + + java.lang.String @@ -260,8 +260,8 @@ - - + + 0 diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-complexFactoryCircle.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-complexFactoryCircle.xml index 85eb3620b0..8370424f73 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-complexFactoryCircle.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-complexFactoryCircle.xml @@ -11,16 +11,16 @@ - + - + - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorArg.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorArg.xml index bc4f87d63a..d500c48881 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorArg.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorArg.xml @@ -13,7 +13,7 @@ - + @@ -117,7 +117,7 @@ - + Kerry1 @@ -126,7 +126,7 @@ - + Kerry2 @@ -135,7 +135,7 @@ - + /test @@ -187,13 +187,13 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorOverrides.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorOverrides.xml index ea061046ce..d703fddd21 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorOverrides.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-constructorOverrides.xml @@ -18,7 +18,7 @@ - Jenny 30 diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultAutowire.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultAutowire.xml index 0094234b09..3815538559 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultAutowire.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultAutowire.xml @@ -3,19 +3,19 @@ - + - + - + - + Kerry diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultLazyInit.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultLazyInit.xml index 5021766b1c..3451c1b37c 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultLazyInit.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-defaultLazyInit.xml @@ -15,6 +15,6 @@ destroy-method="customDestroy" /> - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-delegationOverrides.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-delegationOverrides.xml index feb3bea499..10ae8ae09f 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-delegationOverrides.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-delegationOverrides.xml @@ -58,7 +58,7 @@ - Jenny 30 @@ -68,7 +68,7 @@ - Simple bean, without any collections. diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-factoryCircle.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-factoryCircle.xml index f94371ee0c..86da8d595d 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-factoryCircle.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-factoryCircle.xml @@ -3,7 +3,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-initializers.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-initializers.xml index 1a6eb55332..0628149017 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-initializers.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-initializers.xml @@ -11,7 +11,7 @@ - - - - + + + Jenny 30 @@ -12,9 +12,8 @@ - + - - - \ No newline at end of file + + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-invalidOverridesNoSuchMethod.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-invalidOverridesNoSuchMethod.xml index e8b85a509a..cd232df3c0 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-invalidOverridesNoSuchMethod.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-invalidOverridesNoSuchMethod.xml @@ -11,7 +11,7 @@ - + Jenny 30 diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-localCollectionsUsingXsd.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-localCollectionsUsingXsd.xml index da6d7405eb..2e49f71a54 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-localCollectionsUsingXsd.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-localCollectionsUsingXsd.xml @@ -12,7 +12,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-overrides.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-overrides.xml index bf0849bc98..0a92c7426d 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-overrides.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-overrides.xml @@ -35,32 +35,32 @@ - + Jenny 30 - + - + Jenny 30 - + - + - + Simple bean, without any collections. @@ -71,12 +71,12 @@ 27 - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-parent.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-parent.xml index 98f2309673..f575bcb44a 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-parent.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-parent.xml @@ -3,7 +3,7 @@ - + parent 1 @@ -13,11 +13,11 @@ 1 - + parent 2 - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-reftypes.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-reftypes.xml index c8adc19bb3..f8e3280906 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-reftypes.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-reftypes.xml @@ -1,102 +1,102 @@ - - + + Jenny 30 - - + + - - + + Andrew 36 - + - - + + Georgia 33 - + - + - + - + - + - + - + - + - + - + outer 0 - + hasInner 5 - + inner1 6 - + inner2 7 - - + + inner5 6 @@ -105,7 +105,7 @@ - + inner3 8 @@ -120,32 +120,32 @@ - + - + inner1 6 - + hasInner 5 - + inner1 6 - + inner2 7 - - + + inner5 6 @@ -153,11 +153,11 @@ - + - + inner3 8 @@ -173,9 +173,9 @@ - + - + inner1 6 diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resource.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resource.xml index 3386242887..9eb0813411 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resource.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resource.xml @@ -5,7 +5,7 @@ - + classpath:org/springframework/beans/factory/xml/test.properties diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resourceImport.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resourceImport.xml index e5515885ef..31fa7a16ba 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resourceImport.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-resourceImport.xml @@ -3,7 +3,7 @@ - + classpath:org/springframework/beans/factory/xml/test.properties diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedAllDepCheck.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedAllDepCheck.xml index 4b315b7582..daa269998e 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedAllDepCheck.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedAllDepCheck.xml @@ -3,14 +3,14 @@ - 33 Rod - diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedObjectDepCheck.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedObjectDepCheck.xml index 8c1d0d3f37..65fbd833c9 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedObjectDepCheck.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedObjectDepCheck.xml @@ -3,11 +3,11 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedSimpleDepCheck.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedSimpleDepCheck.xml index 9298119502..9088b962e0 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedSimpleDepCheck.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-satisfiedSimpleDepCheck.xml @@ -3,7 +3,7 @@ - 33 Rod diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNameInAlias.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNameInAlias.xml index cc049ed23c..393028d4f1 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNameInAlias.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNameInAlias.xml @@ -3,8 +3,8 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNames.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNames.xml index e991af7167..90de544437 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNames.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-testWithDuplicateNames.xml @@ -3,8 +3,8 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingObjects.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingObjects.xml index 19faed7925..a771266aa9 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingObjects.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingObjects.xml @@ -3,7 +3,7 @@ - 33 Rod diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingSimple.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingSimple.xml index df21ad7262..8cd2e72569 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingSimple.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedAllDepCheckMissingSimple.xml @@ -3,13 +3,13 @@ - tony --> - diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedObjectDepCheck.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedObjectDepCheck.xml index f18e9e77c2..a96c4d303d 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedObjectDepCheck.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedObjectDepCheck.xml @@ -3,7 +3,7 @@ - diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedSimpleDepCheck.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedSimpleDepCheck.xml index 8463f132a1..4968b12b3a 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedSimpleDepCheck.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests-unsatisfiedSimpleDepCheck.xml @@ -3,7 +3,7 @@ - diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java index 3eed0d7cfc..b4e6a07538 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,13 +42,8 @@ import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeansException; -import org.springframework.beans.DerivedTestBean; import org.springframework.beans.FatalBeanException; -import org.springframework.beans.ITestBean; -import org.springframework.beans.IndexedTestBean; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.ResourceTestBean; -import org.springframework.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; @@ -56,7 +51,6 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanIsAbstractException; import org.springframework.beans.factory.CannotLoadBeanClassException; import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.DummyFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.UnsatisfiedDependencyException; @@ -69,6 +63,13 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.UrlResource; import org.springframework.core.io.support.EncodedResource; +import org.springframework.tests.sample.beans.DependenciesBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.ResourceTestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.util.FileCopyUtils; import org.springframework.util.SerializationTestUtils; import org.springframework.util.StopWatch; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests-context.xml b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests-context.xml index 1fbd833086..17c9c7e8f5 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests-context.xml +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests-context.xml @@ -10,11 +10,11 @@ - + - + @@ -24,14 +24,14 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java index 7a52f76eda..68accbae1d 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/support/CustomNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,31 +16,27 @@ package org.springframework.beans.factory.xml.support; -import java.io.IOException; import static java.lang.String.format; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.xml.sax.InputSource; -import test.interceptor.NopInterceptor; - import org.springframework.aop.Advisor; import org.springframework.aop.config.AbstractInterceptorDrivenBeanDefinitionDecorator; import org.springframework.aop.framework.Advised; import org.springframework.aop.interceptor.DebugInterceptor; import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeanInstantiationException; -import org.springframework.beans.ITestBean; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; @@ -60,6 +56,13 @@ import org.springframework.context.ApplicationListener; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.InputSource; /** * Unit tests for custom XML namespace handler implementations. diff --git a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java index a720743520..6f407fb24e 100644 --- a/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/AbstractApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ package org.springframework.context; import java.util.Locale; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.AbstractListableBeanFactoryTests; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.LifecycleBean; +import org.springframework.beans.factory.xml.AbstractListableBeanFactoryTests; +import org.springframework.tests.sample.beans.LifecycleBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson diff --git a/spring-context/src/test/java/org/springframework/context/LifecycleContextBean.java b/spring-context/src/test/java/org/springframework/context/LifecycleContextBean.java index 69fea0435d..96f39c3296 100644 --- a/spring-context/src/test/java/org/springframework/context/LifecycleContextBean.java +++ b/spring-context/src/test/java/org/springframework/context/LifecycleContextBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.context; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.LifecycleBean; +import org.springframework.tests.sample.beans.LifecycleBean; /** * Simple bean to test ApplicationContext lifecycle methods for beans diff --git a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-collections.xml b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-collections.xml index 30b7c590c8..81770ea423 100644 --- a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-collections.xml +++ b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-collections.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> - + Jenny 30 @@ -11,8 +11,8 @@ - - + + Simple bean, without any collections. @@ -22,8 +22,8 @@ 27 - - + + Rod 32 @@ -34,8 +34,8 @@ - - + + Jenny 30 @@ -44,12 +44,12 @@ - + David 27 - + Rod 32 @@ -63,7 +63,7 @@ - + loner 26 @@ -73,8 +73,8 @@ - - + + @@ -84,7 +84,7 @@ - + @@ -97,26 +97,26 @@ - + verbose - - + + - + - + - - + + @@ -126,7 +126,7 @@ - + @@ -158,7 +158,7 @@ - + @@ -167,7 +167,7 @@ - + @@ -198,8 +198,8 @@ - - + + @@ -207,7 +207,7 @@ - + bar @@ -217,15 +217,15 @@ - + - - - + + + bar @@ -233,8 +233,8 @@ - - + + @@ -243,7 +243,7 @@ - + one @@ -251,8 +251,8 @@ - - + + java.lang.String @@ -260,8 +260,8 @@ - - + + 0 diff --git a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-parent.xml b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-parent.xml index 6f5675fffd..99d732a164 100644 --- a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-parent.xml +++ b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests-parent.xml @@ -3,7 +3,7 @@ - + parent 1 @@ -13,11 +13,11 @@ 1 - + parent 2 - + diff --git a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java index e87e602378..8001716e48 100644 --- a/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java +++ b/spring-context/src/test/java/org/springframework/context/access/ContextJndiBeanFactoryLocatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.access.BootstrapException; import org.springframework.context.ApplicationContext; -import org.springframework.mock.jndi.SimpleNamingContextBuilder; +import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; /** * @author Colin Sampaleanu diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java index bfbc2c9ef6..e3ed03301f 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AbstractCircularImportDetectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ConfigurationClassParser; import org.springframework.context.annotation.Import; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java index d35b5396fd..0a9cfdf655 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Test; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Required; import org.springframework.beans.factory.config.RuntimeBeanReference; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java index 50b8cd2045..55d08669d0 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathBeanDefinitionScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.aspectj.lang.annotation.Aspect; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.config.BeanDefinition; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java index 1e4deb22f0..4475d87e4a 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ClassPathFactoryBeanDefinitionScannerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,10 +20,10 @@ import junit.framework.TestCase; import org.springframework.aop.scope.ScopedObject; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.TestBean; +import org.springframework.tests.context.SimpleMapScope; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.config.SimpleMapScope; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation4.DependencyBean; import org.springframework.context.annotation4.FactoryMethodComponent; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java index 62aa1411a3..331a2f0af2 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,11 @@ import javax.ejb.EJB; import org.junit.Test; import org.springframework.beans.BeansException; -import org.springframework.beans.INestedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.NestedTestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; +import org.springframework.tests.sample.beans.INestedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.NestedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -41,7 +42,6 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.GenericApplicationContext; import org.springframework.jndi.support.SimpleJndiBeanFactory; -import org.springframework.mock.jndi.ExpectedLookupTemplate; import org.springframework.util.SerializationTestUtils; import static org.junit.Assert.*; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java index 7b461584a0..f6d90975c2 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,12 +31,12 @@ import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.CustomAutowireConfigurer; import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.SimpleMapScope; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.ComponentScanParserTests.CustomAnnotationAutowiredBean; import org.springframework.context.support.GenericApplicationContext; +import org.springframework.tests.context.SimpleMapScope; import org.springframework.util.SerializationTestUtils; import example.scannable.CustomComponent; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java index 4cbfd9b34e..31a87271ca 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserScopedProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.beans.FatalBeanException; -import org.springframework.beans.factory.config.SimpleMapScope; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.tests.context.SimpleMapScope; import org.springframework.util.SerializationTestUtils; /** diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java index ee826eb33a..b35fc04574 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassAndBFPPTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import static org.junit.Assert.assertThat; import org.junit.Test; import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java index eb288746fd..6972adada9 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import static org.junit.Assert.assertThat; import javax.annotation.PostConstruct; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; /** diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java index d52a9db656..815c487294 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.context.annotation; import static org.junit.Assert.*; import org.junit.Test; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.support.ChildBeanDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/FooServiceDependentConverter.java b/spring-context/src/test/java/org/springframework/context/annotation/FooServiceDependentConverter.java index c01fc14cec..eab6f37b7f 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/FooServiceDependentConverter.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/FooServiceDependentConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import org.springframework.core.convert.converter.Converter; /** * @author Juergen Hoeller */ -public class FooServiceDependentConverter implements Converter { +public class FooServiceDependentConverter implements Converter { private FooService fooService; @@ -32,8 +32,8 @@ public class FooServiceDependentConverter implements Converter - + diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportXmlWithAopNamespace-context.xml b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportXmlWithAopNamespace-context.xml index 44fc77e3b5..1b95433a63 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportXmlWithAopNamespace-context.xml +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportXmlWithAopNamespace-context.xml @@ -5,7 +5,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java index b23695db3b..e895a207c3 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportedConfigurationClassEnhancementTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.util.ClassUtils; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Unit tests cornering the bug exposed in SPR-6779. diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java index 49007b8a34..52aaaac7e9 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ScopingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; -import test.beans.ITestBean; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.aop.scope.ScopedObject; import org.springframework.beans.factory.ObjectFactory; diff --git a/spring-context/src/test/java/org/springframework/context/annotation4/FactoryMethodComponent.java b/spring-context/src/test/java/org/springframework/context/annotation4/FactoryMethodComponent.java index 125c77c636..6c59cf8522 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation4/FactoryMethodComponent.java +++ b/spring-context/src/test/java/org/springframework/context/annotation4/FactoryMethodComponent.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.context.annotation4; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; diff --git a/spring-context/src/test/java/org/springframework/context/annotation4/SimpleBean.java b/spring-context/src/test/java/org/springframework/context/annotation4/SimpleBean.java index b2cc55fec2..fcfe98d94a 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation4/SimpleBean.java +++ b/spring-context/src/test/java/org/springframework/context/annotation4/SimpleBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.context.annotation4; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.annotation.Bean; /** diff --git a/spring-context/src/test/java/org/springframework/context/annotation6/ConfigForScanning.java b/spring-context/src/test/java/org/springframework/context/annotation6/ConfigForScanning.java index 8dbb67f34a..42098c96e7 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation6/ConfigForScanning.java +++ b/spring-context/src/test/java/org/springframework/context/annotation6/ConfigForScanning.java @@ -3,7 +3,7 @@ package org.springframework.context.annotation6; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; @Configuration public class ConfigForScanning { diff --git a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java index 56233a7373..d124bac830 100644 --- a/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import static org.mockito.Mockito.verify; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java index 592337551c..1a0e064b75 100644 --- a/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,9 @@ import org.junit.Before; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.BeansException; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; diff --git a/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java b/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java index 3384916c08..17176f9dcd 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/ApplicationContextExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.apache.commons.logging.LogFactory; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; diff --git a/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java index 4dda9faf6c..152cf5d758 100644 --- a/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/expression/EnvironmentAccessorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.mock.env.MockPropertySource; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** diff --git a/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java index 8c39e53d32..152ecfb6ec 100644 --- a/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/BeanFactoryPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.*; import org.junit.Test; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; diff --git a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resource.xml b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resource.xml index e339891102..6c95987712 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resource.xml +++ b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resource.xml @@ -5,7 +5,7 @@ - + classpath:org/springframework/beans/factory/xml/test.properties diff --git a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resourceImport.xml b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resourceImport.xml index 717148bc4c..232374bd0e 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resourceImport.xml +++ b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests-resourceImport.xml @@ -3,7 +3,7 @@ - + test.properties diff --git a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java index 38939c7fcb..7ff83e35ea 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ClassPathXmlApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import java.util.Map; import org.junit.Test; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ResourceTestBean; +import org.springframework.tests.sample.beans.ResourceTestBean; import org.springframework.beans.TypeMismatchException; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanFactoryUtils; diff --git a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java index 49fda87dab..676ff05a30 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import java.util.Set; import org.junit.Test; -import org.springframework.beans.ResourceTestBean; +import org.springframework.tests.sample.beans.ResourceTestBean; import org.springframework.context.ApplicationContext; import org.springframework.core.convert.ConversionService; import org.springframework.core.convert.TypeDescriptor; diff --git a/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java index 39482f71cf..24185526d6 100644 --- a/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/PropertyResourceConfigurerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import java.io.FileNotFoundException; import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; diff --git a/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java b/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java index 3e640d9145..078b116979 100644 --- a/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/PropertySourcesPlaceholderConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import org.springframework.core.io.Resource; import org.springframework.mock.env.MockEnvironment; import org.springframework.mock.env.MockPropertySource; -import test.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Unit tests for {@link PropertySourcesPlaceholderConfigurer}. diff --git a/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTest.java b/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTest.java index e03b30eaa6..887c6fc1cc 100644 --- a/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTest.java +++ b/spring-context/src/test/java/org/springframework/context/support/SimpleThreadScopeTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java index 39651c9370..b1f9d24ecd 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextMulticasterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import java.util.Locale; import java.util.Map; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.context.ACATester; import org.springframework.context.AbstractApplicationContextTests; diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java index acddae3ff1..bba7f77668 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import java.util.Locale; import java.util.Map; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader; import org.springframework.context.ACATester; import org.springframework.context.AbstractApplicationContextTests; diff --git a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java index 8a94e8326e..908f5652c1 100644 --- a/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/StaticMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -203,9 +203,9 @@ public class StaticMessageSourceTests extends AbstractApplicationContextTests { Map m = new HashMap(); m.put("name", "Roderick"); - parent.registerPrototype("rod", org.springframework.beans.TestBean.class, new MutablePropertyValues(m)); + parent.registerPrototype("rod", org.springframework.tests.sample.beans.TestBean.class, new MutablePropertyValues(m)); m.put("name", "Albert"); - parent.registerPrototype("father", org.springframework.beans.TestBean.class, new MutablePropertyValues(m)); + parent.registerPrototype("father", org.springframework.tests.sample.beans.TestBean.class, new MutablePropertyValues(m)); parent.refresh(); parent.addApplicationListener(parentListener); diff --git a/spring-context/src/test/java/org/springframework/context/support/conversionService.xml b/spring-context/src/test/java/org/springframework/context/support/conversionService.xml index 57c2b5c8af..bcfae1cdb5 100644 --- a/spring-context/src/test/java/org/springframework/context/support/conversionService.xml +++ b/spring-context/src/test/java/org/springframework/context/support/conversionService.xml @@ -5,7 +5,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/context/support/conversionServiceWithResourceOverriding.xml b/spring-context/src/test/java/org/springframework/context/support/conversionServiceWithResourceOverriding.xml index 5e407ee0be..5ddcbab67d 100644 --- a/spring-context/src/test/java/org/springframework/context/support/conversionServiceWithResourceOverriding.xml +++ b/spring-context/src/test/java/org/springframework/context/support/conversionServiceWithResourceOverriding.xml @@ -9,7 +9,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/context/support/testBeans.properties b/spring-context/src/test/java/org/springframework/context/support/testBeans.properties index 1eab846bc5..6b9c028005 100644 --- a/spring-context/src/test/java/org/springframework/context/support/testBeans.properties +++ b/spring-context/src/test/java/org/springframework/context/support/testBeans.properties @@ -1,42 +1,42 @@ # this must only be used for ApplicationContexts, some classes are only appropriate for application contexts -rod.(class)=org.springframework.beans.TestBean +rod.(class)=org.springframework.tests.sample.beans.TestBean rod.name=Rod rod.age=31 roderick.(parent)=rod roderick.name=Roderick -kerry.(class)=org.springframework.beans.TestBean +kerry.(class)=org.springframework.tests.sample.beans.TestBean kerry.name=Kerry kerry.age=34 kerry.spouse(ref)=rod -kathy.(class)=org.springframework.beans.TestBean +kathy.(class)=org.springframework.tests.sample.beans.TestBean kathy.(singleton)=false -typeMismatch.(class)=org.springframework.beans.TestBean +typeMismatch.(class)=org.springframework.tests.sample.beans.TestBean typeMismatch.name=typeMismatch typeMismatch.age=34x typeMismatch.spouse(ref)=rod typeMismatch.(singleton)=false -validEmpty.(class)=org.springframework.beans.TestBean +validEmpty.(class)=org.springframework.tests.sample.beans.TestBean -listenerVeto.(class)=org.springframework.beans.TestBean +listenerVeto.(class)=org.springframework.tests.sample.beans.TestBean typeMismatch.name=typeMismatch typeMismatch.age=34x typeMismatch.spouse(ref)=rod -singletonFactory.(class)=org.springframework.beans.factory.DummyFactory +singletonFactory.(class)=org.springframework.tests.sample.beans.factory.DummyFactory singletonFactory.singleton=true -prototypeFactory.(class)=org.springframework.beans.factory.DummyFactory +prototypeFactory.(class)=org.springframework.tests.sample.beans.factory.DummyFactory prototypeFactory.singleton=false -mustBeInitialized.(class)=org.springframework.beans.factory.MustBeInitialized +mustBeInitialized.(class)=org.springframework.tests.sample.beans.MustBeInitialized lifecycle.(class)=org.springframework.context.LifecycleContextBean -lifecyclePostProcessor.(class)=org.springframework.beans.factory.LifecycleBean$PostProcessor +lifecyclePostProcessor.(class)=org.springframework.tests.sample.beans.LifecycleBean$PostProcessor diff --git a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java index d8c1aa1390..4eea7e8155 100644 --- a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,11 @@ import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.parsing.BeanComponentDefinition; -import org.springframework.beans.factory.parsing.CollectingReaderEventListener; import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.beans.CollectingReaderEventListener; /** * @author Torsten Juergeleit diff --git a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java index 1afb7000f3..c2430271b4 100644 --- a/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/config/JeeNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.RuntimeBeanReference; @@ -125,7 +125,7 @@ public class JeeNamespaceHandlerTests { assertPropertyValue(beanDefinition, "lookupHomeOnStartup", "true"); assertPropertyValue(beanDefinition, "resourceRef", "true"); assertPropertyValue(beanDefinition, "jndiEnvironment", "foo=bar"); - assertPropertyValue(beanDefinition, "homeInterface", "org.springframework.beans.ITestBean"); + assertPropertyValue(beanDefinition, "homeInterface", "org.springframework.tests.sample.beans.ITestBean"); assertPropertyValue(beanDefinition, "refreshHomeOnConnectFailure", "true"); assertPropertyValue(beanDefinition, "cacheSessionBean", "true"); } diff --git a/spring-context/src/test/java/org/springframework/ejb/config/jeeNamespaceHandlerTests.xml b/spring-context/src/test/java/org/springframework/ejb/config/jeeNamespaceHandlerTests.xml index 6d1a3ddf83..e8767251a9 100644 --- a/spring-context/src/test/java/org/springframework/ejb/config/jeeNamespaceHandlerTests.xml +++ b/spring-context/src/test/java/org/springframework/ejb/config/jeeNamespaceHandlerTests.xml @@ -41,11 +41,11 @@ + business-interface="org.springframework.tests.sample.beans.ITestBean"/> @@ -54,15 +54,15 @@ + business-interface="org.springframework.tests.sample.beans.ITestBean"/> foo=bar @@ -71,8 +71,8 @@ + business-interface="org.springframework.tests.sample.beans.ITestBean" lazy-init="true" /> + business-interface="org.springframework.tests.sample.beans.ITestBean" lazy-init="true" /> diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index 26b0af991d..2d7d9e2639 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,6 @@ import javax.management.ObjectName; import javax.management.modelmbean.ModelMBeanInfo; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.TestBean; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; @@ -48,8 +47,8 @@ import org.springframework.jmx.export.assembler.SimpleReflectiveMBeanInfoAssembl import org.springframework.jmx.export.naming.SelfNaming; import org.springframework.jmx.support.ObjectNameManager; import org.springframework.jmx.support.RegistrationPolicy; - -import test.interceptor.NopInterceptor; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.TestBean; /** * Integration tests for the {@link MBeanExporter} class. diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java index 4c7c414d85..99cefe7158 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -32,8 +32,7 @@ import org.springframework.jmx.JmxTestBean; import org.springframework.jmx.export.MBeanExporter; import org.springframework.jmx.export.metadata.JmxAttributeSource; import org.springframework.jmx.support.ObjectNameManager; - -import test.interceptor.NopInterceptor; +import org.springframework.tests.aop.interceptor.NopInterceptor; /** * @author Rob Harrop diff --git a/spring-context/src/test/java/org/springframework/jmx/export/propertyPlaceholderConfigurer.xml b/spring-context/src/test/java/org/springframework/jmx/export/propertyPlaceholderConfigurer.xml index b108c30e01..79790d3963 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/propertyPlaceholderConfigurer.xml +++ b/spring-context/src/test/java/org/springframework/jmx/export/propertyPlaceholderConfigurer.xml @@ -17,7 +17,7 @@ - + diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java index a99ef772f0..4ad2255d2c 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiObjectFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,10 +26,10 @@ import javax.naming.Context; import javax.naming.NamingException; import org.junit.Test; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; -import org.springframework.mock.jndi.ExpectedLookupTemplate; +import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rod Johnson @@ -378,7 +378,7 @@ public class JndiObjectFactoryBeanTests { fail("Should have thrown NamingException"); } catch (NamingException ex) { - assertTrue(ex.getMessage().indexOf("org.springframework.beans.DerivedTestBean") != -1); + assertTrue(ex.getMessage().indexOf("org.springframework.tests.sample.beans.DerivedTestBean") != -1); } } diff --git a/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java b/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java index 5148742ca4..ad6ac8871a 100644 --- a/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/JndiPropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import javax.naming.Context; import javax.naming.NamingException; import org.junit.Test; -import org.springframework.mock.jndi.SimpleNamingContext; +import org.springframework.tests.mock.jndi.SimpleNamingContext; /** * Unit tests for {@link JndiPropertySource}. diff --git a/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java b/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java index 23bac25d53..917e8dc918 100644 --- a/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java +++ b/spring-context/src/test/java/org/springframework/jndi/SimpleNamingContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ import javax.sql.DataSource; import org.junit.Test; -import org.springframework.mock.jndi.SimpleNamingContext; -import org.springframework.mock.jndi.SimpleNamingContextBuilder; +import org.springframework.tests.mock.jndi.SimpleNamingContext; +import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; import static org.junit.Assert.*; diff --git a/spring-context/src/test/java/org/springframework/mock/env/MockPropertySource.java b/spring-context/src/test/java/org/springframework/mock/env/MockPropertySource.java deleted file mode 100644 index 2783f244b1..0000000000 --- a/spring-context/src/test/java/org/springframework/mock/env/MockPropertySource.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.env; - -import java.util.Properties; - -import org.springframework.core.env.PropertiesPropertySource; -import org.springframework.core.env.PropertySource; - -/** - * Simple {@link PropertySource} implementation for use in testing. Accepts - * a user-provided {@link Properties} object, or if omitted during construction, - * the implementation will initialize its own. - * - * The {@link #setProperty} and {@link #withProperty} methods are exposed for - * convenience, for example: - *
- * {@code
- *   PropertySource source = new MockPropertySource().withProperty("foo", "bar");
- * }
- * 
- * - * @author Chris Beams - * @since 3.1 - * @see org.springframework.mock.env.MockEnvironment - */ -public class MockPropertySource extends PropertiesPropertySource { - - /** - * {@value} is the default name for {@link MockPropertySource} instances not - * otherwise given an explicit name. - * @see #MockPropertySource() - * @see #MockPropertySource(String) - */ - public static final String MOCK_PROPERTIES_PROPERTY_SOURCE_NAME = "mockProperties"; - - /** - * Create a new {@code MockPropertySource} named {@value #MOCK_PROPERTIES_PROPERTY_SOURCE_NAME} - * that will maintain its own internal {@link Properties} instance. - */ - public MockPropertySource() { - this(new Properties()); - } - - /** - * Create a new {@code MockPropertySource} with the given name that will - * maintain its own internal {@link Properties} instance. - * @param name the {@linkplain #getName() name} of the property source - */ - public MockPropertySource(String name) { - this(name, new Properties()); - } - - /** - * Create a new {@code MockPropertySource} named {@value #MOCK_PROPERTIES_PROPERTY_SOURCE_NAME} - * and backed by the given {@link Properties} object. - * @param properties the properties to use - */ - public MockPropertySource(Properties properties) { - this(MOCK_PROPERTIES_PROPERTY_SOURCE_NAME, properties); - } - - /** - * Create a new {@code MockPropertySource} with the given name and backed by the given - * {@link Properties} object - * @param name the {@linkplain #getName() name} of the property source - * @param properties the properties to use - */ - public MockPropertySource(String name, Properties properties) { - super(name, properties); - } - - /** - * Set the given property on the underlying {@link Properties} object. - */ - public void setProperty(String name, Object value) { - this.source.put(name, value); - } - - /** - * Convenient synonym for {@link #setProperty} that returns the current instance. - * Useful for method chaining and fluent-style use. - * @return this {@link MockPropertySource} instance - */ - public MockPropertySource withProperty(String name, Object value) { - this.setProperty(name, value); - return this; - } - -} diff --git a/spring-context/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java b/spring-context/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java deleted file mode 100644 index 7173686606..0000000000 --- a/spring-context/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.jndi; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.naming.NamingException; - -import org.springframework.jndi.JndiTemplate; - -/** - * Simple extension of the JndiTemplate class that always returns - * a given object. Very useful for testing. Effectively a mock object. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public class ExpectedLookupTemplate extends JndiTemplate { - - private final Map jndiObjects = new ConcurrentHashMap(); - - - /** - * Construct a new JndiTemplate that will always return given objects - * for given names. To be populated through {@code addObject} calls. - * @see #addObject(String, Object) - */ - public ExpectedLookupTemplate() { - } - - /** - * Construct a new JndiTemplate that will always return the - * given object, but honour only requests for the given name. - * @param name the name the client is expected to look up - * @param object the object that will be returned - */ - public ExpectedLookupTemplate(String name, Object object) { - addObject(name, object); - } - - - /** - * Add the given object to the list of JNDI objects that this - * template will expose. - * @param name the name the client is expected to look up - * @param object the object that will be returned - */ - public void addObject(String name, Object object) { - this.jndiObjects.put(name, object); - } - - - /** - * If the name is the expected name specified in the constructor, - * return the object provided in the constructor. If the name is - * unexpected, a respective NamingException gets thrown. - */ - @Override - public Object lookup(String name) throws NamingException { - Object object = this.jndiObjects.get(name); - if (object == null) { - throw new NamingException("Unexpected JNDI name '" + name + "': expecting " + this.jndiObjects.keySet()); - } - return object; - } - -} diff --git a/spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java b/spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java deleted file mode 100644 index 883db7bfd3..0000000000 --- a/spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.jndi; - -import java.util.Hashtable; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.spi.InitialContextFactory; -import javax.naming.spi.InitialContextFactoryBuilder; -import javax.naming.spi.NamingManager; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.util.ClassUtils; - -/** - * Simple implementation of a JNDI naming context builder. - * - *

Mainly targeted at test environments, where each test case can - * configure JNDI appropriately, so that {@code new InitialContext()} - * will expose the required objects. Also usable for standalone applications, - * e.g. for binding a JDBC DataSource to a well-known JNDI location, to be - * able to use traditional J2EE data access code outside of a J2EE container. - * - *

There are various choices for DataSource implementations: - *

    - *
  • SingleConnectionDataSource (using the same Connection for all getConnection calls); - *
  • DriverManagerDataSource (creating a new Connection on each getConnection call); - *
  • Apache's Jakarta Commons DBCP offers BasicDataSource (a real pool). - *
- * - *

Typical usage in bootstrap code: - * - *

- * SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
- * DataSource ds = new DriverManagerDataSource(...);
- * builder.bind("java:comp/env/jdbc/myds", ds);
- * builder.activate();
- * - * Note that it's impossible to activate multiple builders within the same JVM, - * due to JNDI restrictions. Thus to configure a fresh builder repeatedly, use - * the following code to get a reference to either an already activated builder - * or a newly activated one: - * - *
- * SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
- * DataSource ds = new DriverManagerDataSource(...);
- * builder.bind("java:comp/env/jdbc/myds", ds);
- * - * Note that you should not call {@code activate()} on a builder from - * this factory method, as there will already be an activated one in any case. - * - *

An instance of this class is only necessary at setup time. - * An application does not need to keep a reference to it after activation. - * - * @author Juergen Hoeller - * @author Rod Johnson - * @see #emptyActivatedContextBuilder() - * @see #bind(String, Object) - * @see #activate() - * @see SimpleNamingContext - * @see org.springframework.jdbc.datasource.SingleConnectionDataSource - * @see org.springframework.jdbc.datasource.DriverManagerDataSource - * @see org.apache.commons.dbcp.BasicDataSource - */ -public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder { - - /** An instance of this class bound to JNDI */ - private static volatile SimpleNamingContextBuilder activated; - - private static boolean initialized = false; - - private static final Object initializationLock = new Object(); - - - /** - * Checks if a SimpleNamingContextBuilder is active. - * @return the current SimpleNamingContextBuilder instance, - * or {@code null} if none - */ - public static SimpleNamingContextBuilder getCurrentContextBuilder() { - return activated; - } - - /** - * If no SimpleNamingContextBuilder is already configuring JNDI, - * create and activate one. Otherwise take the existing activate - * SimpleNamingContextBuilder, clear it and return it. - *

This is mainly intended for test suites that want to - * reinitialize JNDI bindings from scratch repeatedly. - * @return an empty SimpleNamingContextBuilder that can be used - * to control JNDI bindings - */ - public static SimpleNamingContextBuilder emptyActivatedContextBuilder() throws NamingException { - if (activated != null) { - // Clear already activated context builder. - activated.clear(); - } - else { - // Create and activate new context builder. - SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); - // The activate() call will cause an assignment to the activated variable. - builder.activate(); - } - return activated; - } - - - private final Log logger = LogFactory.getLog(getClass()); - - private final Hashtable boundObjects = new Hashtable(); - - - /** - * Register the context builder by registering it with the JNDI NamingManager. - * Note that once this has been done, {@code new InitialContext()} will always - * return a context from this factory. Use the {@code emptyActivatedContextBuilder()} - * static method to get an empty context (for example, in test methods). - * @throws IllegalStateException if there's already a naming context builder - * registered with the JNDI NamingManager - */ - public void activate() throws IllegalStateException, NamingException { - logger.info("Activating simple JNDI environment"); - synchronized (initializationLock) { - if (!initialized) { - if (NamingManager.hasInitialContextFactoryBuilder()) { - throw new IllegalStateException( - "Cannot activate SimpleNamingContextBuilder: there is already a JNDI provider registered. " + - "Note that JNDI is a JVM-wide service, shared at the JVM system class loader level, " + - "with no reset option. As a consequence, a JNDI provider must only be registered once per JVM."); - } - NamingManager.setInitialContextFactoryBuilder(this); - initialized = true; - } - } - activated = this; - } - - /** - * Temporarily deactivate this context builder. It will remain registered with - * the JNDI NamingManager but will delegate to the standard JNDI InitialContextFactory - * (if configured) instead of exposing its own bound objects. - *

Call {@code activate()} again in order to expose this context builder's own - * bound objects again. Such activate/deactivate sequences can be applied any number - * of times (e.g. within a larger integration test suite running in the same VM). - * @see #activate() - */ - public void deactivate() { - logger.info("Deactivating simple JNDI environment"); - activated = null; - } - - /** - * Clear all bindings in this context builder, while keeping it active. - */ - public void clear() { - this.boundObjects.clear(); - } - - /** - * Bind the given object under the given name, for all naming contexts - * that this context builder will generate. - * @param name the JNDI name of the object (e.g. "java:comp/env/jdbc/myds") - * @param obj the object to bind (e.g. a DataSource implementation) - */ - public void bind(String name, Object obj) { - if (logger.isInfoEnabled()) { - logger.info("Static JNDI binding: [" + name + "] = [" + obj + "]"); - } - this.boundObjects.put(name, obj); - } - - - /** - * Simple InitialContextFactoryBuilder implementation, - * creating a new SimpleNamingContext instance. - * @see SimpleNamingContext - */ - @Override - public InitialContextFactory createInitialContextFactory(Hashtable environment) { - if (activated == null && environment != null) { - Object icf = environment.get(Context.INITIAL_CONTEXT_FACTORY); - if (icf != null) { - Class icfClass = null; - if (icf instanceof Class) { - icfClass = (Class) icf; - } - else if (icf instanceof String) { - icfClass = ClassUtils.resolveClassName((String) icf, getClass().getClassLoader()); - } - else { - throw new IllegalArgumentException("Invalid value type for environment key [" + - Context.INITIAL_CONTEXT_FACTORY + "]: " + icf.getClass().getName()); - } - if (!InitialContextFactory.class.isAssignableFrom(icfClass)) { - throw new IllegalArgumentException( - "Specified class does not implement [" + InitialContextFactory.class.getName() + "]: " + icf); - } - try { - return (InitialContextFactory) icfClass.newInstance(); - } - catch (Throwable ex) { - IllegalStateException ise = - new IllegalStateException("Cannot instantiate specified InitialContextFactory: " + icf); - ise.initCause(ex); - throw ise; - } - } - } - - // Default case... - return new InitialContextFactory() { - @Override - @SuppressWarnings("unchecked") - public Context getInitialContext(Hashtable environment) { - return new SimpleNamingContext("", boundObjects, (Hashtable) environment); - } - }; - } - -} diff --git a/spring-context/src/test/java/org/springframework/mock/jndi/package-info.java b/spring-context/src/test/java/org/springframework/mock/jndi/package-info.java deleted file mode 100644 index 9c268b0f67..0000000000 --- a/spring-context/src/test/java/org/springframework/mock/jndi/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * The simplest implementation of the JNDI SPI that could possibly work. - * - *

Useful for setting up a simple JNDI environment for test suites - * or standalone applications. If e.g. JDBC DataSources get bound to the - * same JNDI names as within a J2EE container, both application code and - * configuration can me reused without changes. - */ - -package org.springframework.mock.jndi; diff --git a/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java b/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java index e0945fab1d..3beaf36b84 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import java.util.TimerTask; import junit.framework.TestCase; -import org.springframework.scheduling.TestMethodInvokingTask; +import org.springframework.tests.context.TestMethodInvokingTask; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/scripting/ContextScriptBean.java b/spring-context/src/test/java/org/springframework/scripting/ContextScriptBean.java index 052209d92f..8c9a0ae2b8 100644 --- a/spring-context/src/test/java/org/springframework/scripting/ContextScriptBean.java +++ b/spring-context/src/test/java/org/springframework/scripting/ContextScriptBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.scripting; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; /** diff --git a/spring-context/src/test/java/org/springframework/scripting/TestBeanAwareMessenger.java b/spring-context/src/test/java/org/springframework/scripting/TestBeanAwareMessenger.java index ddc139475c..7ea2ee2590 100644 --- a/spring-context/src/test/java/org/springframework/scripting/TestBeanAwareMessenger.java +++ b/spring-context/src/test/java/org/springframework/scripting/TestBeanAwareMessenger.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.scripting; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java index 8add303ba8..0560184010 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/BshScriptFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import junit.framework.TestCase; import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/MessengerImpl.bsh b/spring-context/src/test/java/org/springframework/scripting/bsh/MessengerImpl.bsh index 62bfe8b7bf..72a1e6a39c 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/MessengerImpl.bsh +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/MessengerImpl.bsh @@ -1,4 +1,4 @@ -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.scripting.TestBeanAwareMessenger; public class MyMessenger implements TestBeanAwareMessenger { diff --git a/spring-context/src/test/java/org/springframework/scripting/bsh/bsh-with-xsd.xml b/spring-context/src/test/java/org/springframework/scripting/bsh/bsh-with-xsd.xml index 5908749d75..116a7d6ab4 100644 --- a/spring-context/src/test/java/org/springframework/scripting/bsh/bsh-with-xsd.xml +++ b/spring-context/src/test/java/org/springframework/scripting/bsh/bsh-with-xsd.xml @@ -36,7 +36,7 @@ autowire="byName" init-method="init" destroy-method="destroy"> - + diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index 86214124a8..e472a7064e 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -36,7 +36,7 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.UnsatisfiedDependencyException; diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/ScriptBean.groovy b/spring-context/src/test/java/org/springframework/scripting/groovy/ScriptBean.groovy index d1b82bfece..0b0116d2e1 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/ScriptBean.groovy +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/ScriptBean.groovy @@ -1,4 +1,4 @@ -import org.springframework.beans.TestBean +import org.springframework.tests.sample.beans.TestBean import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.scripting.ContextScriptBean diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/groovy-multiple-properties.xml b/spring-context/src/test/java/org/springframework/scripting/groovy/groovy-multiple-properties.xml index 58ce5e022a..eaad85d1f8 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/groovy-multiple-properties.xml +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/groovy-multiple-properties.xml @@ -19,6 +19,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-beanNameAutoProxyCreator.xml b/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-beanNameAutoProxyCreator.xml index a8afa2447f..1516ac2dbc 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-beanNameAutoProxyCreator.xml +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-beanNameAutoProxyCreator.xml @@ -16,6 +16,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-factoryBean.xml b/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-factoryBean.xml index 3744ad4ea6..2cd55ee7df 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-factoryBean.xml +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests-factoryBean.xml @@ -16,6 +16,6 @@ - + diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests.java index a379176180..0e29267700 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/AdvisedJRubyScriptFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,10 +25,9 @@ import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.scripting.Messenger; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; import org.springframework.util.MBeanTestUtils; -import test.advice.CountingBeforeAdvice; - /** * @author Rob Harrop * @author Chris Beams diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java index dd338997f0..8071e6309e 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java @@ -22,7 +22,7 @@ import junit.framework.TestCase; import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/jruby-with-xsd.xml b/spring-context/src/test/java/org/springframework/scripting/jruby/jruby-with-xsd.xml index 13f5d3c9aa..5df3894c08 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/jruby-with-xsd.xml +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/jruby-with-xsd.xml @@ -28,7 +28,7 @@ autowire="byName"> - + diff --git a/spring-context/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java b/spring-context/src/test/java/org/springframework/tests/context/SimpleMapScope.java similarity index 95% rename from spring-context/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java rename to spring-context/src/test/java/org/springframework/tests/context/SimpleMapScope.java index 71b565f900..9b63bfc333 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/config/SimpleMapScope.java +++ b/spring-context/src/test/java/org/springframework/tests/context/SimpleMapScope.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans.factory.config; +package org.springframework.tests.context; import java.io.Serializable; import java.util.HashMap; @@ -24,6 +24,7 @@ import java.util.List; import java.util.Map; import org.springframework.beans.factory.ObjectFactory; +import org.springframework.beans.factory.config.Scope; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java b/spring-context/src/test/java/org/springframework/tests/context/TestMethodInvokingTask.java similarity index 96% rename from spring-context/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java rename to spring-context/src/test/java/org/springframework/tests/context/TestMethodInvokingTask.java index a95a2408b5..118feabbc3 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/TestMethodInvokingTask.java +++ b/spring-context/src/test/java/org/springframework/tests/context/TestMethodInvokingTask.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.scheduling; +package org.springframework.tests.context; /** * @author Juergen Hoeller diff --git a/spring-tx/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java b/spring-context/src/test/java/org/springframework/tests/mock/jndi/ExpectedLookupTemplate.java similarity index 98% rename from spring-tx/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java rename to spring-context/src/test/java/org/springframework/tests/mock/jndi/ExpectedLookupTemplate.java index 7173686606..a4e8932e26 100644 --- a/spring-tx/src/test/java/org/springframework/mock/jndi/ExpectedLookupTemplate.java +++ b/spring-context/src/test/java/org/springframework/tests/mock/jndi/ExpectedLookupTemplate.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.mock.jndi; +package org.springframework.tests.mock.jndi; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; diff --git a/spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java b/spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContext.java similarity index 98% rename from spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java rename to spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContext.java index 4e1641b2cd..bdad96e32d 100644 --- a/spring-context/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java +++ b/spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContext.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.mock.jndi; +package org.springframework.tests.mock.jndi; import java.util.HashMap; import java.util.Hashtable; @@ -149,7 +149,7 @@ public class SimpleNamingContext implements Context { * Note: Not intended for direct use by applications * if setting up a JVM-level JNDI environment. * Use SimpleNamingContextBuilder to set up JNDI bindings then. - * @see org.springframework.mock.jndi.SimpleNamingContextBuilder#bind + * @see org.springframework.tests.mock.jndi.SimpleNamingContextBuilder#bind */ @Override public void bind(String name, Object obj) { diff --git a/spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java b/spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContextBuilder.java similarity index 99% rename from spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java rename to spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContextBuilder.java index 883db7bfd3..3d1452ac29 100644 --- a/spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContextBuilder.java +++ b/spring-context/src/test/java/org/springframework/tests/mock/jndi/SimpleNamingContextBuilder.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.mock.jndi; +package org.springframework.tests.mock.jndi; import java.util.Hashtable; diff --git a/spring-context/src/test/java/test/beans/SideEffectBean.java b/spring-context/src/test/java/org/springframework/tests/mock/jndi/package-info.java similarity index 62% rename from spring-context/src/test/java/test/beans/SideEffectBean.java rename to spring-context/src/test/java/org/springframework/tests/mock/jndi/package-info.java index 52b7873717..8847baab54 100644 --- a/spring-context/src/test/java/test/beans/SideEffectBean.java +++ b/spring-context/src/test/java/org/springframework/tests/mock/jndi/package-info.java @@ -14,28 +14,12 @@ * limitations under the License. */ -package test.beans; - /** - * Bean that changes state on a business invocation, so that - * we can check whether it's been invoked + * The simplest implementation of the JNDI SPI that could possibly work. * - * @author Rod Johnson + *

Useful for setting up a simple JNDI environment for test suites + * or standalone applications. If e.g. JDBC DataSources get bound to the + * same JNDI names as within a J2EE container, both application code and + * configuration can me reused without changes. */ -public class SideEffectBean { - - private int count; - - public void setCount(int count) { - this.count = count; - } - - public int getCount() { - return this.count; - } - - public void doWork() { - ++count; - } - -} \ No newline at end of file +package org.springframework.tests.mock.jndi; diff --git a/spring-context/src/test/java/org/springframework/beans/BeanWithObjectProperty.java b/spring-context/src/test/java/org/springframework/tests/sample/beans/BeanWithObjectProperty.java similarity index 94% rename from spring-context/src/test/java/org/springframework/beans/BeanWithObjectProperty.java rename to spring-context/src/test/java/org/springframework/tests/sample/beans/BeanWithObjectProperty.java index bb5e71f5cd..4448962d49 100644 --- a/spring-context/src/test/java/org/springframework/beans/BeanWithObjectProperty.java +++ b/spring-context/src/test/java/org/springframework/tests/sample/beans/BeanWithObjectProperty.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/test/beans/Employee.java b/spring-context/src/test/java/org/springframework/tests/sample/beans/Employee.java similarity index 89% rename from spring-context/src/test/java/test/beans/Employee.java rename to spring-context/src/test/java/org/springframework/tests/sample/beans/Employee.java index 537a5a8833..7bed71f394 100644 --- a/spring-context/src/test/java/test/beans/Employee.java +++ b/spring-context/src/test/java/org/springframework/tests/sample/beans/Employee.java @@ -15,9 +15,9 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; public class Employee extends TestBean { diff --git a/spring-context/src/test/java/test/beans/FactoryMethods.java b/spring-context/src/test/java/org/springframework/tests/sample/beans/FactoryMethods.java similarity index 95% rename from spring-context/src/test/java/test/beans/FactoryMethods.java rename to spring-context/src/test/java/org/springframework/tests/sample/beans/FactoryMethods.java index 8e0f55ce77..a98548867a 100644 --- a/spring-context/src/test/java/test/beans/FactoryMethods.java +++ b/spring-context/src/test/java/org/springframework/tests/sample/beans/FactoryMethods.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package test.beans; +package org.springframework.tests.sample.beans; /** * Test class for Spring's ability to create objects using static diff --git a/spring-webmvc/src/test/java/org/springframework/beans/FieldAccessBean.java b/spring-context/src/test/java/org/springframework/tests/sample/beans/FieldAccessBean.java similarity index 95% rename from spring-webmvc/src/test/java/org/springframework/beans/FieldAccessBean.java rename to spring-context/src/test/java/org/springframework/tests/sample/beans/FieldAccessBean.java index 61f911902c..a250f329cb 100644 --- a/spring-webmvc/src/test/java/org/springframework/beans/FieldAccessBean.java +++ b/spring-context/src/test/java/org/springframework/tests/sample/beans/FieldAccessBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/beans/ResourceTestBean.java b/spring-context/src/test/java/org/springframework/tests/sample/beans/ResourceTestBean.java similarity index 97% rename from spring-context/src/test/java/org/springframework/beans/ResourceTestBean.java rename to spring-context/src/test/java/org/springframework/tests/sample/beans/ResourceTestBean.java index 0831e05c58..a5b1eef734 100644 --- a/spring-context/src/test/java/org/springframework/beans/ResourceTestBean.java +++ b/spring-context/src/test/java/org/springframework/tests/sample/beans/ResourceTestBean.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.beans; +package org.springframework.tests.sample.beans; import java.io.InputStream; import java.util.Map; diff --git a/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java b/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java index 09a8c6aaa8..7b159f3b3a 100644 --- a/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java +++ b/spring-context/src/test/java/org/springframework/ui/ModelMapTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import java.util.Map; import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; diff --git a/spring-context/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-context/src/test/java/org/springframework/util/SerializationTestUtils.java deleted file mode 100644 index b20121d864..0000000000 --- a/spring-context/src/test/java/org/springframework/util/SerializationTestUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * - * @author Rod Johnson - */ -public class SerializationTestUtils { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - return o2; - } - -} diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java index e64219c59c..bf2031ba53 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderFieldAccessTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +21,11 @@ import java.util.Map; import junit.framework.TestCase; -import org.springframework.beans.FieldAccessBean; +import org.springframework.tests.sample.beans.FieldAccessBean; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.NotWritablePropertyException; import org.springframework.beans.PropertyValue; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java index 9107bb3a59..515a1013b0 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,16 +37,16 @@ import java.util.TreeSet; import junit.framework.TestCase; -import org.springframework.beans.BeanWithObjectProperty; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.BeanWithObjectProperty; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; import org.springframework.beans.InvalidPropertyException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.NotWritablePropertyException; import org.springframework.beans.NullValueInNestedPathException; -import org.springframework.beans.SerializablePerson; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.SerializablePerson; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.context.i18n.LocaleContextHolder; @@ -1196,8 +1196,8 @@ public class DataBinderTests extends TestCase { pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); - assertEquals("listtest1", tb.getArray()[0].getNestedIndexedBean().getList().get(0).getName()); - assertEquals("listtest2", tb.getArray()[1].getNestedIndexedBean().getList().get(1).getName()); + assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); + assertEquals("listtest2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); } @@ -1221,8 +1221,8 @@ public class DataBinderTests extends TestCase { pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); - assertEquals("listtest1", tb.getArray()[0].getNestedIndexedBean().getList().get(0).getName()); - assertEquals("test2", tb.getArray()[1].getNestedIndexedBean().getList().get(1).getName()); + assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); + assertEquals("test2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); } @@ -1246,8 +1246,8 @@ public class DataBinderTests extends TestCase { pvs.add("array[0].nestedIndexedBean.list[0].name", "test1"); pvs.add("array[1].nestedIndexedBean.list[1].name", "test2"); binder.bind(pvs); - assertEquals("listtest1", tb.getArray()[0].getNestedIndexedBean().getList().get(0).getName()); - assertEquals("test2", tb.getArray()[1].getNestedIndexedBean().getList().get(1).getName()); + assertEquals("listtest1", ((TestBean)tb.getArray()[0].getNestedIndexedBean().getList().get(0)).getName()); + assertEquals("test2", ((TestBean)tb.getArray()[1].getNestedIndexedBean().getList().get(1)).getName()); assertEquals("test1", binder.getBindingResult().getFieldValue("array[0].nestedIndexedBean.list[0].name")); assertEquals("test2", binder.getBindingResult().getFieldValue("array[1].nestedIndexedBean.list[1].name")); } @@ -1282,7 +1282,7 @@ public class DataBinderTests extends TestCase { assertEquals("NOT_ROD.tb.array", errors.getFieldError("array[0]").getCodes()[1]); assertEquals("NOT_ROD.array[0]", errors.getFieldError("array[0]").getCodes()[2]); assertEquals("NOT_ROD.array", errors.getFieldError("array[0]").getCodes()[3]); - assertEquals("NOT_ROD.org.springframework.beans.DerivedTestBean", errors.getFieldError("array[0]").getCodes()[4]); + assertEquals("NOT_ROD.org.springframework.tests.sample.beans.DerivedTestBean", errors.getFieldError("array[0]").getCodes()[4]); assertEquals("NOT_ROD", errors.getFieldError("array[0]").getCodes()[5]); assertEquals("arraya", errors.getFieldValue("array[0]")); @@ -1292,7 +1292,7 @@ public class DataBinderTests extends TestCase { assertEquals("NOT_ROD.tb.map", errors.getFieldError("map[key1]").getCodes()[1]); assertEquals("NOT_ROD.map[key1]", errors.getFieldError("map[key1]").getCodes()[2]); assertEquals("NOT_ROD.map", errors.getFieldError("map[key1]").getCodes()[3]); - assertEquals("NOT_ROD.org.springframework.beans.TestBean", errors.getFieldError("map[key1]").getCodes()[4]); + assertEquals("NOT_ROD.org.springframework.tests.sample.beans.TestBean", errors.getFieldError("map[key1]").getCodes()[4]); assertEquals("NOT_ROD", errors.getFieldError("map[key1]").getCodes()[5]); assertEquals(1, errors.getFieldErrorCount("map[key0]")); @@ -1330,7 +1330,7 @@ public class DataBinderTests extends TestCase { assertEquals("NOT_NULL.map", errors.getFieldError("map[key0]").getCodes()[3]); // This next code is only generated because of the registered editor, using the // registered type of the editor as guess for the content type of the collection. - assertEquals("NOT_NULL.org.springframework.beans.TestBean", errors.getFieldError("map[key0]").getCodes()[4]); + assertEquals("NOT_NULL.org.springframework.tests.sample.beans.TestBean", errors.getFieldError("map[key0]").getCodes()[4]); assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCodes()[5]); } @@ -1360,7 +1360,7 @@ public class DataBinderTests extends TestCase { assertEquals("NOT_NULL.map", errors.getFieldError("map[key0]").getCodes()[3]); // This next code is only generated because of the registered editor, using the // registered type of the editor as guess for the content type of the collection. - assertEquals("NOT_NULL.org.springframework.beans.TestBean", errors.getFieldError("map[key0]").getCodes()[4]); + assertEquals("NOT_NULL.org.springframework.tests.sample.beans.TestBean", errors.getFieldError("map[key0]").getCodes()[4]); assertEquals("NOT_NULL", errors.getFieldError("map[key0]").getCodes()[5]); } @@ -1392,7 +1392,7 @@ public class DataBinderTests extends TestCase { assertEquals("NOT_ROD.tb.array", errors.getFieldError("array[0]").getCodes()[1]); assertEquals("NOT_ROD.array[0]", errors.getFieldError("array[0]").getCodes()[2]); assertEquals("NOT_ROD.array", errors.getFieldError("array[0]").getCodes()[3]); - assertEquals("NOT_ROD.org.springframework.beans.DerivedTestBean", errors.getFieldError("array[0]").getCodes()[4]); + assertEquals("NOT_ROD.org.springframework.tests.sample.beans.DerivedTestBean", errors.getFieldError("array[0]").getCodes()[4]); assertEquals("NOT_ROD", errors.getFieldError("array[0]").getCodes()[5]); assertEquals("arraya", errors.getFieldValue("array[0]")); } diff --git a/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java index d5e094a2e1..947677717c 100644 --- a/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DefaultMessageCodesResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.DefaultMessageCodesResolver.Format; /** @@ -48,7 +48,7 @@ public class DefaultMessageCodesResolverTests { assertThat(codes, is(equalTo(new String[] { "errorCode.objectName.field", "errorCode.field", - "errorCode.org.springframework.beans.TestBean", + "errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode" }))); } @@ -64,7 +64,7 @@ public class DefaultMessageCodesResolverTests { "errorCode.a.b[3].c.d", "errorCode.a.b.c.d", "errorCode.d", - "errorCode.org.springframework.beans.TestBean", + "errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode" }))); } @@ -85,7 +85,7 @@ public class DefaultMessageCodesResolverTests { assertThat(codes, is(equalTo(new String[] { "prefix.errorCode.objectName.field", "prefix.errorCode.field", - "prefix.errorCode.org.springframework.beans.TestBean", + "prefix.errorCode.org.springframework.tests.sample.beans.TestBean", "prefix.errorCode" }))); } @@ -97,7 +97,7 @@ public class DefaultMessageCodesResolverTests { assertThat(codes, is(equalTo(new String[] { "errorCode.objectName.field", "errorCode.field", - "errorCode.org.springframework.beans.TestBean", + "errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode" }))); } @@ -108,7 +108,7 @@ public class DefaultMessageCodesResolverTests { assertThat(codes, is(equalTo(new String[] { "errorCode.objectName.field[", "errorCode.field[", - "errorCode.org.springframework.beans.TestBean", + "errorCode.org.springframework.tests.sample.beans.TestBean", "errorCode" }))); } @@ -139,7 +139,7 @@ public class DefaultMessageCodesResolverTests { assertThat(codes, is(equalTo(new String[] { "objectName.field.errorCode", "field.errorCode", - "org.springframework.beans.TestBean.errorCode", + "org.springframework.tests.sample.beans.TestBean.errorCode", "errorCode" }))); } diff --git a/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java b/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java index 1c7fe2c708..83a36cf955 100644 --- a/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java +++ b/spring-context/src/test/java/org/springframework/validation/ValidationUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.validation; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Unit tests for {@link ValidationUtils}. diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java index b98fb42007..6d831328c1 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/BeanValidationPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import javax.validation.constraints.Size; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; diff --git a/spring-context/src/test/java/test/advice/CountingBeforeAdvice.java b/spring-context/src/test/java/test/advice/CountingBeforeAdvice.java deleted file mode 100644 index 5aa37b61e1..0000000000 --- a/spring-context/src/test/java/test/advice/CountingBeforeAdvice.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.advice; - -import java.lang.reflect.Method; - -import org.springframework.aop.MethodBeforeAdvice; - -/** - * Simple before advice example that we can use for counting checks. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class CountingBeforeAdvice extends MethodCounter implements MethodBeforeAdvice { - - @Override - public void before(Method m, Object[] args, Object target) throws Throwable { - count(m); - } - -} diff --git a/spring-context/src/test/java/test/advice/MethodCounter.java b/spring-context/src/test/java/test/advice/MethodCounter.java deleted file mode 100644 index e0e45d6f14..0000000000 --- a/spring-context/src/test/java/test/advice/MethodCounter.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.advice; - -import java.io.Serializable; -import java.lang.reflect.Method; -import java.util.HashMap; - -/** - * Abstract superclass for counting advices etc. - * - * @author Rod Johnson - * @author Chris Beams - */ -@SuppressWarnings("serial") -public class MethodCounter implements Serializable { - - /** Method name --> count, does not understand overloading */ - private HashMap map = new HashMap(); - - private int allCount; - - protected void count(Method m) { - count(m.getName()); - } - - protected void count(String methodName) { - Integer i = map.get(methodName); - i = (i != null) ? new Integer(i.intValue() + 1) : new Integer(1); - map.put(methodName, i); - ++allCount; - } - - public int getCalls(String methodName) { - Integer i = map.get(methodName); - return (i != null ? i.intValue() : 0); - } - - public int getCalls() { - return allCount; - } - - /** - * A bit simplistic: just wants the same class. - * Doesn't worry about counts. - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object other) { - return (other != null && other.getClass() == this.getClass()); - } - - public int hashCode() { - return getClass().hashCode(); - } - -} diff --git a/spring-context/src/test/java/test/beans/Colour.java b/spring-context/src/test/java/test/beans/Colour.java deleted file mode 100644 index 193531bcbd..0000000000 --- a/spring-context/src/test/java/test/beans/Colour.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings({ "serial", "deprecation" }) -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - - public static final Colour BLUE = new Colour(1, "BLUE"); - - public static final Colour GREEN = new Colour(2, "GREEN"); - - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } -} diff --git a/spring-context/src/test/java/test/beans/CustomScope.java b/spring-context/src/test/java/test/beans/CustomScope.java deleted file mode 100644 index 32de232264..0000000000 --- a/spring-context/src/test/java/test/beans/CustomScope.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.beans.factory.ObjectFactory; -import org.springframework.beans.factory.config.Scope; - -/** - * Simple scope implementation which creates object based on a flag. - * - * @author Costin Leau - * @author Chris Beams - */ -public class CustomScope implements Scope { - - public boolean createNewScope = true; - - private Map beans = new HashMap(); - - @Override - public Object get(String name, ObjectFactory objectFactory) { - if (createNewScope) { - beans.clear(); - // reset the flag back - createNewScope = false; - } - - Object bean = beans.get(name); - // if a new object is requested or none exists under the current - // name, create one - if (bean == null) { - beans.put(name, objectFactory.getObject()); - } - - return beans.get(name); - } - - @Override - public String getConversationId() { - return null; - } - - @Override - public void registerDestructionCallback(String name, Runnable callback) { - // do nothing - } - - @Override - public Object remove(String name) { - return beans.remove(name); - } - - @Override - public Object resolveContextualObject(String key) { - return null; - } - -} diff --git a/spring-context/src/test/java/test/beans/DependsOnTestBean.java b/spring-context/src/test/java/test/beans/DependsOnTestBean.java deleted file mode 100644 index d784bae712..0000000000 --- a/spring-context/src/test/java/test/beans/DependsOnTestBean.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -public class DependsOnTestBean { - - public TestBean tb; - - private int state; - - public void setTestBean(TestBean tb) { - this.tb = tb; - } - - public int getState() { - return state; - } - - public TestBean getTestBean() { - return tb; - } - -} diff --git a/spring-context/src/test/java/test/beans/INestedTestBean.java b/spring-context/src/test/java/test/beans/INestedTestBean.java deleted file mode 100644 index 4cdf0cfc5c..0000000000 --- a/spring-context/src/test/java/test/beans/INestedTestBean.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -public interface INestedTestBean { - - String getCompany(); - -} diff --git a/spring-context/src/test/java/test/beans/IOther.java b/spring-context/src/test/java/test/beans/IOther.java deleted file mode 100644 index cfd81f2bad..0000000000 --- a/spring-context/src/test/java/test/beans/IOther.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -public interface IOther { - - void absquatulate(); - -} diff --git a/spring-context/src/test/java/test/beans/ITestBean.java b/spring-context/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 242d5e3850..0000000000 --- a/spring-context/src/test/java/test/beans/ITestBean.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -import java.io.IOException; - - -/** - * Interface used for test beans. Two methods are the same as on Person, but if this extends - * person it breaks quite a few tests - * - * @author Rod Johnson - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - /** - * t null no error. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; -} diff --git a/spring-context/src/test/java/test/beans/IndexedTestBean.java b/spring-context/src/test/java/test/beans/IndexedTestBean.java deleted file mode 100644 index 8cef5b2321..0000000000 --- a/spring-context/src/test/java/test/beans/IndexedTestBean.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2002-2008 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] { tb0, tb1 }; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} diff --git a/spring-context/src/test/java/test/beans/NestedTestBean.java b/spring-context/src/test/java/test/beans/NestedTestBean.java deleted file mode 100644 index 0546fdadeb..0000000000 --- a/spring-context/src/test/java/test/beans/NestedTestBean.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = ((company != null) ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - @Override - public int hashCode() { - return this.company.hashCode(); - } - - @Override - public String toString() { - return "NestedTestBean: " + this.company; - } - -} diff --git a/spring-context/src/test/java/test/beans/TestBean.java b/spring-context/src/test/java/test/beans/TestBean.java deleted file mode 100644 index 4b98eab870..0000000000 --- a/spring-context/src/test/java/test/beans/TestBean.java +++ /dev/null @@ -1,436 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package test.beans; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; - -import org.springframework.util.ObjectUtils; - -import java.io.IOException; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - - -/** - * Simple test bean used for testing bean factories, AOP framework etc. - * - * @author Rod Johnson - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean spouse; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouse = spouse; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouse = spouse; - this.someProperties = someProperties; - } - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return spouse; - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouse = spouse; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String[] getStringArray() { - return stringArray; - } - - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setDoctor(INestedTestBean bean) { - doctor = bean; - } - - public void setLawyer(INestedTestBean bean) { - lawyer = bean; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - /** - * @see ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - - /** - * @see ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - - if ((other == null) || !(other instanceof TestBean)) { - return false; - } - - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && (this.age == tb2.age)); - } - - @Override - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if ((this.name != null) && (other instanceof TestBean)) { - return this.name.compareTo(((TestBean) other).getName()); - } - - return 1; - } - - @Override - public String toString() { - String s = "name=" + name + "; age=" + age + "; touchy=" + touchy; - s += "; spouse={" + ((spouse != null) ? spouse.getName() : null) + "}"; - return s; - } - -} diff --git a/spring-context/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerWithExpressionLanguageTests.xml b/spring-context/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerWithExpressionLanguageTests.xml index 1067cbc26c..3982b48c7c 100644 --- a/spring-context/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerWithExpressionLanguageTests.xml +++ b/spring-context/src/test/resources/org/springframework/beans/factory/xml/simplePropertyNamespaceHandlerWithExpressionLanguageTests.xml @@ -4,8 +4,8 @@ xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + - + diff --git a/spring-context/src/test/resources/org/springframework/context/support/simpleThreadScopeTests.xml b/spring-context/src/test/resources/org/springframework/context/support/simpleThreadScopeTests.xml index 2b71bd3001..efb31d0297 100644 --- a/spring-context/src/test/resources/org/springframework/context/support/simpleThreadScopeTests.xml +++ b/spring-context/src/test/resources/org/springframework/context/support/simpleThreadScopeTests.xml @@ -14,34 +14,34 @@ - + - override - override @@ -42,7 +42,7 @@ - + myname diff --git a/spring-orm/src/test/resources/org/springframework/beans/factory/xml/test.xml b/spring-orm/src/test/resources/org/springframework/beans/factory/xml/test.xml index e67e310136..933e66b7d0 100644 --- a/spring-orm/src/test/resources/org/springframework/beans/factory/xml/test.xml +++ b/spring-orm/src/test/resources/org/springframework/beans/factory/xml/test.xml @@ -3,7 +3,7 @@ - + I have no properties and I'm happy without them. @@ -12,7 +12,7 @@ - + aliased @@ -20,17 +20,17 @@ - + aliased - + aliased - + @@ -40,7 +40,7 @@ - + Rod 31 @@ -52,29 +52,29 @@ - + Kerry 34 - + Kathy 28 - + typeMismatch 34x - + - true @@ -85,10 +85,10 @@ - + - + false @@ -113,14 +113,14 @@ - + listenerVeto 66 - + - + this is a ]]> diff --git a/spring-test/src/test/java/org/springframework/beans/Colour.java b/spring-test/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index 194e003797..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings({ "serial", "deprecation" }) -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - - private Colour(int code, String label) { - super(code, label); - } - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/beans/Employee.java b/spring-test/src/test/java/org/springframework/beans/Employee.java deleted file mode 100644 index 9289e45137..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/Employee.java +++ /dev/null @@ -1,39 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public class Employee extends TestBean { - - private String co; - - /** - * Constructor for Employee. - */ - public Employee() { - super(); - } - - public String getCompany() { - return co; - } - - public void setCompany(String co) { - this.co = co; - } - -} diff --git a/spring-test/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-test/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/beans/IOther.java b/spring-test/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/beans/ITestBean.java b/spring-test/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-test/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index cd1724f264..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -@SuppressWarnings("rawtypes") -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - @SuppressWarnings("unchecked") - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] { tb0, tb1 }; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-test/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/beans/TestBean.java b/spring-test/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 3ce93f7c43..0000000000 --- a/spring-test/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,455 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -@SuppressWarnings("rawtypes") -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] { spouse }; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] { spouse }; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] { spouse }; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - /** - * @see ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - - /** - * @see ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-test/src/test/java/org/springframework/test/AbstractSpr3350SingleSpringContextTests.java b/spring-test/src/test/java/org/springframework/test/AbstractSpr3350SingleSpringContextTests.java index 06c94aa441..ba8c81c294 100644 --- a/spring-test/src/test/java/org/springframework/test/AbstractSpr3350SingleSpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/AbstractSpr3350SingleSpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ApplicationContext; diff --git a/spring-test/src/test/java/org/springframework/test/PropertiesBasedSpr3350SingleSpringContextTests-context.properties b/spring-test/src/test/java/org/springframework/test/PropertiesBasedSpr3350SingleSpringContextTests-context.properties index 307a4e93df..7b96503a3f 100644 --- a/spring-test/src/test/java/org/springframework/test/PropertiesBasedSpr3350SingleSpringContextTests-context.properties +++ b/spring-test/src/test/java/org/springframework/test/PropertiesBasedSpr3350SingleSpringContextTests-context.properties @@ -1,2 +1,2 @@ -cat.(class)=org.springframework.beans.Pet +cat.(class)=org.springframework.tests.sample.beans.Pet cat.$0=Garfield diff --git a/spring-test/src/test/java/org/springframework/test/XmlBasedSpr3350SingleSpringContextTests-context.xml b/spring-test/src/test/java/org/springframework/test/XmlBasedSpr3350SingleSpringContextTests-context.xml index 7236045484..b1939de12f 100644 --- a/spring-test/src/test/java/org/springframework/test/XmlBasedSpr3350SingleSpringContextTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/XmlBasedSpr3350SingleSpringContextTests-context.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties index 1efbb6201e..45d36076bb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests-context.properties @@ -1,4 +1,4 @@ -dog.(class)=org.springframework.beans.Pet +dog.(class)=org.springframework.tests.sample.beans.Pet dog.$0=Fido testString2.(class)=java.lang.String diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java index eb6f44f176..3a976747ea 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesAndInheritedLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextLoader; diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests-context.properties b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests-context.properties index 1efbb6201e..45d36076bb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests-context.properties +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests-context.properties @@ -1,4 +1,4 @@ -dog.(class)=org.springframework.beans.Pet +dog.(class)=org.springframework.tests.sample.beans.Pet dog.$0=Fido testString2.(class)=java.lang.String diff --git a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java index 81f51d459a..77f079aec2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/configuration/ContextConfigurationWithPropertiesExtendingPropertiesTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextLoader; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests-context.xml index acdab7073c..9f2fdef412 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests-context.xml @@ -3,13 +3,13 @@ xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> - + - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests.java index 147679ed5f..735f96a01f 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit38/ConcreteTransactionalJUnit38SpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import javax.sql.DataSource; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests-context.xml index a219470ce6..a91178410a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests-context.xml @@ -8,13 +8,13 @@ - + - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java index bab1df5ff8..c88aed37d1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ConcreteTransactionalJUnit4SpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ import javax.sql.DataSource; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java index 0c06882087..3ee77974a0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/CustomDefaultContextLoaderClassSpringRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.model.InitializationError; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.support.GenericPropertiesContextLoader; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context1.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context1.xml index 2f6eda6962..b40fed69ca 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context1.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context1.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context2.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context2.xml index cb75b8accd..f6a90a62ea 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context2.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/MultipleResourcesSpringJUnit4ClassRunnerAppCtxTests-context2.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests-context.xml index 62206fde4a..67590a6b58 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests-context.xml @@ -2,19 +2,19 @@ - + - + - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java index ed2f58de11..bf07919721 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/ParameterizedDependencyInjectionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties index 0e62ef734f..6df81585fb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests-context.properties @@ -1,4 +1,4 @@ -cat.(class)=org.springframework.beans.Pet +cat.(class)=org.springframework.tests.sample.beans.Pet cat.$0=Garfield testString.(class)=java.lang.String diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java index d41dbb5026..b5d74839f6 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/PropertiesBasedSpringJUnit4ClassRunnerAppCtxTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import java.util.Properties; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml index dffdb30f99..704b347873 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml @@ -2,13 +2,13 @@ - + - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java index 399f6a6103..4973d7c68d 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,8 @@ import javax.inject.Named; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.BeansException; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java index 46dfd6725a..a0c51ded52 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/BeanOverridingDefaultConfigClassesInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java index 469e35f8d9..e8a440a230 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesBaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java index e426d1e7f3..05c74a29eb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultConfigClassesInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java index 9f29d9a54a..7af6a541b4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderBeanOverridingDefaultConfigClassesInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java index 278804817e..00da19f130 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesBaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java index 3cf8f064d0..9b4793e462 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderDefaultConfigClassesInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java index b54613b491..6613a695b4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesBaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java index c060ea4b55..a0f7668ae2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/DefaultLoaderExplicitConfigClassesInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java index a3d2ecee16..7da5e68bd0 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesBaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java index 54596ae6d2..cca20f4827 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/ExplicitConfigClassesInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/PojoAndStringConfig.java b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/PojoAndStringConfig.java index 0208925227..19eefe388a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/PojoAndStringConfig.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/annotation/PojoAndStringConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package org.springframework.test.context.junit4.annotation; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java index cc26b849db..836dca41df 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileAnnotationConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileConfig.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileConfig.java index 98cc3af149..44b5675a89 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileConfig.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DefaultProfileConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.profile.annotation; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileConfig.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileConfig.java index 9fb695889a..cafc8b6e47 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileConfig.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/annotation/DevProfileConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.profile.annotation; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java index f6f2907f87..07a8d2d5ff 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileAnnotationConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileConfig.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileConfig.java index a4af38435a..818212dd3e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileConfig.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/DefaultProfileConfig.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.profile.importresource; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/import.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/import.xml index 8427a674a3..3861d0ec59 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/import.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/importresource/import.xml @@ -3,7 +3,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests-context.xml index 1fc6d4ecfc..0e672de084 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests-context.xml @@ -2,12 +2,12 @@ - + - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java index f79a9b0aa5..1ed4f5467a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/profile/xml/DefaultProfileXmlConfigTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,8 +22,8 @@ import static org.junit.Assert.assertNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests-context.xml index 55a4cff1e8..7238260bd4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/BeanOverridingDefaultLocationsInheritedTests-context.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests-context.xml index 2f6eda6962..b40fed69ca 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests-context.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java index fb373a0347..7131201d43 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsBaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests-context.xml index cb75b8accd..f6a90a62ea 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests-context.xml @@ -2,7 +2,7 @@ - + diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java index 9896e35880..1f488ec26c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/DefaultLocationsInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java index 1c9fbe9125..cd81b6becb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsBaseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java index 5c99fefa39..b01764251c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr3896/ExplicitLocationsInheritedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Test; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java index d8b7fcacf3..54b55c8c44 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java index 373166d9b4..6e0f84f733 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassWithAtConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import static org.junit.Assert.assertSame; import javax.sql.DataSource; import org.junit.Before; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java index 3f6a054ecb..622f0dfe68 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/TransactionalAnnotatedConfigClassesWithoutAtConfigurationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import static org.junit.Assert.assertNotSame; import javax.sql.DataSource; import org.junit.Before; -import org.springframework.beans.Employee; +import org.springframework.tests.sample.beans.Employee; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.JdbcTemplate; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java index cd20e40f3f..5dbba76acb 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9604/LookUpTxMgrViaTransactionManagementConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9604; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.TransactionManagementConfigurer; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java index 72af7e7a7b..78720a8f5e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpNonexistentTxMgrTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9645; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -24,7 +24,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; /** diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java index 6f1525229f..331342d4fc 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndDefaultNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9645; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java index d8c070c504..76a82b823c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndNameTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9645; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -27,7 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; import org.springframework.test.context.transaction.TransactionConfiguration; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java index bbc0951e4f..8492b02d5a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtClassLevelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9645; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java index b9d6b4b6ae..363d47a9b2 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeAndQualifierAtMethodLevelTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9645; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java index b7a52aa961..957533f913 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9645/LookUpTxMgrByTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.test.context.junit4.spr9645; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; @@ -26,7 +26,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.AfterTransaction; import org.springframework.test.context.transaction.BeforeTransaction; -import org.springframework.test.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.Transactional; diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java index 4cfb6b8abc..f20e466410 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/AnnotationConfigTransactionalTestNGSpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,8 +23,8 @@ import static org.testng.Assert.assertNotNull; import javax.sql.DataSource; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests-context.xml b/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests-context.xml index 11e92153da..a46a6da3d1 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests-context.xml +++ b/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests-context.xml @@ -5,10 +5,10 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> - - + diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests.java index 0ad8862c2e..ee25cb32e4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/ConcreteTransactionalTestNGSpringContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import static org.testng.Assert.assertTrue; import javax.annotation.Resource; -import org.springframework.beans.Employee; -import org.springframework.beans.Pet; +import org.springframework.tests.sample.beans.Employee; +import org.springframework.tests.sample.beans.Pet; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; diff --git a/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java b/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java index c07b25a927..829d70ffec 100644 --- a/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; diff --git a/spring-test/src/test/resources/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests-context.xml b/spring-test/src/test/resources/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests-context.xml index 0930460eea..7f2a6c5b23 100644 --- a/spring-test/src/test/resources/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests-context.xml +++ b/spring-test/src/test/resources/org/springframework/test/context/web/RequestAndSessionScopedBeansWacTests-context.xml @@ -2,10 +2,10 @@ - + - + diff --git a/spring-tx/src/test/java/org/springframework/beans/Colour.java b/spring-tx/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-tx/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-tx/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index c5360de531..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-tx/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-tx/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-tx/src/test/java/org/springframework/beans/IOther.java b/spring-tx/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-tx/src/test/java/org/springframework/beans/ITestBean.java b/spring-tx/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-tx/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-tx/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770e..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-tx/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-tx/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-tx/src/test/java/org/springframework/beans/TestBean.java b/spring-tx/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 6d71de7576..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see org.springframework.beans.ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see org.springframework.beans.ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see org.springframework.beans.IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-tx/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java b/spring-tx/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java deleted file mode 100644 index c7066b5cc7..0000000000 --- a/spring-tx/src/test/java/org/springframework/beans/factory/parsing/CollectingReaderEventListener.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory.parsing; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.springframework.core.CollectionFactory; - -/** - * @author Rob Harrop - * @author Juergen Hoeller - */ -public class CollectingReaderEventListener implements ReaderEventListener { - - private final List defaults = new LinkedList(); - - private final Map componentDefinitions = new LinkedHashMap<>(8); - - private final Map aliasMap = new LinkedHashMap<>(8); - - private final List imports = new LinkedList(); - - - @Override - public void defaultsRegistered(DefaultsDefinition defaultsDefinition) { - this.defaults.add(defaultsDefinition); - } - - public List getDefaults() { - return Collections.unmodifiableList(this.defaults); - } - - @Override - public void componentRegistered(ComponentDefinition componentDefinition) { - this.componentDefinitions.put(componentDefinition.getName(), componentDefinition); - } - - public ComponentDefinition getComponentDefinition(String name) { - return (ComponentDefinition) this.componentDefinitions.get(name); - } - - public ComponentDefinition[] getComponentDefinitions() { - Collection collection = this.componentDefinitions.values(); - return (ComponentDefinition[]) collection.toArray(new ComponentDefinition[collection.size()]); - } - - @Override - public void aliasRegistered(AliasDefinition aliasDefinition) { - List aliases = (List) this.aliasMap.get(aliasDefinition.getBeanName()); - if(aliases == null) { - aliases = new ArrayList(); - this.aliasMap.put(aliasDefinition.getBeanName(), aliases); - } - aliases.add(aliasDefinition); - } - - public List getAliases(String beanName) { - List aliases = (List) this.aliasMap.get(beanName); - return aliases == null ? null : Collections.unmodifiableList(aliases); - } - - @Override - public void importProcessed(ImportDefinition importDefinition) { - this.imports.add(importDefinition); - } - - public List getImports() { - return Collections.unmodifiableList(this.imports); - } - -} diff --git a/spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java b/spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java deleted file mode 100644 index 4e1641b2cd..0000000000 --- a/spring-tx/src/test/java/org/springframework/mock/jndi/SimpleNamingContext.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.jndi; - -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; -import javax.naming.Binding; -import javax.naming.Context; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NameNotFoundException; -import javax.naming.NameParser; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.OperationNotSupportedException; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.util.StringUtils; - -/** - * Simple implementation of a JNDI naming context. - * Only supports binding plain Objects to String names. - * Mainly for test environments, but also usable for standalone applications. - * - *

This class is not intended for direct usage by applications, although it - * can be used for example to override JndiTemplate's {@code createInitialContext} - * method in unit tests. Typically, SimpleNamingContextBuilder will be used to - * set up a JVM-level JNDI environment. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @see SimpleNamingContextBuilder - * @see org.springframework.jndi.JndiTemplate#createInitialContext - */ -public class SimpleNamingContext implements Context { - - private final Log logger = LogFactory.getLog(getClass()); - - private final String root; - - private final Hashtable boundObjects; - - private final Hashtable environment = new Hashtable(); - - - /** - * Create a new naming context. - */ - public SimpleNamingContext() { - this(""); - } - - /** - * Create a new naming context with the given naming root. - */ - public SimpleNamingContext(String root) { - this.root = root; - this.boundObjects = new Hashtable(); - } - - /** - * Create a new naming context with the given naming root, - * the given name/object map, and the JNDI environment entries. - */ - public SimpleNamingContext(String root, Hashtable boundObjects, Hashtable env) { - this.root = root; - this.boundObjects = boundObjects; - if (env != null) { - this.environment.putAll(env); - } - } - - - // Actual implementations of Context methods follow - - @Override - public NamingEnumeration list(String root) throws NamingException { - if (logger.isDebugEnabled()) { - logger.debug("Listing name/class pairs under [" + root + "]"); - } - return new NameClassPairEnumeration(this, root); - } - - @Override - public NamingEnumeration listBindings(String root) throws NamingException { - if (logger.isDebugEnabled()) { - logger.debug("Listing bindings under [" + root + "]"); - } - return new BindingEnumeration(this, root); - } - - /** - * Look up the object with the given name. - *

Note: Not intended for direct use by applications. - * Will be used by any standard InitialContext JNDI lookups. - * @throws javax.naming.NameNotFoundException if the object could not be found - */ - @Override - public Object lookup(String lookupName) throws NameNotFoundException { - String name = this.root + lookupName; - if (logger.isDebugEnabled()) { - logger.debug("Static JNDI lookup: [" + name + "]"); - } - if ("".equals(name)) { - return new SimpleNamingContext(this.root, this.boundObjects, this.environment); - } - Object found = this.boundObjects.get(name); - if (found == null) { - if (!name.endsWith("/")) { - name = name + "/"; - } - for (String boundName : this.boundObjects.keySet()) { - if (boundName.startsWith(name)) { - return new SimpleNamingContext(name, this.boundObjects, this.environment); - } - } - throw new NameNotFoundException( - "Name [" + this.root + lookupName + "] not bound; " + this.boundObjects.size() + " bindings: [" + - StringUtils.collectionToDelimitedString(this.boundObjects.keySet(), ",") + "]"); - } - return found; - } - - @Override - public Object lookupLink(String name) throws NameNotFoundException { - return lookup(name); - } - - /** - * Bind the given object to the given name. - * Note: Not intended for direct use by applications - * if setting up a JVM-level JNDI environment. - * Use SimpleNamingContextBuilder to set up JNDI bindings then. - * @see org.springframework.mock.jndi.SimpleNamingContextBuilder#bind - */ - @Override - public void bind(String name, Object obj) { - if (logger.isInfoEnabled()) { - logger.info("Static JNDI binding: [" + this.root + name + "] = [" + obj + "]"); - } - this.boundObjects.put(this.root + name, obj); - } - - @Override - public void unbind(String name) { - if (logger.isInfoEnabled()) { - logger.info("Static JNDI remove: [" + this.root + name + "]"); - } - this.boundObjects.remove(this.root + name); - } - - @Override - public void rebind(String name, Object obj) { - bind(name, obj); - } - - @Override - public void rename(String oldName, String newName) throws NameNotFoundException { - Object obj = lookup(oldName); - unbind(oldName); - bind(newName, obj); - } - - @Override - public Context createSubcontext(String name) { - String subcontextName = this.root + name; - if (!subcontextName.endsWith("/")) { - subcontextName += "/"; - } - Context subcontext = new SimpleNamingContext(subcontextName, this.boundObjects, this.environment); - bind(name, subcontext); - return subcontext; - } - - @Override - public void destroySubcontext(String name) { - unbind(name); - } - - @Override - public String composeName(String name, String prefix) { - return prefix + name; - } - - @Override - public Hashtable getEnvironment() { - return this.environment; - } - - @Override - public Object addToEnvironment(String propName, Object propVal) { - return this.environment.put(propName, propVal); - } - - @Override - public Object removeFromEnvironment(String propName) { - return this.environment.remove(propName); - } - - @Override - public void close() { - } - - - // Unsupported methods follow: no support for javax.naming.Name - - @Override - public NamingEnumeration list(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public NamingEnumeration listBindings(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public Object lookup(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public Object lookupLink(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public void bind(Name name, Object obj) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public void unbind(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public void rebind(Name name, Object obj) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public void rename(Name oldName, Name newName) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public Context createSubcontext(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public void destroySubcontext(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public String getNameInNamespace() throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public NameParser getNameParser(Name name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public NameParser getNameParser(String name) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - @Override - public Name composeName(Name name, Name prefix) throws NamingException { - throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]"); - } - - - private static abstract class AbstractNamingEnumeration implements NamingEnumeration { - - private Iterator iterator; - - private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException { - if (!"".equals(proot) && !proot.endsWith("/")) { - proot = proot + "/"; - } - String root = context.root + proot; - Map contents = new HashMap(); - for (String boundName : context.boundObjects.keySet()) { - if (boundName.startsWith(root)) { - int startIndex = root.length(); - int endIndex = boundName.indexOf('/', startIndex); - String strippedName = - (endIndex != -1 ? boundName.substring(startIndex, endIndex) : boundName.substring(startIndex)); - if (!contents.containsKey(strippedName)) { - try { - contents.put(strippedName, createObject(strippedName, context.lookup(proot + strippedName))); - } - catch (NameNotFoundException ex) { - // cannot happen - } - } - } - } - if (contents.size() == 0) { - throw new NamingException("Invalid root: [" + context.root + proot + "]"); - } - this.iterator = contents.values().iterator(); - } - - protected abstract T createObject(String strippedName, Object obj); - - @Override - public boolean hasMore() { - return this.iterator.hasNext(); - } - - @Override - public T next() { - return this.iterator.next(); - } - - @Override - public boolean hasMoreElements() { - return this.iterator.hasNext(); - } - - @Override - public T nextElement() { - return this.iterator.next(); - } - - @Override - public void close() { - } - } - - - private static class NameClassPairEnumeration extends AbstractNamingEnumeration { - - private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException { - super(context, root); - } - - @Override - protected NameClassPair createObject(String strippedName, Object obj) { - return new NameClassPair(strippedName, obj.getClass().getName()); - } - } - - - private static class BindingEnumeration extends AbstractNamingEnumeration { - - private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException { - super(context, root); - } - - @Override - protected Binding createObject(String strippedName, Object obj) { - return new Binding(strippedName, obj); - } - } - -} diff --git a/spring-test/src/test/java/org/springframework/test/transaction/CallCountingTransactionManager.java b/spring-tx/src/test/java/org/springframework/tests/transaction/CallCountingTransactionManager.java similarity index 97% rename from spring-test/src/test/java/org/springframework/test/transaction/CallCountingTransactionManager.java rename to spring-tx/src/test/java/org/springframework/tests/transaction/CallCountingTransactionManager.java index 13f3b5d360..d3852d4e34 100644 --- a/spring-test/src/test/java/org/springframework/test/transaction/CallCountingTransactionManager.java +++ b/spring-tx/src/test/java/org/springframework/tests/transaction/CallCountingTransactionManager.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.test.transaction; +package org.springframework.tests.transaction; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.support.AbstractPlatformTransactionManager; @@ -33,7 +33,6 @@ public class CallCountingTransactionManager extends AbstractPlatformTransactionM public int rollbacks; public int inflight; - @Override protected Object doGetTransaction() { return new Object(); diff --git a/spring-tx/src/test/java/org/springframework/transaction/MockJtaTransaction.java b/spring-tx/src/test/java/org/springframework/tests/transaction/MockJtaTransaction.java similarity index 96% rename from spring-tx/src/test/java/org/springframework/transaction/MockJtaTransaction.java rename to spring-tx/src/test/java/org/springframework/tests/transaction/MockJtaTransaction.java index e2066af4d9..eb68f25517 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/MockJtaTransaction.java +++ b/spring-tx/src/test/java/org/springframework/tests/transaction/MockJtaTransaction.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.transaction; +package org.springframework.tests.transaction; import javax.transaction.Status; import javax.transaction.Synchronization; diff --git a/spring-tx/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java b/spring-tx/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java deleted file mode 100644 index b1862dd893..0000000000 --- a/spring-tx/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.transaction; - -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -import org.springframework.transaction.support.DefaultTransactionStatus; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -@SuppressWarnings("serial") -public class CallCountingTransactionManager extends AbstractPlatformTransactionManager { - - public TransactionDefinition lastDefinition; - public int begun; - public int commits; - public int rollbacks; - public int inflight; - - @Override - protected Object doGetTransaction() { - return new Object(); - } - - @Override - protected void doBegin(Object transaction, TransactionDefinition definition) { - this.lastDefinition = definition; - ++begun; - ++inflight; - } - - @Override - protected void doCommit(DefaultTransactionStatus status) { - ++commits; - --inflight; - } - - @Override - protected void doRollback(DefaultTransactionStatus status) { - ++rollbacks; - --inflight; - } - - public void clear() { - begun = commits = rollbacks = inflight = 0; - } - -} diff --git a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java index 11566aeee7..04e937b7ec 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import javax.transaction.UserTransaction; import junit.framework.TestCase; import org.easymock.MockControl; -import org.springframework.mock.jndi.ExpectedLookupTemplate; +import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.transaction.jta.UserTransactionAdapter; import org.springframework.transaction.support.TransactionCallbackWithoutResult; diff --git a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java index 8bb6181200..c13ea6bc41 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/JtaTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import junit.framework.TestCase; import org.easymock.MockControl; import org.springframework.dao.OptimisticLockingFailureException; +import org.springframework.tests.transaction.MockJtaTransaction; import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallbackWithoutResult; diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java index 38c7e20d22..3f4286e51b 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerEventTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ package org.springframework.transaction; import junit.framework.TestCase; import org.springframework.beans.factory.parsing.BeanComponentDefinition; -import org.springframework.beans.factory.parsing.CollectingReaderEventListener; import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; +import org.springframework.tests.beans.CollectingReaderEventListener; /** * @author Torsten Juergeleit diff --git a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java index 7808f43b99..813a905e07 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/TxNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,8 @@ import java.lang.reflect.Method; import junit.framework.TestCase; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.transaction.interceptor.TransactionAttribute; diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java index 7caafe92c2..ad05997a07 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionAttributeSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import org.junit.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.interceptor.NoRollbackRuleAttribute; import org.springframework.transaction.interceptor.RollbackRuleAttribute; import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute; diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java index 21c5f5374f..556cb59965 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.transaction.annotation; import junit.framework.TestCase; import org.springframework.aop.framework.ProxyFactory; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.interceptor.TransactionInterceptor; import org.springframework.transaction.support.TransactionSynchronizationManager; diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java index 0f0deca866..92f1ed6514 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/AnnotationTransactionNamespaceHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.stereotype.Service; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; /** * @author Rob Harrop diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java b/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java index 417859b43e..5c11e26d5d 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Service; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.AnnotationTransactionNamespaceHandlerTests.TransactionalTestBean; diff --git a/spring-tx/src/test/java/org/springframework/transaction/annotation/annotationTransactionNamespaceHandlerTests.xml b/spring-tx/src/test/java/org/springframework/transaction/annotation/annotationTransactionNamespaceHandlerTests.xml index d30fd87be1..bd659fd893 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/annotation/annotationTransactionNamespaceHandlerTests.xml +++ b/spring-tx/src/test/java/org/springframework/transaction/annotation/annotationTransactionNamespaceHandlerTests.xml @@ -11,7 +11,7 @@ - + diff --git a/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java b/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java index d6a79128d0..ee458c0cf8 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/config/AnnotationDrivenTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import org.springframework.aop.support.AopUtils; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.SerializationTestUtils; diff --git a/spring-tx/src/test/java/org/springframework/transaction/config/TransactionManagerConfiguration.java b/spring-tx/src/test/java/org/springframework/transaction/config/TransactionManagerConfiguration.java index 11a649ad50..965a0db01e 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/config/TransactionManagerConfiguration.java +++ b/spring-tx/src/test/java/org/springframework/transaction/config/TransactionManagerConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.transaction.config; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; /** diff --git a/spring-tx/src/test/java/org/springframework/transaction/config/annotationDrivenProxyTargetClassTests.xml b/spring-tx/src/test/java/org/springframework/transaction/config/annotationDrivenProxyTargetClassTests.xml index ea4f7189c8..a707e84fd3 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/config/annotationDrivenProxyTargetClassTests.xml +++ b/spring-tx/src/test/java/org/springframework/transaction/config/annotationDrivenProxyTargetClassTests.xml @@ -12,11 +12,11 @@ - + - + diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java index 7a818f701b..2b01ef4a91 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,8 @@ import java.lang.reflect.Method; import junit.framework.TestCase; import org.easymock.MockControl; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.transaction.CannotCreateTransactionException; import org.springframework.transaction.MockCallbackPreferringTransactionManager; diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java index a34a228a45..1ff4a262f4 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,14 +28,14 @@ import org.easymock.MockControl; import org.springframework.aop.support.AopUtils; import org.springframework.aop.support.StaticMethodMatcherPointcut; import org.springframework.aop.target.HotSwappableTargetSource; -import org.springframework.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.beans.FatalBeanException; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; -import org.springframework.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/ImplementsNoInterfaces.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/ImplementsNoInterfaces.java index 302026a7aa..79885dd3ee 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/ImplementsNoInterfaces.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/ImplementsNoInterfaces.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.transaction.interceptor; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * Test for CGLIB proxying that implements no interfaces diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/noTransactionAttributeSource.xml b/spring-tx/src/test/java/org/springframework/transaction/interceptor/noTransactionAttributeSource.xml index 09c860fffd..e9ef193b44 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/noTransactionAttributeSource.xml +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/noTransactionAttributeSource.xml @@ -4,11 +4,11 @@ - + custom 666 - + - + custom 666 @@ -22,16 +22,16 @@ - org.springframework.beans.ITestBean.s*=PROPAGATION_MANDATORY - org.springframework.beans.ITestBean.setAg*=PROPAGATION_REQUIRED - org.springframework.beans.ITestBean.set*= PROPAGATION_SUPPORTS , readOnly + org.springframework.tests.sample.beans.ITestBean.s*=PROPAGATION_MANDATORY + org.springframework.tests.sample.beans.ITestBean.setAg*=PROPAGATION_REQUIRED + org.springframework.tests.sample.beans.ITestBean.set*= PROPAGATION_SUPPORTS , readOnly - org.springframework.beans.ITestBean + org.springframework.tests.sample.beans.ITestBean diff --git a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java index 12c70ed91c..5630bd8219 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/jta/WebSphereUowTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import junit.framework.TestCase; import org.easymock.MockControl; import org.springframework.dao.OptimisticLockingFailureException; -import org.springframework.mock.jndi.ExpectedLookupTemplate; +import org.springframework.tests.mock.jndi.ExpectedLookupTemplate; import org.springframework.transaction.IllegalTransactionStateException; import org.springframework.transaction.NestedTransactionNotSupportedException; import org.springframework.transaction.TransactionDefinition; diff --git a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java index 99f791a532..ff819d3ede 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/support/JtaTransactionManagerSerializationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import javax.transaction.UserTransaction; import junit.framework.TestCase; -import org.springframework.mock.jndi.SimpleNamingContextBuilder; +import org.springframework.tests.mock.jndi.SimpleNamingContextBuilder; import org.springframework.transaction.jta.JtaTransactionManager; import org.springframework.util.SerializationTestUtils; diff --git a/spring-tx/src/test/java/org/springframework/transaction/txNamespaceHandlerTests.xml b/spring-tx/src/test/java/org/springframework/transaction/txNamespaceHandlerTests.xml index 0a4b7e9f1c..a8adf10c6d 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/txNamespaceHandlerTests.xml +++ b/spring-tx/src/test/java/org/springframework/transaction/txNamespaceHandlerTests.xml @@ -26,8 +26,8 @@ - + - + diff --git a/spring-tx/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-tx/src/test/java/org/springframework/util/SerializationTestUtils.java deleted file mode 100644 index dbe6421093..0000000000 --- a/spring-tx/src/test/java/org/springframework/util/SerializationTestUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * The Spring Framework is published under the terms - * of the Apache Software License. - */ - -package org.springframework.util; - -import java.awt.Point; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import junit.framework.TestCase; - -import org.springframework.beans.TestBean; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * Extends TestCase only to test itself. - * - * @author Rod Johnson - */ -public class SerializationTestUtils extends TestCase { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - - return o2; - } - - public SerializationTestUtils(String s) { - super(s); - } - - public void testWithNonSerializableObject() throws IOException { - TestBean o = new TestBean(); - assertFalse(o instanceof Serializable); - - assertFalse(isSerializable(o)); - - try { - testSerialization(o); - fail(); - } - catch (NotSerializableException ex) { - // Ok - } - } - - public void testWithSerializableObject() throws Exception { - int x = 5; - int y = 10; - Point p = new Point(x, y); - assertTrue(p instanceof Serializable); - - testSerialization(p); - - assertTrue(isSerializable(p)); - - Point p2 = (Point) serializeAndDeserialize(p); - assertNotSame(p, p2); - assertEquals(x, (int) p2.getX()); - assertEquals(y, (int) p2.getY()); - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/BeanWithObjectProperty.java b/spring-web/src/test/java/org/springframework/beans/BeanWithObjectProperty.java deleted file mode 100644 index bb5e71f5cd..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/BeanWithObjectProperty.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2002-2005 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.beans; - -/** - * @author Juergen Hoeller - * @since 17.08.2004 - */ -public class BeanWithObjectProperty { - - private Object object; - - public Object getObject() { - return object; - } - - public void setObject(Object object) { - this.object = object; - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/Colour.java b/spring-web/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-web/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-web/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index c5360de531..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-web/src/test/java/org/springframework/beans/FieldAccessBean.java b/spring-web/src/test/java/org/springframework/beans/FieldAccessBean.java deleted file mode 100644 index 61f911902c..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/FieldAccessBean.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * @author Juergen Hoeller - * @since 07.03.2006 - */ -public class FieldAccessBean { - - public String name; - - protected int age; - - private TestBean spouse; - - - public String getName() { - return name; - } - - public int getAge() { - return age; - } - - public TestBean getSpouse() { - return spouse; - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-web/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/IOther.java b/spring-web/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-web/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770e..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-web/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/SerializablePerson.java b/spring-web/src/test/java/org/springframework/beans/SerializablePerson.java deleted file mode 100644 index dbe365f493..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/SerializablePerson.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.util.ObjectUtils; - -/** - * Serializable implementation of the Person interface. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class SerializablePerson implements Person, Serializable { - - private String name; - private int age; - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - @Override - public Object echo(Object o) throws Throwable { - if (o instanceof Throwable) { - throw (Throwable) o; - } - return o; - } - - public boolean equals(Object other) { - if (!(other instanceof SerializablePerson)) { - return false; - } - SerializablePerson p = (SerializablePerson) other; - return p.age == age && ObjectUtils.nullSafeEquals(name, p.name); - } - -} diff --git a/spring-web/src/test/java/org/springframework/beans/TestBean.java b/spring-web/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 1fc36aba37..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,495 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Integer[][] nestedIntegerArray; - - private int[] someIntArray; - - private int[][] nestedIntArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - public void setConcreteSpouse(TestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean getConcreteSpouse() { - return (spouses != null ? (TestBean) spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - @Override - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - @Override - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - @Override - public Integer[][] getNestedIntegerArray() { - return nestedIntegerArray; - } - - @Override - public void setNestedIntegerArray(Integer[][] nestedIntegerArray) { - this.nestedIntegerArray = nestedIntegerArray; - } - - @Override - public int[] getSomeIntArray() { - return someIntArray; - } - - @Override - public void setSomeIntArray(int[] someIntArray) { - this.someIntArray = someIntArray; - } - - @Override - public int[][] getNestedIntArray() { - return nestedIntArray; - } - - @Override - public void setNestedIntArray(int[][] nestedIntArray) { - this.nestedIntArray = nestedIntArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - - @Override - public Object returnsThis() { - return this; - } - - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/beans/factory/DummyFactory.java b/spring-web/src/test/java/org/springframework/beans/factory/DummyFactory.java deleted file mode 100644 index 6fc7e36aa9..0000000000 --- a/spring-web/src/test/java/org/springframework/beans/factory/DummyFactory.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; - -/** - * Simple factory to allow testing of FactoryBean support in AbstractBeanFactory. - * Depending on whether its singleton property is set, it will return a singleton - * or a prototype instance. - * - *

Implements InitializingBean interface, so we can check that - * factories get this lifecycle callback if they want. - * - * @author Rod Johnson - * @since 10.03.2003 - */ -public class DummyFactory - implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { - - public static final String SINGLETON_NAME = "Factory singleton"; - - private static boolean prototypeCreated; - - /** - * Clear static state. - */ - public static void reset() { - prototypeCreated = false; - } - - - /** - * Default is for factories to return a singleton instance. - */ - private boolean singleton = true; - - private String beanName; - - private AutowireCapableBeanFactory beanFactory; - - private boolean postProcessed; - - private boolean initialized; - - private TestBean testBean; - - private TestBean otherTestBean; - - - public DummyFactory() { - this.testBean = new TestBean(); - this.testBean.setName(SINGLETON_NAME); - this.testBean.setAge(25); - } - - /** - * Return if the bean managed by this factory is a singleton. - * @see FactoryBean#isSingleton() - */ - @Override - public boolean isSingleton() { - return this.singleton; - } - - /** - * Set if the bean managed by this factory is a singleton. - */ - public void setSingleton(boolean singleton) { - this.singleton = singleton; - } - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = (AutowireCapableBeanFactory) beanFactory; - this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName); - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - public void setOtherTestBean(TestBean otherTestBean) { - this.otherTestBean = otherTestBean; - this.testBean.setSpouse(otherTestBean); - } - - public TestBean getOtherTestBean() { - return otherTestBean; - } - - @Override - public void afterPropertiesSet() { - if (initialized) { - throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean"); - } - this.initialized = true; - } - - /** - * Was this initialized by invocation of the - * afterPropertiesSet() method from the InitializingBean interface? - */ - public boolean wasInitialized() { - return initialized; - } - - public static boolean wasPrototypeCreated() { - return prototypeCreated; - } - - - /** - * Return the managed object, supporting both singleton - * and prototype mode. - * @see FactoryBean#getObject() - */ - @Override - public Object getObject() throws BeansException { - if (isSingleton()) { - return this.testBean; - } - else { - TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11); - if (this.beanFactory != null) { - this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName); - } - prototypeCreated = true; - return prototype; - } - } - - @Override - public Class getObjectType() { - return TestBean.class; - } - - - @Override - public void destroy() { - if (this.testBean != null) { - this.testBean.setName(null); - } - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java index 2af35321ff..3a3d4a6885 100644 --- a/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java +++ b/spring-web/src/test/java/org/springframework/http/client/AbstractHttpRequestFactoryTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,6 +43,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; +import org.springframework.tests.web.FreePortScanner; import org.springframework.util.FileCopyUtils; public abstract class AbstractHttpRequestFactoryTestCase { diff --git a/spring-web/src/test/java/org/springframework/http/client/FreePortScanner.java b/spring-web/src/test/java/org/springframework/http/client/FreePortScanner.java deleted file mode 100644 index 83add2ceaf..0000000000 --- a/spring-web/src/test/java/org/springframework/http/client/FreePortScanner.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.http.client; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.util.Random; - -import org.springframework.util.Assert; - -/** - * Utility class that finds free BSD ports for use in testing scenario's. - * - * @author Ben Hale - * @author Arjen Poutsma - */ -public abstract class FreePortScanner { - - private static final int MIN_SAFE_PORT = 1024; - - private static final int MAX_PORT = 65535; - - private static final Random random = new Random(); - - /** - * Returns the number of a free port in the default range. - */ - public static int getFreePort() { - return getFreePort(MIN_SAFE_PORT, MAX_PORT); - } - - /** - * Returns the number of a free port in the given range. - */ - public static int getFreePort(int minPort, int maxPort) { - Assert.isTrue(minPort > 0, "'minPort' must be larger than 0"); - Assert.isTrue(maxPort > minPort, "'maxPort' must be larger than minPort"); - int portRange = maxPort - minPort; - int candidatePort; - int searchCounter = 0; - do { - if (++searchCounter > portRange) { - throw new IllegalStateException( - String.format("There were no ports available in the range %d to %d", minPort, maxPort)); - } - candidatePort = getRandomPort(minPort, portRange); - } - while (!isPortAvailable(candidatePort)); - - return candidatePort; - } - - private static int getRandomPort(int minPort, int portRange) { - return minPort + random.nextInt(portRange); - } - - private static boolean isPortAvailable(int port) { - ServerSocket serverSocket; - try { - serverSocket = new ServerSocket(); - } - catch (IOException ex) { - throw new IllegalStateException("Unable to create ServerSocket.", ex); - } - - try { - InetSocketAddress sa = new InetSocketAddress(port); - serverSocket.bind(sa); - return true; - } - catch (IOException ex) { - return false; - } - finally { - try { - serverSocket.close(); - } - catch (IOException ex) { - // ignore - } - } - } - -} diff --git a/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java b/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java index 6617a787d5..d26b34565f 100644 --- a/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/caucho/CauchoRemotingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import com.caucho.burlap.client.BurlapProxyFactory; import com.caucho.hessian.client.HessianProxyFactory; import junit.framework.TestCase; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.remoting.RemoteAccessException; /** diff --git a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java index 71c463177a..b436e306ec 100644 --- a/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/httpinvoker/HttpInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.aopalliance.intercept.MethodInvocation; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; diff --git a/spring-webmvc/src/test/java/org/springframework/http/client/FreePortScanner.java b/spring-web/src/test/java/org/springframework/tests/web/FreePortScanner.java similarity index 98% rename from spring-webmvc/src/test/java/org/springframework/http/client/FreePortScanner.java rename to spring-web/src/test/java/org/springframework/tests/web/FreePortScanner.java index 83add2ceaf..9f5a3d9c33 100644 --- a/spring-webmvc/src/test/java/org/springframework/http/client/FreePortScanner.java +++ b/spring-web/src/test/java/org/springframework/tests/web/FreePortScanner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.springframework.http.client; +package org.springframework.tests.web; import java.io.IOException; import java.net.InetSocketAddress; diff --git a/spring-web/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-web/src/test/java/org/springframework/util/SerializationTestUtils.java deleted file mode 100644 index dbe6421093..0000000000 --- a/spring-web/src/test/java/org/springframework/util/SerializationTestUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * The Spring Framework is published under the terms - * of the Apache Software License. - */ - -package org.springframework.util; - -import java.awt.Point; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import junit.framework.TestCase; - -import org.springframework.beans.TestBean; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * Extends TestCase only to test itself. - * - * @author Rod Johnson - */ -public class SerializationTestUtils extends TestCase { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - - return o2; - } - - public SerializationTestUtils(String s) { - super(s); - } - - public void testWithNonSerializableObject() throws IOException { - TestBean o = new TestBean(); - assertFalse(o instanceof Serializable); - - assertFalse(isSerializable(o)); - - try { - testSerialization(o); - fail(); - } - catch (NotSerializableException ex) { - // Ok - } - } - - public void testWithSerializableObject() throws Exception { - int x = 5; - int y = 10; - Point p = new Point(x, y); - assertTrue(p instanceof Serializable); - - testSerialization(p); - - assertTrue(isSerializable(p)); - - Point p2 = (Point) serializeAndDeserialize(p); - assertNotSame(p, p2); - assertEquals(x, (int) p2.getX()); - assertEquals(y, (int) p2.getY()); - } - -} \ No newline at end of file diff --git a/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java b/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java index 9f6a1df756..25d63e8b3a 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/EscapedErrorsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.web.bind; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; diff --git a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java index cf514b44b8..34340bd3e1 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestDataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import java.util.HashMap; import java.util.Map; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; /** diff --git a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java index 3f194e9bd0..b3e347fd5f 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,10 +24,10 @@ import java.util.Map; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockMultipartFile; import org.springframework.mock.web.test.MockMultipartHttpServletRequest; @@ -63,7 +63,7 @@ public class WebRequestDataBinderTests { @Test public void testBindingWithNestedObjectCreationThroughAutoGrow() throws Exception { - TestBean tb = new TestBean(); + TestBean tb = new TestBeanWithConcreteSpouse(); WebRequestDataBinder binder = new WebRequestDataBinder(tb, "person"); binder.setIgnoreUnknownFields(false); @@ -305,21 +305,30 @@ public class WebRequestDataBinderTests { public static class EnumHolder { - private MyEnum myEnum; + private MyEnum myEnum; - public MyEnum getMyEnum() { - return myEnum; - } + public MyEnum getMyEnum() { + return myEnum; + } - public void setMyEnum(MyEnum myEnum) { - this.myEnum = myEnum; - } - } + public void setMyEnum(MyEnum myEnum) { + this.myEnum = myEnum; + } + } + public enum MyEnum { + FOO, BAR + } - public enum MyEnum { + static class TestBeanWithConcreteSpouse extends TestBean { + public void setConcreteSpouse(TestBean spouse) { + this.spouses = new ITestBean[] {spouse}; + } + + public TestBean getConcreteSpouse() { + return (spouses != null ? (TestBean) spouses[0] : null); + } + } - FOO, BAR - } } diff --git a/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java b/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java index a02fcae95b..ea09d9a3dd 100644 --- a/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java +++ b/spring-web/src/test/java/org/springframework/web/client/RestTemplateIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,8 +62,8 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.FreePortScanner; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; +import org.springframework.tests.web.FreePortScanner; import org.springframework.util.FileCopyUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java index 5c18203da6..a4b7d6018a 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestAndSessionScopedBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import javax.servlet.http.HttpServletRequest; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.mock.web.test.MockHttpServletRequest; diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java index 3b12ab2dba..6f88b6a948 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,8 @@ package org.springframework.web.context.request; import junit.framework.TestCase; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCurrentlyInCreationException; import org.springframework.beans.factory.FactoryBean; diff --git a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java index 250e50c75c..4a5703f34a 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/RequestScopedProxyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,10 +21,10 @@ import org.junit.Before; import org.junit.Test; import org.springframework.aop.support.AopUtils; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.DummyFactory; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java index c6b0c656fa..4e540a7d20 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/SessionScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,8 +21,8 @@ import java.io.Serializable; import junit.framework.TestCase; import org.springframework.beans.BeansException; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.beans.factory.support.DefaultListableBeanFactory; diff --git a/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java b/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java index 53e2e0a458..5c2ef5823c 100644 --- a/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/request/WebApplicationContextScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import javax.servlet.ServletContextEvent; import static org.junit.Assert.*; import org.junit.Test; -import org.springframework.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockServletContext; diff --git a/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java b/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java index 1d38301342..8412e2b667 100644 --- a/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java +++ b/spring-web/src/test/java/org/springframework/web/context/support/SpringBeanAutowiringSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,9 @@ package org.springframework.web.context.support; import org.junit.Test; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.mock.web.test.MockServletContext; diff --git a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingVariableResolverTests.java b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingVariableResolverTests.java index a2c27162a2..053a53150a 100644 --- a/spring-web/src/test/java/org/springframework/web/jsf/DelegatingVariableResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/jsf/DelegatingVariableResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import javax.faces.el.VariableResolver; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.StaticWebApplicationContext; diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java index 986df7e9fa..170e8e2c9b 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.MethodParameter; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.validation.BindException; diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java index a9699262e4..1da1934391 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/SessionAttributesHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import java.util.HashSet; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.SessionAttributes; diff --git a/spring-web/src/test/resources/org/springframework/web/context/request/requestScopeTests.xml b/spring-web/src/test/resources/org/springframework/web/context/request/requestScopeTests.xml index f2d06c527f..3ed39dfd7a 100644 --- a/spring-web/src/test/resources/org/springframework/web/context/request/requestScopeTests.xml +++ b/spring-web/src/test/resources/org/springframework/web/context/request/requestScopeTests.xml @@ -4,35 +4,35 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> - + - + - + - + - + - + - + - + - + diff --git a/spring-web/src/test/resources/org/springframework/web/context/request/requestScopedProxyTests.xml b/spring-web/src/test/resources/org/springframework/web/context/request/requestScopedProxyTests.xml index ee1313d4dc..92759852b5 100644 --- a/spring-web/src/test/resources/org/springframework/web/context/request/requestScopedProxyTests.xml +++ b/spring-web/src/test/resources/org/springframework/web/context/request/requestScopedProxyTests.xml @@ -5,47 +5,47 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> - + - + - + - + - + - + - + - + - + - + diff --git a/spring-web/src/test/resources/org/springframework/web/context/request/sessionScopeTests.xml b/spring-web/src/test/resources/org/springframework/web/context/request/sessionScopeTests.xml index e4f05b9abe..e92f639f8c 100644 --- a/spring-web/src/test/resources/org/springframework/web/context/request/sessionScopeTests.xml +++ b/spring-web/src/test/resources/org/springframework/web/context/request/sessionScopeTests.xml @@ -3,8 +3,8 @@ - + - + diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/Colour.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index c5360de531..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/IOther.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/ITestBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770e..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/TestBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 6d71de7576..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see org.springframework.beans.ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see org.springframework.beans.ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see org.springframework.beans.IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java deleted file mode 100644 index d6911ee72f..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractBeanFactoryTests.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import java.beans.PropertyEditorSupport; -import java.util.StringTokenizer; - -import junit.framework.TestCase; - -import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyBatchUpdateException; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; - -/** - * Subclasses must implement setUp() to initialize bean factory - * and any other variables they need. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractBeanFactoryTests extends TestCase { - - protected abstract BeanFactory getBeanFactory(); - - /** - * Roderick beans inherits from rod, overriding name only. - */ - public void testInheritance() { - assertTrue(getBeanFactory().containsBean("rod")); - assertTrue(getBeanFactory().containsBean("roderick")); - TestBean rod = (TestBean) getBeanFactory().getBean("rod"); - TestBean roderick = (TestBean) getBeanFactory().getBean("roderick"); - assertTrue("not == ", rod != roderick); - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick")); - assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge()); - } - - public void testGetBeanWithNullArg() { - try { - getBeanFactory().getBean((String) null); - fail("Can't get null bean"); - } - catch (IllegalArgumentException ex) { - // OK - } - } - - /** - * Test that InitializingBean objects receive the afterPropertiesSet() callback - */ - public void testInitializingBeanCallback() { - MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized"); - // The dummy business method will throw an exception if the - // afterPropertiesSet() callback wasn't invoked - mbi.businessMethod(); - } - - /** - * Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the - * afterPropertiesSet() callback before BeanFactoryAware callbacks - */ - public void testLifecycleCallbacks() { - LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle"); - assertEquals("lifecycle", lb.getBeanName()); - // The dummy business method will throw an exception if the - // necessary callbacks weren't invoked in the right order. - lb.businessMethod(); - assertTrue("Not destroyed", !lb.isDestroyed()); - } - - public void testFindsValidInstance() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - TestBean rod = (TestBean) o; - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testGetInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetInstanceByNonmatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass()); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testGetSharedInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetSharedInstanceByMatchingClassNoCatch() { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - - public void testGetSharedInstanceByNonmatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testSharedInstancesAreEqual() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean1 is a TestBean", o instanceof TestBean); - Object o1 = getBeanFactory().getBean("rod"); - assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean); - assertTrue("Object equals applies", o == o1); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testPrototypeInstancesAreIndependent() { - TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy"); - TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy"); - assertTrue("ref equal DOES NOT apply", tb1 != tb2); - assertTrue("object equal true", tb1.equals(tb2)); - tb1.setAge(1); - tb2.setAge(2); - assertTrue("1 age independent = 1", tb1.getAge() == 1); - assertTrue("2 age independent = 2", tb2.getAge() == 2); - assertTrue("object equal now false", !tb1.equals(tb2)); - } - - public void testNotThere() { - assertFalse(getBeanFactory().containsBean("Mr Squiggle")); - try { - Object o = getBeanFactory().getBean("Mr Squiggle"); - fail("Can't find missing bean"); - } - catch (BeansException ex) { - //ex.printStackTrace(); - //fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testValidEmpty() { - try { - Object o = getBeanFactory().getBean("validEmpty"); - assertTrue("validEmpty bean is a TestBean", o instanceof TestBean); - TestBean ve = (TestBean) o; - assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null); - } - catch (BeansException ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on valid empty"); - } - } - - public void xtestTypeMismatch() { - try { - Object o = getBeanFactory().getBean("typeMismatch"); - fail("Shouldn't succeed with type mismatch"); - } - catch (BeanCreationException wex) { - assertEquals("typeMismatch", wex.getBeanName()); - assertTrue(wex.getCause() instanceof PropertyBatchUpdateException); - PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause(); - // Further tests - assertTrue("Has one error ", ex.getExceptionCount() == 1); - assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null); - assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x")); - } - } - - public void testGrandparentDefinitionFoundInBeanFactory() throws Exception { - TestBean dad = (TestBean) getBeanFactory().getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testFactorySingleton() throws Exception { - assertTrue(getBeanFactory().isSingleton("&singletonFactory")); - assertTrue(getBeanFactory().isSingleton("singletonFactory")); - TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME)); - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton references ==", tb == tb2); - assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null); - } - - public void testFactoryPrototype() throws Exception { - assertTrue(getBeanFactory().isSingleton("&prototypeFactory")); - assertFalse(getBeanFactory().isSingleton("prototypeFactory")); - TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME)); - TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue("Prototype references !=", tb != tb2); - } - - /** - * Check that we can get the factory bean itself. - * This is only possible if we're dealing with a factory - * @throws Exception - */ - public void testGetFactoryItself() throws Exception { - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue(factory != null); - } - - /** - * Check that afterPropertiesSet gets called on factory - * @throws Exception - */ - public void testFactoryIsInitialized() throws Exception { - TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized()); - } - - /** - * It should be illegal to dereference a normal bean - * as a factory - */ - public void testRejectsFactoryGetOnNormalBean() { - try { - getBeanFactory().getBean("&rod"); - fail("Shouldn't permit factory get on normal bean"); - } - catch (BeanIsNotAFactoryException ex) { - // Ok - } - } - - // TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory) - // and rename this class - public void testAliasing() { - BeanFactory bf = getBeanFactory(); - if (!(bf instanceof ConfigurableBeanFactory)) { - return; - } - ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf; - - String alias = "rods alias"; - try { - cbf.getBean(alias); - fail("Shouldn't permit factory get on normal bean"); - } - catch (NoSuchBeanDefinitionException ex) { - // Ok - assertTrue(alias.equals(ex.getBeanName())); - } - - // Create alias - cbf.registerAlias("rod", alias); - Object rod = getBeanFactory().getBean("rod"); - Object aliasRod = getBeanFactory().getBean(alias); - assertTrue(rod == aliasRod); - } - - - public static class TestBeanEditor extends PropertyEditorSupport { - - @Override - public void setAsText(String text) { - TestBean tb = new TestBean(); - StringTokenizer st = new StringTokenizer(text, "_"); - tb.setName(st.nextToken()); - tb.setAge(Integer.parseInt(st.nextToken())); - setValue(tb); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java deleted file mode 100644 index 855f23af39..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/AbstractListableBeanFactoryTests.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.TestBean; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests { - - /** Subclasses must initialize this */ - protected ListableBeanFactory getListableBeanFactory() { - BeanFactory bf = getBeanFactory(); - if (!(bf instanceof ListableBeanFactory)) { - throw new IllegalStateException("ListableBeanFactory required"); - } - return (ListableBeanFactory) bf; - } - - /** - * Subclasses can override this. - */ - public void testCount() { - assertCount(13); - } - - protected final void assertCount(int count) { - String[] defnames = getListableBeanFactory().getBeanDefinitionNames(); - assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count); - } - - public void assertTestBeanCount(int count) { - String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); - assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " + - defNames.length, defNames.length == count); - - int countIncludingFactoryBeans = count + 2; - String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true); - assertTrue("We should have " + countIncludingFactoryBeans + - " beans for class org.springframework.beans.TestBean, not " + names.length, - names.length == countIncludingFactoryBeans); - } - - public void testGetDefinitionsForNoSuchClass() { - String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class); - assertTrue("No string definitions", defnames.length == 0); - } - - /** - * Check that count refers to factory class, not bean class. (We don't know - * what type factories may return, and it may even change over time.) - */ - public void testGetCountForFactoryClass() { - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); - - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); - } - - public void testContainsBeanDefinition() { - assertTrue(getListableBeanFactory().containsBeanDefinition("rod")); - assertTrue(getListableBeanFactory().containsBeanDefinition("roderick")); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/DummyFactory.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/DummyFactory.java deleted file mode 100644 index 6fc7e36aa9..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/DummyFactory.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; - -/** - * Simple factory to allow testing of FactoryBean support in AbstractBeanFactory. - * Depending on whether its singleton property is set, it will return a singleton - * or a prototype instance. - * - *

Implements InitializingBean interface, so we can check that - * factories get this lifecycle callback if they want. - * - * @author Rod Johnson - * @since 10.03.2003 - */ -public class DummyFactory - implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { - - public static final String SINGLETON_NAME = "Factory singleton"; - - private static boolean prototypeCreated; - - /** - * Clear static state. - */ - public static void reset() { - prototypeCreated = false; - } - - - /** - * Default is for factories to return a singleton instance. - */ - private boolean singleton = true; - - private String beanName; - - private AutowireCapableBeanFactory beanFactory; - - private boolean postProcessed; - - private boolean initialized; - - private TestBean testBean; - - private TestBean otherTestBean; - - - public DummyFactory() { - this.testBean = new TestBean(); - this.testBean.setName(SINGLETON_NAME); - this.testBean.setAge(25); - } - - /** - * Return if the bean managed by this factory is a singleton. - * @see FactoryBean#isSingleton() - */ - @Override - public boolean isSingleton() { - return this.singleton; - } - - /** - * Set if the bean managed by this factory is a singleton. - */ - public void setSingleton(boolean singleton) { - this.singleton = singleton; - } - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = (AutowireCapableBeanFactory) beanFactory; - this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName); - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - public void setOtherTestBean(TestBean otherTestBean) { - this.otherTestBean = otherTestBean; - this.testBean.setSpouse(otherTestBean); - } - - public TestBean getOtherTestBean() { - return otherTestBean; - } - - @Override - public void afterPropertiesSet() { - if (initialized) { - throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean"); - } - this.initialized = true; - } - - /** - * Was this initialized by invocation of the - * afterPropertiesSet() method from the InitializingBean interface? - */ - public boolean wasInitialized() { - return initialized; - } - - public static boolean wasPrototypeCreated() { - return prototypeCreated; - } - - - /** - * Return the managed object, supporting both singleton - * and prototype mode. - * @see FactoryBean#getObject() - */ - @Override - public Object getObject() throws BeansException { - if (isSingleton()) { - return this.testBean; - } - else { - TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11); - if (this.beanFactory != null) { - this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName); - } - prototypeCreated = true; - return prototype; - } - } - - @Override - public Class getObjectType() { - return TestBean.class; - } - - - @Override - public void destroy() { - if (this.testBean != null) { - this.testBean.setName(null); - } - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/LifecycleBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/LifecycleBean.java deleted file mode 100644 index 013a65a0e4..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/LifecycleBean.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; - -/** - * Simple test of BeanFactory initialization and lifecycle callbacks. - * - * @author Rod Johnson - * @author Colin Sampaleanu - * @since 12.03.2003 - */ -public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { - - protected boolean initMethodDeclared = false; - - protected String beanName; - - protected BeanFactory owningFactory; - - protected boolean postProcessedBeforeInit; - - protected boolean inited; - - protected boolean initedViaDeclaredInitMethod; - - protected boolean postProcessedAfterInit; - - protected boolean destroyed; - - - public void setInitMethodDeclared(boolean initMethodDeclared) { - this.initMethodDeclared = initMethodDeclared; - } - - public boolean isInitMethodDeclared() { - return initMethodDeclared; - } - - @Override - public void setBeanName(String name) { - this.beanName = name; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.owningFactory = beanFactory; - } - - public void postProcessBeforeInit() { - if (this.inited || this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet"); - } - if (this.postProcessedBeforeInit) { - throw new RuntimeException("Factory called postProcessBeforeInit twice"); - } - this.postProcessedBeforeInit = true; - } - - @Override - public void afterPropertiesSet() { - if (this.owningFactory == null) { - throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean"); - } - if (!this.postProcessedBeforeInit) { - throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean"); - } - if (this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet"); - } - if (this.inited) { - throw new RuntimeException("Factory called afterPropertiesSet twice"); - } - this.inited = true; - } - - public void declaredInitMethod() { - if (!this.inited) { - throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method"); - } - - if (this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called declared init method twice"); - } - this.initedViaDeclaredInitMethod = true; - } - - public void postProcessAfterInit() { - if (!this.inited) { - throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet"); - } - if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method"); - } - if (this.postProcessedAfterInit) { - throw new RuntimeException("Factory called postProcessAfterInit twice"); - } - this.postProcessedAfterInit = true; - } - - /** - * Dummy business method that will fail unless the factory - * managed the bean's lifecycle correctly - */ - public void businessMethod() { - if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) || - !this.postProcessedAfterInit) { - throw new RuntimeException("Factory didn't initialize lifecycle object correctly"); - } - } - - @Override - public void destroy() { - if (this.destroyed) { - throw new IllegalStateException("Already destroyed"); - } - this.destroyed = true; - } - - public boolean isDestroyed() { - return destroyed; - } - - - public static class PostProcessor implements BeanPostProcessor { - - @Override - public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessBeforeInit(); - } - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessAfterInit(); - } - return bean; - } - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/MustBeInitialized.java b/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/MustBeInitialized.java deleted file mode 100644 index b9a7925ad8..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/beans/factory/MustBeInitialized.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.factory.InitializingBean; - -/** - * Simple test of BeanFactory initialization - * @author Rod Johnson - * @since 12.03.2003 - */ -public class MustBeInitialized implements InitializingBean { - - private boolean inited; - - /** - * @see InitializingBean#afterPropertiesSet() - */ - @Override - public void afterPropertiesSet() throws Exception { - this.inited = true; - } - - /** - * Dummy business method that will fail unless the factory - * managed the bean's lifecycle correctly - */ - public void businessMethod() { - if (!this.inited) - throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object"); - } - -} \ No newline at end of file diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/AbstractApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/AbstractApplicationContextTests.java deleted file mode 100644 index a720743520..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/AbstractApplicationContextTests.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.context; - -import java.util.Locale; - -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.AbstractListableBeanFactoryTests; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.LifecycleBean; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests { - - /** Must be supplied as XML */ - public static final String TEST_NAMESPACE = "testNamespace"; - - protected ConfigurableApplicationContext applicationContext; - - /** Subclass must register this */ - protected TestListener listener = new TestListener(); - - protected TestListener parentListener = new TestListener(); - - @Override - protected void setUp() throws Exception { - this.applicationContext = createContext(); - } - - @Override - protected BeanFactory getBeanFactory() { - return applicationContext; - } - - protected ApplicationContext getApplicationContext() { - return applicationContext; - } - - /** - * Must register a TestListener. - * Must register standard beans. - * Parent must register rod with name Roderick - * and father with name Albert. - */ - protected abstract ConfigurableApplicationContext createContext() throws Exception; - - public void testContextAwareSingletonWasCalledBack() throws Exception { - ACATester aca = (ACATester) applicationContext.getBean("aca"); - assertTrue("has had context set", aca.getApplicationContext() == applicationContext); - Object aca2 = applicationContext.getBean("aca"); - assertTrue("Same instance", aca == aca2); - assertTrue("Says is singleton", applicationContext.isSingleton("aca")); - } - - public void testContextAwarePrototypeWasCalledBack() throws Exception { - ACATester aca = (ACATester) applicationContext.getBean("aca-prototype"); - assertTrue("has had context set", aca.getApplicationContext() == applicationContext); - Object aca2 = applicationContext.getBean("aca-prototype"); - assertTrue("NOT Same instance", aca != aca2); - assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype")); - } - - public void testParentNonNull() { - assertTrue("parent isn't null", applicationContext.getParent() != null); - } - - public void testGrandparentNull() { - assertTrue("grandparent is null", applicationContext.getParent().getParent() == null); - } - - public void testOverrideWorked() throws Exception { - TestBean rod = (TestBean) applicationContext.getParent().getBean("rod"); - assertTrue("Parent's name differs", rod.getName().equals("Roderick")); - } - - public void testGrandparentDefinitionFound() throws Exception { - TestBean dad = (TestBean) applicationContext.getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testGrandparentTypedDefinitionFound() throws Exception { - TestBean dad = applicationContext.getBean("father", TestBean.class); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testCloseTriggersDestroy() { - LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle"); - assertTrue("Not destroyed", !lb.isDestroyed()); - applicationContext.close(); - if (applicationContext.getParent() != null) { - ((ConfigurableApplicationContext) applicationContext.getParent()).close(); - } - assertTrue("Destroyed", lb.isDestroyed()); - applicationContext.close(); - if (applicationContext.getParent() != null) { - ((ConfigurableApplicationContext) applicationContext.getParent()).close(); - } - assertTrue("Destroyed", lb.isDestroyed()); - } - - public void testMessageSource() throws NoSuchMessageException { - assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault())); - assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault())); - - try { - applicationContext.getMessage("code0", null, Locale.getDefault()); - fail("looking for code0 should throw a NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // that's how it should be - } - } - - public void testEvents() throws Exception { - listener.zeroCounter(); - parentListener.zeroCounter(); - assertTrue("0 events before publication", listener.getEventCount() == 0); - assertTrue("0 parent events before publication", parentListener.getEventCount() == 0); - this.applicationContext.publishEvent(new MyEvent(this)); - assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1); - assertTrue("1 parent events after publication", parentListener.getEventCount() == 1); - } - - public void testBeanAutomaticallyHearsEvents() throws Exception { - //String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class); - //assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens")); - BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens"); - b.zero(); - assertTrue("0 events before publication", b.getEventCount() == 0); - this.applicationContext.publishEvent(new MyEvent(this)); - assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1); - } - - - @SuppressWarnings("serial") - public static class MyEvent extends ApplicationEvent { - - public MyEvent(Object source) { - super(source); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java b/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java index 14acac1ceb..37d4c9715f 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/context/LifecycleContextBean.java @@ -3,7 +3,7 @@ package org.springframework.context; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.LifecycleBean; +import org.springframework.tests.sample.beans.LifecycleBean; /** * Simple bean to test ApplicationContext lifecycle methods for beans diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java deleted file mode 100644 index d580974a60..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/DelegatingServletOutputStream.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import java.io.IOException; -import java.io.OutputStream; -import javax.servlet.ServletOutputStream; - -import org.springframework.util.Assert; - -/** - * Delegating implementation of {@link javax.servlet.ServletOutputStream}. - * - *

Used by {@link MockHttpServletResponse}; typically not directly - * used for testing application controllers. - * - * @author Juergen Hoeller - * @since 1.0.2 - * @see MockHttpServletResponse - */ -public class DelegatingServletOutputStream extends ServletOutputStream { - - private final OutputStream targetStream; - - - /** - * Create a DelegatingServletOutputStream for the given target stream. - * @param targetStream the target stream (never {@code null}) - */ - public DelegatingServletOutputStream(OutputStream targetStream) { - Assert.notNull(targetStream, "Target OutputStream must not be null"); - this.targetStream = targetStream; - } - - /** - * Return the underlying target stream (never {@code null}). - */ - public final OutputStream getTargetStream() { - return this.targetStream; - } - - - @Override - public void write(int b) throws IOException { - this.targetStream.write(b); - } - - @Override - public void flush() throws IOException { - super.flush(); - this.targetStream.flush(); - } - - @Override - public void close() throws IOException { - super.close(); - this.targetStream.close(); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/HeaderValueHolder.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/HeaderValueHolder.java deleted file mode 100644 index e8f5e91dfb..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/HeaderValueHolder.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.springframework.util.Assert; -import org.springframework.util.CollectionUtils; - -/** - * Internal helper class that serves as value holder for request headers. - * - * @author Juergen Hoeller - * @author Rick Evans - * @since 2.0.1 - */ -class HeaderValueHolder { - - private final List values = new LinkedList(); - - - public void setValue(Object value) { - this.values.clear(); - this.values.add(value); - } - - public void addValue(Object value) { - this.values.add(value); - } - - public void addValues(Collection values) { - this.values.addAll(values); - } - - public void addValueArray(Object values) { - CollectionUtils.mergeArrayIntoCollection(values, this.values); - } - - public List getValues() { - return Collections.unmodifiableList(this.values); - } - - public List getStringValues() { - List stringList = new ArrayList(this.values.size()); - for (Object value : this.values) { - stringList.add(value.toString()); - } - return Collections.unmodifiableList(stringList); - } - - public Object getValue() { - return (!this.values.isEmpty() ? this.values.get(0) : null); - } - - public String getStringValue() { - return (!this.values.isEmpty() ? this.values.get(0).toString() : null); - } - - - /** - * Find a HeaderValueHolder by name, ignoring casing. - * @param headers the Map of header names to HeaderValueHolders - * @param name the name of the desired header - * @return the corresponding HeaderValueHolder, - * or {@code null} if none found - */ - public static HeaderValueHolder getByName(Map headers, String name) { - Assert.notNull(name, "Header name must not be null"); - for (String headerName : headers.keySet()) { - if (headerName.equalsIgnoreCase(name)) { - return headers.get(headerName); - } - } - return null; - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java deleted file mode 100644 index 5a2b7fd1aa..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpServletResponse.java +++ /dev/null @@ -1,641 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.util.Assert; -import org.springframework.util.LinkedCaseInsensitiveMap; -import org.springframework.web.util.WebUtils; - -/** - * Mock implementation of the {@link javax.servlet.http.HttpServletResponse} interface. - * - *

Compatible with Servlet 2.5 as well as Servlet 3.0. - * - * @author Juergen Hoeller - * @author Rod Johnson - * @since 1.0.2 - */ -public class MockHttpServletResponse implements HttpServletResponse { - - private static final String CHARSET_PREFIX = "charset="; - - private static final String CONTENT_TYPE_HEADER = "Content-Type"; - - private static final String CONTENT_LENGTH_HEADER = "Content-Length"; - - private static final String LOCATION_HEADER = "Location"; - - //--------------------------------------------------------------------- - // ServletResponse properties - //--------------------------------------------------------------------- - - private boolean outputStreamAccessAllowed = true; - - private boolean writerAccessAllowed = true; - - private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING; - - private boolean charset = false; - - private final ByteArrayOutputStream content = new ByteArrayOutputStream(); - - private final ServletOutputStream outputStream = new ResponseServletOutputStream(this.content); - - private PrintWriter writer; - - private int contentLength = 0; - - private String contentType; - - private int bufferSize = 4096; - - private boolean committed; - - private Locale locale = Locale.getDefault(); - - - //--------------------------------------------------------------------- - // HttpServletResponse properties - //--------------------------------------------------------------------- - - private final List cookies = new ArrayList(); - - private final Map headers = new LinkedCaseInsensitiveMap(); - - private int status = HttpServletResponse.SC_OK; - - private String errorMessage; - - private String forwardedUrl; - - private final List includedUrls = new ArrayList(); - - - //--------------------------------------------------------------------- - // ServletResponse interface - //--------------------------------------------------------------------- - - /** - * Set whether {@link #getOutputStream()} access is allowed. - *

Default is {@code true}. - */ - public void setOutputStreamAccessAllowed(boolean outputStreamAccessAllowed) { - this.outputStreamAccessAllowed = outputStreamAccessAllowed; - } - - /** - * Return whether {@link #getOutputStream()} access is allowed. - */ - public boolean isOutputStreamAccessAllowed() { - return this.outputStreamAccessAllowed; - } - - /** - * Set whether {@link #getWriter()} access is allowed. - *

Default is {@code true}. - */ - public void setWriterAccessAllowed(boolean writerAccessAllowed) { - this.writerAccessAllowed = writerAccessAllowed; - } - - /** - * Return whether {@link #getOutputStream()} access is allowed. - */ - public boolean isWriterAccessAllowed() { - return this.writerAccessAllowed; - } - - @Override - public void setCharacterEncoding(String characterEncoding) { - this.characterEncoding = characterEncoding; - this.charset = true; - updateContentTypeHeader(); - } - - private void updateContentTypeHeader() { - if (this.contentType != null) { - StringBuilder sb = new StringBuilder(this.contentType); - if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.charset) { - sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding); - } - doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true); - } - } - - @Override - public String getCharacterEncoding() { - return this.characterEncoding; - } - - @Override - public ServletOutputStream getOutputStream() { - if (!this.outputStreamAccessAllowed) { - throw new IllegalStateException("OutputStream access not allowed"); - } - return this.outputStream; - } - - @Override - public PrintWriter getWriter() throws UnsupportedEncodingException { - if (!this.writerAccessAllowed) { - throw new IllegalStateException("Writer access not allowed"); - } - if (this.writer == null) { - Writer targetWriter = (this.characterEncoding != null ? - new OutputStreamWriter(this.content, this.characterEncoding) : new OutputStreamWriter(this.content)); - this.writer = new ResponsePrintWriter(targetWriter); - } - return this.writer; - } - - public byte[] getContentAsByteArray() { - flushBuffer(); - return this.content.toByteArray(); - } - - public String getContentAsString() throws UnsupportedEncodingException { - flushBuffer(); - return (this.characterEncoding != null) ? - this.content.toString(this.characterEncoding) : this.content.toString(); - } - - @Override - public void setContentLength(int contentLength) { - this.contentLength = contentLength; - doAddHeaderValue(CONTENT_LENGTH_HEADER, contentLength, true); - } - - public int getContentLength() { - return this.contentLength; - } - - @Override - public void setContentType(String contentType) { - this.contentType = contentType; - if (contentType != null) { - int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX); - if (charsetIndex != -1) { - String encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length()); - this.characterEncoding = encoding; - this.charset = true; - } - updateContentTypeHeader(); - } - } - - @Override - public String getContentType() { - return this.contentType; - } - - @Override - public void setBufferSize(int bufferSize) { - this.bufferSize = bufferSize; - } - - @Override - public int getBufferSize() { - return this.bufferSize; - } - - @Override - public void flushBuffer() { - setCommitted(true); - } - - @Override - public void resetBuffer() { - if (isCommitted()) { - throw new IllegalStateException("Cannot reset buffer - response is already committed"); - } - this.content.reset(); - } - - private void setCommittedIfBufferSizeExceeded() { - int bufSize = getBufferSize(); - if (bufSize > 0 && this.content.size() > bufSize) { - setCommitted(true); - } - } - - public void setCommitted(boolean committed) { - this.committed = committed; - } - - @Override - public boolean isCommitted() { - return this.committed; - } - - @Override - public void reset() { - resetBuffer(); - this.characterEncoding = null; - this.contentLength = 0; - this.contentType = null; - this.locale = null; - this.cookies.clear(); - this.headers.clear(); - this.status = HttpServletResponse.SC_OK; - this.errorMessage = null; - } - - @Override - public void setLocale(Locale locale) { - this.locale = locale; - } - - @Override - public Locale getLocale() { - return this.locale; - } - - - //--------------------------------------------------------------------- - // HttpServletResponse interface - //--------------------------------------------------------------------- - - @Override - public void addCookie(Cookie cookie) { - Assert.notNull(cookie, "Cookie must not be null"); - this.cookies.add(cookie); - } - - public Cookie[] getCookies() { - return this.cookies.toArray(new Cookie[this.cookies.size()]); - } - - public Cookie getCookie(String name) { - Assert.notNull(name, "Cookie name must not be null"); - for (Cookie cookie : this.cookies) { - if (name.equals(cookie.getName())) { - return cookie; - } - } - return null; - } - - @Override - public boolean containsHeader(String name) { - return (HeaderValueHolder.getByName(this.headers, name) != null); - } - - /** - * Return the names of all specified headers as a Set of Strings. - *

As of Servlet 3.0, this method is also defined HttpServletResponse. - * @return the {@code Set} of header name {@code Strings}, or an empty {@code Set} if none - */ - public Set getHeaderNames() { - return this.headers.keySet(); - } - - /** - * Return the primary value for the given header as a String, if any. - * Will return the first value in case of multiple values. - *

As of Servlet 3.0, this method is also defined in HttpServletResponse. - * As of Spring 3.1, it returns a stringified value for Servlet 3.0 compatibility. - * Consider using {@link #getHeaderValue(String)} for raw Object access. - * @param name the name of the header - * @return the associated header value, or {@code null} if none - */ - public String getHeader(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return (header != null ? header.getStringValue() : null); - } - - /** - * Return all values for the given header as a List of Strings. - *

As of Servlet 3.0, this method is also defined in HttpServletResponse. - * As of Spring 3.1, it returns a List of stringified values for Servlet 3.0 compatibility. - * Consider using {@link #getHeaderValues(String)} for raw Object access. - * @param name the name of the header - * @return the associated header values, or an empty List if none - */ - public List getHeaders(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - if (header != null) { - return header.getStringValues(); - } - else { - return Collections.emptyList(); - } - } - - /** - * Return the primary value for the given header, if any. - *

Will return the first value in case of multiple values. - * @param name the name of the header - * @return the associated header value, or {@code null} if none - */ - public Object getHeaderValue(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return (header != null ? header.getValue() : null); - } - - /** - * Return all values for the given header as a List of value objects. - * @param name the name of the header - * @return the associated header values, or an empty List if none - */ - public List getHeaderValues(String name) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - if (header != null) { - return header.getValues(); - } - else { - return Collections.emptyList(); - } - } - - /** - * The default implementation returns the given URL String as-is. - *

Can be overridden in subclasses, appending a session id or the like. - */ - @Override - public String encodeURL(String url) { - return url; - } - - /** - * The default implementation delegates to {@link #encodeURL}, - * returning the given URL String as-is. - *

Can be overridden in subclasses, appending a session id or the like - * in a redirect-specific fashion. For general URL encoding rules, - * override the common {@link #encodeURL} method instead, applying - * to redirect URLs as well as to general URLs. - */ - @Override - public String encodeRedirectURL(String url) { - return encodeURL(url); - } - - @Override - public String encodeUrl(String url) { - return encodeURL(url); - } - - @Override - public String encodeRedirectUrl(String url) { - return encodeRedirectURL(url); - } - - @Override - public void sendError(int status, String errorMessage) throws IOException { - if (isCommitted()) { - throw new IllegalStateException("Cannot set error status - response is already committed"); - } - this.status = status; - this.errorMessage = errorMessage; - setCommitted(true); - } - - @Override - public void sendError(int status) throws IOException { - if (isCommitted()) { - throw new IllegalStateException("Cannot set error status - response is already committed"); - } - this.status = status; - setCommitted(true); - } - - @Override - public void sendRedirect(String url) throws IOException { - if (isCommitted()) { - throw new IllegalStateException("Cannot send redirect - response is already committed"); - } - Assert.notNull(url, "Redirect URL must not be null"); - setHeader(LOCATION_HEADER, url); - setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY); - setCommitted(true); - } - - public String getRedirectedUrl() { - return getHeader(LOCATION_HEADER); - } - - @Override - public void setDateHeader(String name, long value) { - setHeaderValue(name, value); - } - - @Override - public void addDateHeader(String name, long value) { - addHeaderValue(name, value); - } - - @Override - public void setHeader(String name, String value) { - setHeaderValue(name, value); - } - - @Override - public void addHeader(String name, String value) { - addHeaderValue(name, value); - } - - @Override - public void setIntHeader(String name, int value) { - setHeaderValue(name, value); - } - - @Override - public void addIntHeader(String name, int value) { - addHeaderValue(name, value); - } - - private void setHeaderValue(String name, Object value) { - if (setSpecialHeader(name, value)) { - return; - } - doAddHeaderValue(name, value, true); - } - - private void addHeaderValue(String name, Object value) { - if (setSpecialHeader(name, value)) { - return; - } - doAddHeaderValue(name, value, false); - } - - private boolean setSpecialHeader(String name, Object value) { - if (CONTENT_TYPE_HEADER.equalsIgnoreCase(name)) { - setContentType((String) value); - return true; - } - else if (CONTENT_LENGTH_HEADER.equalsIgnoreCase(name)) { - setContentLength(Integer.parseInt((String) value)); - return true; - } - else { - return false; - } - } - - private void doAddHeaderValue(String name, Object value, boolean replace) { - HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - Assert.notNull(value, "Header value must not be null"); - if (header == null) { - header = new HeaderValueHolder(); - this.headers.put(name, header); - } - if (replace) { - header.setValue(value); - } - else { - header.addValue(value); - } - } - - @Override - public void setStatus(int status) { - this.status = status; - } - - @Override - public void setStatus(int status, String errorMessage) { - this.status = status; - this.errorMessage = errorMessage; - } - - public int getStatus() { - return this.status; - } - - public String getErrorMessage() { - return this.errorMessage; - } - - - //--------------------------------------------------------------------- - // Methods for MockRequestDispatcher - //--------------------------------------------------------------------- - - public void setForwardedUrl(String forwardedUrl) { - this.forwardedUrl = forwardedUrl; - } - - public String getForwardedUrl() { - return this.forwardedUrl; - } - - public void setIncludedUrl(String includedUrl) { - this.includedUrls.clear(); - if (includedUrl != null) { - this.includedUrls.add(includedUrl); - } - } - - public String getIncludedUrl() { - int count = this.includedUrls.size(); - if (count > 1) { - throw new IllegalStateException( - "More than 1 URL included - check getIncludedUrls instead: " + this.includedUrls); - } - return (count == 1 ? this.includedUrls.get(0) : null); - } - - public void addIncludedUrl(String includedUrl) { - Assert.notNull(includedUrl, "Included URL must not be null"); - this.includedUrls.add(includedUrl); - } - - public List getIncludedUrls() { - return this.includedUrls; - } - - - /** - * Inner class that adapts the ServletOutputStream to mark the - * response as committed once the buffer size is exceeded. - */ - private class ResponseServletOutputStream extends DelegatingServletOutputStream { - - public ResponseServletOutputStream(OutputStream out) { - super(out); - } - - @Override - public void write(int b) throws IOException { - super.write(b); - super.flush(); - setCommittedIfBufferSizeExceeded(); - } - - @Override - public void flush() throws IOException { - super.flush(); - setCommitted(true); - } - } - - - /** - * Inner class that adapts the PrintWriter to mark the - * response as committed once the buffer size is exceeded. - */ - private class ResponsePrintWriter extends PrintWriter { - - public ResponsePrintWriter(Writer out) { - super(out, true); - } - - @Override - public void write(char buf[], int off, int len) { - super.write(buf, off, len); - super.flush(); - setCommittedIfBufferSizeExceeded(); - } - - @Override - public void write(String s, int off, int len) { - super.write(s, off, len); - super.flush(); - setCommittedIfBufferSizeExceeded(); - } - - @Override - public void write(int c) { - super.write(c); - super.flush(); - setCommittedIfBufferSizeExceeded(); - } - - @Override - public void flush() { - super.flush(); - setCommitted(true); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpSession.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpSession.java deleted file mode 100644 index 82a89b61a3..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockHttpSession.java +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import java.io.Serializable; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import javax.servlet.ServletContext; -import javax.servlet.http.HttpSession; -import javax.servlet.http.HttpSessionBindingEvent; -import javax.servlet.http.HttpSessionBindingListener; -import javax.servlet.http.HttpSessionContext; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.servlet.http.HttpSession} interface. - * - *

Compatible with Servlet 2.5 as well as Servlet 3.0. - * - *

Used for testing the web framework; also useful for testing application - * controllers. - * - * @author Juergen Hoeller - * @author Rod Johnson - * @author Mark Fisher - * @author Sam Brannen - * @since 1.0.2 - */ -@SuppressWarnings("deprecation") -public class MockHttpSession implements HttpSession { - - public static final String SESSION_COOKIE_NAME = "JSESSION"; - - private static int nextId = 1; - - private final String id; - - private final long creationTime = System.currentTimeMillis(); - - private int maxInactiveInterval; - - private long lastAccessedTime = System.currentTimeMillis(); - - private final ServletContext servletContext; - - private final Map attributes = new LinkedHashMap(); - - private boolean invalid = false; - - private boolean isNew = true; - - - /** - * Create a new MockHttpSession with a default {@link MockServletContext}. - * - * @see MockServletContext - */ - public MockHttpSession() { - this(null); - } - - /** - * Create a new MockHttpSession. - * - * @param servletContext the ServletContext that the session runs in - */ - public MockHttpSession(ServletContext servletContext) { - this(servletContext, null); - } - - /** - * Create a new MockHttpSession. - * - * @param servletContext the ServletContext that the session runs in - * @param id a unique identifier for this session - */ - public MockHttpSession(ServletContext servletContext, String id) { - this.servletContext = (servletContext != null ? servletContext : new MockServletContext()); - this.id = (id != null ? id : Integer.toString(nextId++)); - } - - @Override - public long getCreationTime() { - return this.creationTime; - } - - @Override - public String getId() { - return this.id; - } - - public void access() { - this.lastAccessedTime = System.currentTimeMillis(); - this.isNew = false; - } - - @Override - public long getLastAccessedTime() { - return this.lastAccessedTime; - } - - @Override - public ServletContext getServletContext() { - return this.servletContext; - } - - @Override - public void setMaxInactiveInterval(int interval) { - this.maxInactiveInterval = interval; - } - - @Override - public int getMaxInactiveInterval() { - return this.maxInactiveInterval; - } - - @Override - public HttpSessionContext getSessionContext() { - throw new UnsupportedOperationException("getSessionContext"); - } - - @Override - public Object getAttribute(String name) { - Assert.notNull(name, "Attribute name must not be null"); - return this.attributes.get(name); - } - - @Override - public Object getValue(String name) { - return getAttribute(name); - } - - @Override - public Enumeration getAttributeNames() { - return Collections.enumeration(this.attributes.keySet()); - } - - @Override - public String[] getValueNames() { - return this.attributes.keySet().toArray(new String[this.attributes.size()]); - } - - @Override - public void setAttribute(String name, Object value) { - Assert.notNull(name, "Attribute name must not be null"); - if (value != null) { - this.attributes.put(name, value); - if (value instanceof HttpSessionBindingListener) { - ((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value)); - } - } - else { - removeAttribute(name); - } - } - - @Override - public void putValue(String name, Object value) { - setAttribute(name, value); - } - - @Override - public void removeAttribute(String name) { - Assert.notNull(name, "Attribute name must not be null"); - Object value = this.attributes.remove(name); - if (value instanceof HttpSessionBindingListener) { - ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value)); - } - } - - @Override - public void removeValue(String name) { - removeAttribute(name); - } - - /** - * Clear all of this session's attributes. - */ - public void clearAttributes() { - for (Iterator> it = this.attributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - String name = entry.getKey(); - Object value = entry.getValue(); - it.remove(); - if (value instanceof HttpSessionBindingListener) { - ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value)); - } - } - } - - /** - * Invalidates this session then unbinds any objects bound to it. - * - * @throws IllegalStateException if this method is called on an already invalidated session - */ - @Override - public void invalidate() { - if (this.invalid) { - throw new IllegalStateException("The session has already been invalidated"); - } - - // else - this.invalid = true; - clearAttributes(); - } - - public boolean isInvalid() { - return this.invalid; - } - - public void setNew(boolean value) { - this.isNew = value; - } - - @Override - public boolean isNew() { - return this.isNew; - } - - /** - * Serialize the attributes of this session into an object that can be - * turned into a byte array with standard Java serialization. - * - * @return a representation of this session's serialized state - */ - public Serializable serializeState() { - HashMap state = new HashMap(); - for (Iterator> it = this.attributes.entrySet().iterator(); it.hasNext();) { - Map.Entry entry = it.next(); - String name = entry.getKey(); - Object value = entry.getValue(); - it.remove(); - if (value instanceof Serializable) { - state.put(name, (Serializable) value); - } - else { - // Not serializable... Servlet containers usually automatically - // unbind the attribute in this case. - if (value instanceof HttpSessionBindingListener) { - ((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value)); - } - } - } - return state; - } - - /** - * Deserialize the attributes of this session from a state object created by - * {@link #serializeState()}. - * - * @param state a representation of this session's serialized state - */ - @SuppressWarnings("unchecked") - public void deserializeState(Serializable state) { - Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]"); - this.attributes.putAll((Map) state); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockMultipartFile.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockMultipartFile.java deleted file mode 100644 index 7d154808d3..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockMultipartFile.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import org.springframework.util.Assert; -import org.springframework.util.FileCopyUtils; -import org.springframework.web.multipart.MultipartFile; - -/** - * Mock implementation of the {@link org.springframework.web.multipart.MultipartFile} - * interface. - * - *

Useful in conjunction with a {@link MockMultipartHttpServletRequest} - * for testing application controllers that access multipart uploads. - * - * @author Juergen Hoeller - * @author Eric Crampton - * @since 2.0 - * @see MockMultipartHttpServletRequest - */ -public class MockMultipartFile implements MultipartFile { - - private final String name; - - private String originalFilename; - - private String contentType; - - private final byte[] content; - - - /** - * Create a new MockMultipartFile with the given content. - * @param name the name of the file - * @param content the content of the file - */ - public MockMultipartFile(String name, byte[] content) { - this(name, "", null, content); - } - - /** - * Create a new MockMultipartFile with the given content. - * @param name the name of the file - * @param contentStream the content of the file as stream - * @throws IOException if reading from the stream failed - */ - public MockMultipartFile(String name, InputStream contentStream) throws IOException { - this(name, "", null, FileCopyUtils.copyToByteArray(contentStream)); - } - - /** - * Create a new MockMultipartFile with the given content. - * @param name the name of the file - * @param originalFilename the original filename (as on the client's machine) - * @param contentType the content type (if known) - * @param content the content of the file - */ - public MockMultipartFile(String name, String originalFilename, String contentType, byte[] content) { - Assert.hasLength(name, "Name must not be null"); - this.name = name; - this.originalFilename = (originalFilename != null ? originalFilename : ""); - this.contentType = contentType; - this.content = (content != null ? content : new byte[0]); - } - - /** - * Create a new MockMultipartFile with the given content. - * @param name the name of the file - * @param originalFilename the original filename (as on the client's machine) - * @param contentType the content type (if known) - * @param contentStream the content of the file as stream - * @throws IOException if reading from the stream failed - */ - public MockMultipartFile(String name, String originalFilename, String contentType, InputStream contentStream) - throws IOException { - - this(name, originalFilename, contentType, FileCopyUtils.copyToByteArray(contentStream)); - } - - - @Override - public String getName() { - return this.name; - } - - @Override - public String getOriginalFilename() { - return this.originalFilename; - } - - @Override - public String getContentType() { - return this.contentType; - } - - @Override - public boolean isEmpty() { - return (this.content.length == 0); - } - - @Override - public long getSize() { - return this.content.length; - } - - @Override - public byte[] getBytes() throws IOException { - return this.content; - } - - @Override - public InputStream getInputStream() throws IOException { - return new ByteArrayInputStream(this.content); - } - - @Override - public void transferTo(File dest) throws IOException, IllegalStateException { - FileCopyUtils.copy(this.content, dest); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java deleted file mode 100644 index e43172c198..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockRequestDispatcher.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.util.Assert; - -/** - * Mock implementation of the {@link javax.servlet.RequestDispatcher} interface. - * - *

Used for testing the web framework; typically not necessary for - * testing application controllers. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @author Sam Brannen - * @since 1.0.2 - */ -public class MockRequestDispatcher implements RequestDispatcher { - - private final Log logger = LogFactory.getLog(getClass()); - - private final String resource; - - - /** - * Create a new MockRequestDispatcher for the given resource. - * @param resource the server resource to dispatch to, located at a - * particular path or given by a particular name - */ - public MockRequestDispatcher(String resource) { - Assert.notNull(resource, "resource must not be null"); - this.resource = resource; - } - - - @Override - public void forward(ServletRequest request, ServletResponse response) { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - if (response.isCommitted()) { - throw new IllegalStateException("Cannot perform forward - response is already committed"); - } - getMockHttpServletResponse(response).setForwardedUrl(this.resource); - if (logger.isDebugEnabled()) { - logger.debug("MockRequestDispatcher: forwarding to [" + this.resource + "]"); - } - } - - @Override - public void include(ServletRequest request, ServletResponse response) { - Assert.notNull(request, "Request must not be null"); - Assert.notNull(response, "Response must not be null"); - getMockHttpServletResponse(response).addIncludedUrl(this.resource); - if (logger.isDebugEnabled()) { - logger.debug("MockRequestDispatcher: including [" + this.resource + "]"); - } - } - - /** - * Obtain the underlying {@link MockHttpServletResponse}, unwrapping - * {@link HttpServletResponseWrapper} decorators if necessary. - */ - protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) { - if (response instanceof MockHttpServletResponse) { - return (MockHttpServletResponse) response; - } - if (response instanceof HttpServletResponseWrapper) { - return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse()); - } - throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse"); - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockServletContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockServletContext.java deleted file mode 100644 index cf3e6e26c1..0000000000 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/MockServletContext.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.mock.web; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Set; -import java.util.Vector; -import javax.activation.FileTypeMap; -import javax.servlet.RequestDispatcher; -import javax.servlet.Servlet; -import javax.servlet.ServletContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; -import org.springframework.util.Assert; -import org.springframework.util.ClassUtils; -import org.springframework.util.ObjectUtils; -import org.springframework.web.util.WebUtils; - -/** - * Mock implementation of the {@link javax.servlet.ServletContext} interface. - * - *

Compatible with Servlet 2.5 and partially with Servlet 3.0. Can be configured to - * expose a specific version through {@link #setMajorVersion}/{@link #setMinorVersion}; - * default is 2.5. Note that Servlet 3.0 support is limited: servlet, filter and listener - * registration methods are not supported; neither is cookie or JSP configuration. - * We generally do not recommend to unit-test your ServletContainerInitializers and - * WebApplicationInitializers which is where those registration methods would be used. - * - *

Used for testing the Spring web framework; only rarely necessary for testing - * application controllers. As long as application components don't explicitly - * access the {@code ServletContext}, {@code ClassPathXmlApplicationContext} or - * {@code FileSystemXmlApplicationContext} can be used to load the context files - * for testing, even for {@code DispatcherServlet} context definitions. - * - *

For setting up a full {@code WebApplicationContext} in a test environment, - * you can use {@code AnnotationConfigWebApplicationContext}, - * {@code XmlWebApplicationContext}, or {@code GenericWebApplicationContext}, - * passing in an appropriate {@code MockServletContext} instance. You might want - * to configure your {@code MockServletContext} with a {@code FileSystemResourceLoader} - * in that case to ensure that resource paths are interpreted as relative filesystem - * locations. - * - *

A common setup is to point your JVM working directory to the root of your - * web application directory, in combination with filesystem-based resource loading. - * This allows to load the context files as used in the web application, with - * relative paths getting interpreted correctly. Such a setup will work with both - * {@code FileSystemXmlApplicationContext} (which will load straight from the - * filesystem) and {@code XmlWebApplicationContext} with an underlying - * {@code MockServletContext} (as long as the {@code MockServletContext} has been - * configured with a {@code FileSystemResourceLoader}). - * - * @author Rod Johnson - * @author Juergen Hoeller - * @author Sam Brannen - * @since 1.0.2 - * @see #MockServletContext(org.springframework.core.io.ResourceLoader) - * @see org.springframework.web.context.support.AnnotationConfigWebApplicationContext - * @see org.springframework.web.context.support.XmlWebApplicationContext - * @see org.springframework.web.context.support.GenericWebApplicationContext - * @see org.springframework.context.support.ClassPathXmlApplicationContext - * @see org.springframework.context.support.FileSystemXmlApplicationContext - */ -public class MockServletContext implements ServletContext { - - /** Default Servlet name used by Tomcat, Jetty, JBoss, and GlassFish: {@value}. */ - private static final String COMMON_DEFAULT_SERVLET_NAME = "default"; - - private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir"; - - private final Log logger = LogFactory.getLog(getClass()); - - private final Map contexts = new HashMap(); - - private final Map initParameters = new LinkedHashMap(); - - private final Map attributes = new LinkedHashMap(); - - private final Set declaredRoles = new HashSet(); - - private final Map namedRequestDispatchers = new HashMap(); - - private final ResourceLoader resourceLoader; - - private final String resourceBasePath; - - private String contextPath = ""; - - private int majorVersion = 2; - - private int minorVersion = 5; - - private int effectiveMajorVersion = 2; - - private int effectiveMinorVersion = 5; - - private String servletContextName = "MockServletContext"; - - private String defaultServletName = COMMON_DEFAULT_SERVLET_NAME; - - - /** - * Create a new MockServletContext, using no base path and a - * DefaultResourceLoader (i.e. the classpath root as WAR root). - * @see org.springframework.core.io.DefaultResourceLoader - */ - public MockServletContext() { - this("", null); - } - - /** - * Create a new MockServletContext, using a DefaultResourceLoader. - * @param resourceBasePath the root directory of the WAR (should not end with a slash) - * @see org.springframework.core.io.DefaultResourceLoader - */ - public MockServletContext(String resourceBasePath) { - this(resourceBasePath, null); - } - - /** - * Create a new MockServletContext, using the specified ResourceLoader - * and no base path. - * @param resourceLoader the ResourceLoader to use (or null for the default) - */ - public MockServletContext(ResourceLoader resourceLoader) { - this("", resourceLoader); - } - - /** - * Create a new MockServletContext using the supplied resource base path and - * resource loader. - *

Registers a {@link MockRequestDispatcher} for the Servlet named - * {@value #COMMON_DEFAULT_SERVLET_NAME}. - * @param resourceBasePath the root directory of the WAR (should not end with a slash) - * @param resourceLoader the ResourceLoader to use (or null for the default) - * @see #registerNamedDispatcher - */ - public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) { - this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader()); - this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : ""); - - // Use JVM temp dir as ServletContext temp dir. - String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY); - if (tempDir != null) { - this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir)); - } - - registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName)); - } - - /** - * Build a full resource location for the given path, - * prepending the resource base path of this MockServletContext. - * @param path the path as specified - * @return the full resource path - */ - protected String getResourceLocation(String path) { - if (!path.startsWith("/")) { - path = "/" + path; - } - return this.resourceBasePath + path; - } - - public void setContextPath(String contextPath) { - this.contextPath = (contextPath != null ? contextPath : ""); - } - - /* This is a Servlet API 2.5 method. */ - @Override - public String getContextPath() { - return this.contextPath; - } - - public void registerContext(String contextPath, ServletContext context) { - this.contexts.put(contextPath, context); - } - - @Override - public ServletContext getContext(String contextPath) { - if (this.contextPath.equals(contextPath)) { - return this; - } - return this.contexts.get(contextPath); - } - - public void setMajorVersion(int majorVersion) { - this.majorVersion = majorVersion; - } - - @Override - public int getMajorVersion() { - return this.majorVersion; - } - - public void setMinorVersion(int minorVersion) { - this.minorVersion = minorVersion; - } - - @Override - public int getMinorVersion() { - return this.minorVersion; - } - - public void setEffectiveMajorVersion(int effectiveMajorVersion) { - this.effectiveMajorVersion = effectiveMajorVersion; - } - - public int getEffectiveMajorVersion() { - return this.effectiveMajorVersion; - } - - public void setEffectiveMinorVersion(int effectiveMinorVersion) { - this.effectiveMinorVersion = effectiveMinorVersion; - } - - public int getEffectiveMinorVersion() { - return this.effectiveMinorVersion; - } - - @Override - public String getMimeType(String filePath) { - return MimeTypeResolver.getMimeType(filePath); - } - - @Override - public Set getResourcePaths(String path) { - String actualPath = (path.endsWith("/") ? path : path + "/"); - Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath)); - try { - File file = resource.getFile(); - String[] fileList = file.list(); - if (ObjectUtils.isEmpty(fileList)) { - return null; - } - Set resourcePaths = new LinkedHashSet(fileList.length); - for (String fileEntry : fileList) { - String resultPath = actualPath + fileEntry; - if (resource.createRelative(fileEntry).getFile().isDirectory()) { - resultPath += "/"; - } - resourcePaths.add(resultPath); - } - return resourcePaths; - } - catch (IOException ex) { - logger.warn("Couldn't get resource paths for " + resource, ex); - return null; - } - } - - @Override - public URL getResource(String path) throws MalformedURLException { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - if (!resource.exists()) { - return null; - } - try { - return resource.getURL(); - } - catch (MalformedURLException ex) { - throw ex; - } - catch (IOException ex) { - logger.warn("Couldn't get URL for " + resource, ex); - return null; - } - } - - @Override - public InputStream getResourceAsStream(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - if (!resource.exists()) { - return null; - } - try { - return resource.getInputStream(); - } - catch (IOException ex) { - logger.warn("Couldn't open InputStream for " + resource, ex); - return null; - } - } - - @Override - public RequestDispatcher getRequestDispatcher(String path) { - if (!path.startsWith("/")) { - throw new IllegalArgumentException("RequestDispatcher path at ServletContext level must start with '/'"); - } - return new MockRequestDispatcher(path); - } - - @Override - public RequestDispatcher getNamedDispatcher(String path) { - return this.namedRequestDispatchers.get(path); - } - - /** - * Register a {@link RequestDispatcher} (typically a {@link MockRequestDispatcher}) - * that acts as a wrapper for the named Servlet. - * - * @param name the name of the wrapped Servlet - * @param requestDispatcher the dispatcher that wraps the named Servlet - * @see #getNamedDispatcher - * @see #unregisterNamedDispatcher - */ - public void registerNamedDispatcher(String name, RequestDispatcher requestDispatcher) { - Assert.notNull(name, "RequestDispatcher name must not be null"); - Assert.notNull(requestDispatcher, "RequestDispatcher must not be null"); - this.namedRequestDispatchers.put(name, requestDispatcher); - } - - /** - * Unregister the {@link RequestDispatcher} with the given name. - * - * @param name the name of the dispatcher to unregister - * @see #getNamedDispatcher - * @see #registerNamedDispatcher - */ - public void unregisterNamedDispatcher(String name) { - Assert.notNull(name, "RequestDispatcher name must not be null"); - this.namedRequestDispatchers.remove(name); - } - - /** - * Get the name of the default {@code Servlet}. - *

Defaults to {@value #COMMON_DEFAULT_SERVLET_NAME}. - * @see #setDefaultServletName - */ - public String getDefaultServletName() { - return this.defaultServletName; - } - - /** - * Set the name of the default {@code Servlet}. - *

Also {@link #unregisterNamedDispatcher unregisters} the current default - * {@link RequestDispatcher} and {@link #registerNamedDispatcher replaces} - * it with a {@link MockRequestDispatcher} for the provided - * {@code defaultServletName}. - * @param defaultServletName the name of the default {@code Servlet}; - * never {@code null} or empty - * @see #getDefaultServletName - */ - public void setDefaultServletName(String defaultServletName) { - Assert.hasText(defaultServletName, "defaultServletName must not be null or empty"); - unregisterNamedDispatcher(this.defaultServletName); - this.defaultServletName = defaultServletName; - registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName)); - } - - @Override - public Servlet getServlet(String name) { - return null; - } - - @Override - public Enumeration getServlets() { - return Collections.enumeration(new HashSet()); - } - - @Override - public Enumeration getServletNames() { - return Collections.enumeration(new HashSet()); - } - - @Override - public void log(String message) { - logger.info(message); - } - - @Override - public void log(Exception ex, String message) { - logger.info(message, ex); - } - - @Override - public void log(String message, Throwable ex) { - logger.info(message, ex); - } - - @Override - public String getRealPath(String path) { - Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); - try { - return resource.getFile().getAbsolutePath(); - } - catch (IOException ex) { - logger.warn("Couldn't determine real path of resource " + resource, ex); - return null; - } - } - - @Override - public String getServerInfo() { - return "MockServletContext"; - } - - @Override - public String getInitParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.initParameters.get(name); - } - - @Override - public Enumeration getInitParameterNames() { - return Collections.enumeration(this.initParameters.keySet()); - } - - public boolean setInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - if (this.initParameters.containsKey(name)) { - return false; - } - this.initParameters.put(name, value); - return true; - } - - public void addInitParameter(String name, String value) { - Assert.notNull(name, "Parameter name must not be null"); - this.initParameters.put(name, value); - } - - @Override - public Object getAttribute(String name) { - Assert.notNull(name, "Attribute name must not be null"); - return this.attributes.get(name); - } - - @Override - public Enumeration getAttributeNames() { - return new Vector(this.attributes.keySet()).elements(); - } - - @Override - public void setAttribute(String name, Object value) { - Assert.notNull(name, "Attribute name must not be null"); - if (value != null) { - this.attributes.put(name, value); - } - else { - this.attributes.remove(name); - } - } - - @Override - public void removeAttribute(String name) { - Assert.notNull(name, "Attribute name must not be null"); - this.attributes.remove(name); - } - - public void setServletContextName(String servletContextName) { - this.servletContextName = servletContextName; - } - - @Override - public String getServletContextName() { - return this.servletContextName; - } - - public ClassLoader getClassLoader() { - return ClassUtils.getDefaultClassLoader(); - } - - public void declareRoles(String... roleNames) { - Assert.notNull(roleNames, "Role names array must not be null"); - for (String roleName : roleNames) { - Assert.hasLength(roleName, "Role name must not be empty"); - this.declaredRoles.add(roleName); - } - } - - public Set getDeclaredRoles() { - return Collections.unmodifiableSet(this.declaredRoles); - } - - - /** - * Inner factory class used to introduce a Java Activation Framework - * dependency when actually asked to resolve a MIME type. - */ - private static class MimeTypeResolver { - - public static String getMimeType(String filePath) { - return FileTypeMap.getDefaultFileTypeMap().getContentType(filePath); - } - } - -} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java index 963ae040f2..da8aa73cac 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/mock/web/portlet/MockPortletSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,13 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; + import javax.portlet.PortletContext; import javax.portlet.PortletSession; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; -import org.springframework.mock.web.MockHttpSession; +import org.springframework.mock.web.test.MockHttpSession; /** * Mock implementation of the {@link javax.portlet.PortletSession} interface. diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java index 6cb7e3ae5f..b1b1459ee7 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/ComplexPortletApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; + import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.EventRequest; @@ -47,9 +48,9 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.Ordered; -import org.springframework.mock.web.MockMultipartFile; import org.springframework.mock.web.portlet.MockPortletConfig; import org.springframework.mock.web.portlet.MockPortletContext; +import org.springframework.mock.web.test.MockMultipartFile; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MaxUploadSizeExceededException; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java index 46ea7b2ba0..fdb7d9df46 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/DispatcherPortletTests.java @@ -1,5 +1,5 @@ /* -* Copyright 2002-2012 the original author or authors. +* Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import javax.portlet.PortletSession; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.i18n.LocaleContext; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/SimplePortletApplicationContext.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/SimplePortletApplicationContext.java index 7bd390f9d2..3f53c7edfa 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/SimplePortletApplicationContext.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/SimplePortletApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import javax.portlet.RenderResponse; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.RuntimeBeanReference; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.validation.BindException; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java index 3f46ddd3a8..3bf2462489 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestDataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import java.util.Set; import junit.framework.TestCase; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.StringArrayPropertyEditor; import org.springframework.mock.web.portlet.MockPortletRequest; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java index 8aeeb819b5..bec09daa5e 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/AbstractXmlWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.web.portlet.context; import javax.servlet.ServletException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.AbstractApplicationContextTests; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java index 452ddb3c52..288b901f37 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/PortletApplicationContextScopeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,20 @@ package org.springframework.web.portlet.context; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + import javax.portlet.PortletContext; import javax.portlet.PortletSession; import javax.servlet.ServletContextEvent; -import static org.junit.Assert.*; import org.junit.Test; - -import org.springframework.beans.DerivedTestBean; import org.springframework.beans.factory.support.GenericBeanDefinition; -import org.springframework.mock.web.MockServletContext; import org.springframework.mock.web.portlet.MockRenderRequest; import org.springframework.mock.web.portlet.ServletWrappingPortletContext; +import org.springframework.mock.web.test.MockServletContext; +import org.springframework.tests.sample.beans.DerivedTestBean; import org.springframework.web.context.ContextCleanupListener; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.RequestContextHolder; @@ -125,4 +127,4 @@ public class PortletApplicationContextScopeTests { assertTrue(bean.wasDestroyed()); } -} \ No newline at end of file +} diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml index 04bc32bb88..9a4a216313 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml @@ -9,7 +9,7 @@ - + - + dummy @@ -45,7 +45,7 @@ Tests of lifecycle callbacks --> + class="org.springframework.tests.sample.beans.MustBeInitialized"> - + yetanotherdummy diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml index 4002703b21..85885f238d 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml @@ -15,7 +15,7 @@ - + Rod 31 @@ -28,32 +28,32 @@ 31 - + - + Kerry 34 - + typeMismatch 34x - + - + false - + listenerVeto 66 - + diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java index 9ec0c1be3b..2df278bba0 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/context/XmlPortletApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import javax.portlet.PortletConfig; import javax.portlet.PortletContext; import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/CommandControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/CommandControllerTests.java index bad1796241..2ea777d8c4 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/CommandControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/CommandControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,8 @@ import javax.portlet.WindowState; import junit.framework.TestCase; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.mock.web.portlet.MockActionRequest; import org.springframework.mock.web.portlet.MockActionResponse; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java index 4705be2f54..600dc7e8fa 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/Portlet20AnnotationControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,9 +41,9 @@ import javax.servlet.http.Cookie; import org.junit.Test; import org.springframework.beans.BeansException; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.propertyeditors.CustomDateEditor; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java index 072476b61d..7a58b4a1c4 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/mvc/annotation/PortletAnnotationControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,9 +38,9 @@ import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; import org.springframework.beans.BeansException; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.beans.propertyeditors.CustomDateEditor; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java index c291a8e74b..8fd99d5357 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/util/PortletUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import javax.portlet.PortletSession; import org.junit.Test; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.portlet.MockActionRequest; import org.springframework.mock.web.portlet.MockActionResponse; import org.springframework.mock.web.portlet.MockPortletContext; diff --git a/spring-webmvc/src/test/java/org/springframework/beans/BeanWithObjectProperty.java b/spring-webmvc/src/test/java/org/springframework/beans/BeanWithObjectProperty.java deleted file mode 100644 index bb5e71f5cd..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/BeanWithObjectProperty.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2002-2005 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.beans; - -/** - * @author Juergen Hoeller - * @since 17.08.2004 - */ -public class BeanWithObjectProperty { - - private Object object; - - public Object getObject() { - return object; - } - - public void setObject(Object object) { - this.object = object; - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/Colour.java b/spring-webmvc/src/test/java/org/springframework/beans/Colour.java deleted file mode 100644 index a992a2ebfc..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/beans/DerivedTestBean.java b/spring-webmvc/src/test/java/org/springframework/beans/DerivedTestBean.java deleted file mode 100644 index c5360de531..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/DerivedTestBean.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.Serializable; - -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.beans.factory.DisposableBean; - -/** - * @author Juergen Hoeller - * @since 21.08.2003 - */ -@SuppressWarnings("serial") -public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean { - - private String beanName; - - private boolean initialized; - - private boolean destroyed; - - - public DerivedTestBean() { - } - - public DerivedTestBean(String[] names) { - if (names == null || names.length < 2) { - throw new IllegalArgumentException("Invalid names array"); - } - setName(names[0]); - setBeanName(names[1]); - } - - public static DerivedTestBean create(String[] names) { - return new DerivedTestBean(names); - } - - - @Override - public void setBeanName(String beanName) { - if (this.beanName == null || beanName == null) { - this.beanName = beanName; - } - } - - @Override - public String getBeanName() { - return beanName; - } - - public void setSpouseRef(String name) { - setSpouse(new TestBean(name)); - } - - - public void initialize() { - this.initialized = true; - } - - public boolean wasInitialized() { - return initialized; - } - - - @Override - public void destroy() { - this.destroyed = true; - } - - @Override - public boolean wasDestroyed() { - return destroyed; - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/beans/GenericBean.java b/spring-webmvc/src/test/java/org/springframework/beans/GenericBean.java deleted file mode 100644 index 00dd127e47..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/GenericBean.java +++ /dev/null @@ -1,247 +0,0 @@ -/* - * Copyright 2002-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.core.io.Resource; - -/** - * @author Juergen Hoeller - */ -public class GenericBean { - - private Set integerSet; - - private Set testBeanSet; - - private List resourceList; - - private List> listOfLists; - - private ArrayList listOfArrays; - - private List> listOfMaps; - - private Map plainMap; - - private Map shortMap; - - private HashMap longMap; - - private Map> collectionMap; - - private Map> mapOfMaps; - - private Map> mapOfLists; - - private CustomEnum customEnum; - - private T genericProperty; - - private List genericListProperty; - - - public GenericBean() { - } - - public GenericBean(Set integerSet) { - this.integerSet = integerSet; - } - - public GenericBean(Set integerSet, List resourceList) { - this.integerSet = integerSet; - this.resourceList = resourceList; - } - - public GenericBean(HashSet integerSet, Map shortMap) { - this.integerSet = integerSet; - this.shortMap = shortMap; - } - - public GenericBean(Map shortMap, Resource resource) { - this.shortMap = shortMap; - this.resourceList = Collections.singletonList(resource); - } - - public GenericBean(Map plainMap, Map shortMap) { - this.plainMap = plainMap; - this.shortMap = shortMap; - } - - public GenericBean(HashMap longMap) { - this.longMap = longMap; - } - - public GenericBean(boolean someFlag, Map> collectionMap) { - this.collectionMap = collectionMap; - } - - - public Set getIntegerSet() { - return integerSet; - } - - public void setIntegerSet(Set integerSet) { - this.integerSet = integerSet; - } - - public Set getTestBeanSet() { - return testBeanSet; - } - - public void setTestBeanSet(Set testBeanSet) { - this.testBeanSet = testBeanSet; - } - - public List getResourceList() { - return resourceList; - } - - public void setResourceList(List resourceList) { - this.resourceList = resourceList; - } - - public List> getListOfLists() { - return listOfLists; - } - - public ArrayList getListOfArrays() { - return listOfArrays; - } - - public void setListOfArrays(ArrayList listOfArrays) { - this.listOfArrays = listOfArrays; - } - - public void setListOfLists(List> listOfLists) { - this.listOfLists = listOfLists; - } - - public List> getListOfMaps() { - return listOfMaps; - } - - public void setListOfMaps(List> listOfMaps) { - this.listOfMaps = listOfMaps; - } - - public Map getPlainMap() { - return plainMap; - } - - public Map getShortMap() { - return shortMap; - } - - public void setShortMap(Map shortMap) { - this.shortMap = shortMap; - } - - public HashMap getLongMap() { - return longMap; - } - - public void setLongMap(HashMap longMap) { - this.longMap = longMap; - } - - public Map> getCollectionMap() { - return collectionMap; - } - - public void setCollectionMap(Map> collectionMap) { - this.collectionMap = collectionMap; - } - - public Map> getMapOfMaps() { - return mapOfMaps; - } - - public void setMapOfMaps(Map> mapOfMaps) { - this.mapOfMaps = mapOfMaps; - } - - public Map> getMapOfLists() { - return mapOfLists; - } - - public void setMapOfLists(Map> mapOfLists) { - this.mapOfLists = mapOfLists; - } - - public T getGenericProperty() { - return genericProperty; - } - - public void setGenericProperty(T genericProperty) { - this.genericProperty = genericProperty; - } - - public List getGenericListProperty() { - return genericListProperty; - } - - public void setGenericListProperty(List genericListProperty) { - this.genericListProperty = genericListProperty; - } - - public CustomEnum getCustomEnum() { - return customEnum; - } - - public void setCustomEnum(CustomEnum customEnum) { - this.customEnum = customEnum; - } - - - public static GenericBean createInstance(Set integerSet) { - return new GenericBean(integerSet); - } - - public static GenericBean createInstance(Set integerSet, List resourceList) { - return new GenericBean(integerSet, resourceList); - } - - public static GenericBean createInstance(HashSet integerSet, Map shortMap) { - return new GenericBean(integerSet, shortMap); - } - - public static GenericBean createInstance(Map shortMap, Resource resource) { - return new GenericBean(shortMap, resource); - } - - public static GenericBean createInstance(Map map, Map shortMap) { - return new GenericBean(map, shortMap); - } - - public static GenericBean createInstance(HashMap longMap) { - return new GenericBean(longMap); - } - - public static GenericBean createInstance(boolean someFlag, Map> collectionMap) { - return new GenericBean(someFlag, collectionMap); - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/INestedTestBean.java b/spring-webmvc/src/test/java/org/springframework/beans/INestedTestBean.java deleted file mode 100644 index e0ae5f20a3..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/IOther.java b/spring-webmvc/src/test/java/org/springframework/beans/IOther.java deleted file mode 100644 index d7fb346185..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -public interface IOther { - - void absquatulate(); - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/ITestBean.java b/spring-webmvc/src/test/java/org/springframework/beans/ITestBean.java deleted file mode 100644 index cdf5ef510d..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2007 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.beans; - -import java.io.IOException; - -/** - * Interface used for {@link org.springframework.beans.TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/IndexedTestBean.java b/spring-webmvc/src/test/java/org/springframework/beans/IndexedTestBean.java deleted file mode 100644 index ddb091770e..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/NestedTestBean.java b/spring-webmvc/src/test/java/org/springframework/beans/NestedTestBean.java deleted file mode 100644 index 412891c439..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/Person.java b/spring-webmvc/src/test/java/org/springframework/beans/Person.java deleted file mode 100644 index 7c66f4b451..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/Person.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * - * @author Rod Johnson - */ -public interface Person { - - String getName(); - void setName(String name); - int getAge(); - void setAge(int i); - - /** - * Test for non-property method matching. - * If the parameter is a Throwable, it will be thrown rather than - * returned. - */ - Object echo(Object o) throws Throwable; -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/Pet.java b/spring-webmvc/src/test/java/org/springframework/beans/Pet.java deleted file mode 100644 index 35d9c736c1..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/Pet.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2002-2006 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -/** - * @author Rob Harrop - * @since 2.0 - */ -public class Pet { - - private String name; - - public Pet(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public String toString() { - return getName(); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final Pet pet = (Pet) o; - - if (name != null ? !name.equals(pet.name) : pet.name != null) return false; - - return true; - } - - public int hashCode() { - return (name != null ? name.hashCode() : 0); - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/TestBean.java b/spring-webmvc/src/test/java/org/springframework/beans/TestBean.java deleted file mode 100644 index 6d71de7576..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/TestBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see org.springframework.beans.ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see org.springframework.beans.ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see org.springframework.beans.IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/factory/DummyFactory.java b/spring-webmvc/src/test/java/org/springframework/beans/factory/DummyFactory.java deleted file mode 100644 index 6fc7e36aa9..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/factory/DummyFactory.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; - -/** - * Simple factory to allow testing of FactoryBean support in AbstractBeanFactory. - * Depending on whether its singleton property is set, it will return a singleton - * or a prototype instance. - * - *

Implements InitializingBean interface, so we can check that - * factories get this lifecycle callback if they want. - * - * @author Rod Johnson - * @since 10.03.2003 - */ -public class DummyFactory - implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { - - public static final String SINGLETON_NAME = "Factory singleton"; - - private static boolean prototypeCreated; - - /** - * Clear static state. - */ - public static void reset() { - prototypeCreated = false; - } - - - /** - * Default is for factories to return a singleton instance. - */ - private boolean singleton = true; - - private String beanName; - - private AutowireCapableBeanFactory beanFactory; - - private boolean postProcessed; - - private boolean initialized; - - private TestBean testBean; - - private TestBean otherTestBean; - - - public DummyFactory() { - this.testBean = new TestBean(); - this.testBean.setName(SINGLETON_NAME); - this.testBean.setAge(25); - } - - /** - * Return if the bean managed by this factory is a singleton. - * @see FactoryBean#isSingleton() - */ - @Override - public boolean isSingleton() { - return this.singleton; - } - - /** - * Set if the bean managed by this factory is a singleton. - */ - public void setSingleton(boolean singleton) { - this.singleton = singleton; - } - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = (AutowireCapableBeanFactory) beanFactory; - this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName); - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - public void setOtherTestBean(TestBean otherTestBean) { - this.otherTestBean = otherTestBean; - this.testBean.setSpouse(otherTestBean); - } - - public TestBean getOtherTestBean() { - return otherTestBean; - } - - @Override - public void afterPropertiesSet() { - if (initialized) { - throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean"); - } - this.initialized = true; - } - - /** - * Was this initialized by invocation of the - * afterPropertiesSet() method from the InitializingBean interface? - */ - public boolean wasInitialized() { - return initialized; - } - - public static boolean wasPrototypeCreated() { - return prototypeCreated; - } - - - /** - * Return the managed object, supporting both singleton - * and prototype mode. - * @see FactoryBean#getObject() - */ - @Override - public Object getObject() throws BeansException { - if (isSingleton()) { - return this.testBean; - } - else { - TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11); - if (this.beanFactory != null) { - this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName); - } - prototypeCreated = true; - return prototype; - } - } - - @Override - public Class getObjectType() { - return TestBean.class; - } - - - @Override - public void destroy() { - if (this.testBean != null) { - this.testBean.setName(null); - } - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/factory/LifecycleBean.java b/spring-webmvc/src/test/java/org/springframework/beans/factory/LifecycleBean.java deleted file mode 100644 index 013a65a0e4..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/factory/LifecycleBean.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanPostProcessor; - -/** - * Simple test of BeanFactory initialization and lifecycle callbacks. - * - * @author Rod Johnson - * @author Colin Sampaleanu - * @since 12.03.2003 - */ -public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean { - - protected boolean initMethodDeclared = false; - - protected String beanName; - - protected BeanFactory owningFactory; - - protected boolean postProcessedBeforeInit; - - protected boolean inited; - - protected boolean initedViaDeclaredInitMethod; - - protected boolean postProcessedAfterInit; - - protected boolean destroyed; - - - public void setInitMethodDeclared(boolean initMethodDeclared) { - this.initMethodDeclared = initMethodDeclared; - } - - public boolean isInitMethodDeclared() { - return initMethodDeclared; - } - - @Override - public void setBeanName(String name) { - this.beanName = name; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.owningFactory = beanFactory; - } - - public void postProcessBeforeInit() { - if (this.inited || this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet"); - } - if (this.postProcessedBeforeInit) { - throw new RuntimeException("Factory called postProcessBeforeInit twice"); - } - this.postProcessedBeforeInit = true; - } - - @Override - public void afterPropertiesSet() { - if (this.owningFactory == null) { - throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean"); - } - if (!this.postProcessedBeforeInit) { - throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean"); - } - if (this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet"); - } - if (this.inited) { - throw new RuntimeException("Factory called afterPropertiesSet twice"); - } - this.inited = true; - } - - public void declaredInitMethod() { - if (!this.inited) { - throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method"); - } - - if (this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called declared init method twice"); - } - this.initedViaDeclaredInitMethod = true; - } - - public void postProcessAfterInit() { - if (!this.inited) { - throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet"); - } - if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) { - throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method"); - } - if (this.postProcessedAfterInit) { - throw new RuntimeException("Factory called postProcessAfterInit twice"); - } - this.postProcessedAfterInit = true; - } - - /** - * Dummy business method that will fail unless the factory - * managed the bean's lifecycle correctly - */ - public void businessMethod() { - if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) || - !this.postProcessedAfterInit) { - throw new RuntimeException("Factory didn't initialize lifecycle object correctly"); - } - } - - @Override - public void destroy() { - if (this.destroyed) { - throw new IllegalStateException("Already destroyed"); - } - this.destroyed = true; - } - - public boolean isDestroyed() { - return destroyed; - } - - - public static class PostProcessor implements BeanPostProcessor { - - @Override - public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessBeforeInit(); - } - return bean; - } - - @Override - public Object postProcessAfterInitialization(Object bean, String name) throws BeansException { - if (bean instanceof LifecycleBean) { - ((LifecycleBean) bean).postProcessAfterInit(); - } - return bean; - } - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/beans/factory/MustBeInitialized.java b/spring-webmvc/src/test/java/org/springframework/beans/factory/MustBeInitialized.java deleted file mode 100644 index b9a7925ad8..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/beans/factory/MustBeInitialized.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.beans.factory; - -import org.springframework.beans.factory.InitializingBean; - -/** - * Simple test of BeanFactory initialization - * @author Rod Johnson - * @since 12.03.2003 - */ -public class MustBeInitialized implements InitializingBean { - - private boolean inited; - - /** - * @see InitializingBean#afterPropertiesSet() - */ - @Override - public void afterPropertiesSet() throws Exception { - this.inited = true; - } - - /** - * Dummy business method that will fail unless the factory - * managed the bean's lifecycle correctly - */ - public void businessMethod() { - if (!this.inited) - throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object"); - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/context/LifecycleContextBean.java b/spring-webmvc/src/test/java/org/springframework/context/LifecycleContextBean.java index 14acac1ceb..37d4c9715f 100644 --- a/spring-webmvc/src/test/java/org/springframework/context/LifecycleContextBean.java +++ b/spring-webmvc/src/test/java/org/springframework/context/LifecycleContextBean.java @@ -3,7 +3,7 @@ package org.springframework.context; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.LifecycleBean; +import org.springframework.tests.sample.beans.LifecycleBean; /** * Simple bean to test ApplicationContext lifecycle methods for beans diff --git a/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java b/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java deleted file mode 100644 index 3d0bce4c84..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/PersonBean.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2002-2005 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.ui.jasperreports; - -/** - * @author Rob Harrop - */ -public class PersonBean { - - private int id; - - private String name; - - private String street; - - private String city; - - public String getCity() { - return city; - } - - public void setCity(String city) { - this.city = city; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/ProductBean.java b/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/ProductBean.java deleted file mode 100644 index 070fa2dc42..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/ui/jasperreports/ProductBean.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2002-2005 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.ui.jasperreports; - -/** - * @author Rob Harrop - */ -public class ProductBean { - - private int id; - - private String name; - - private float quantity; - - private float price; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public float getQuantity() { - return quantity; - } - - public void setQuantity(float quantity) { - this.quantity = quantity; - } - - public float getPrice() { - return price; - } - - public void setPrice(float price) { - this.price = price; - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/util/SerializationTestUtils.java b/spring-webmvc/src/test/java/org/springframework/util/SerializationTestUtils.java deleted file mode 100644 index 9ae4f54ec2..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/util/SerializationTestUtils.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2002-2009 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * - * @author Rod Johnson - */ -public class SerializationTestUtils { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - return o2; - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/AbstractApplicationContextTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/AbstractApplicationContextTests.java deleted file mode 100644 index facc86bace..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/context/AbstractApplicationContextTests.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.web.context; - -import java.util.Locale; - -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.LifecycleBean; -import org.springframework.context.ACATester; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.BeanThatListens; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.NoSuchMessageException; -import org.springframework.context.TestListener; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests { - - /** Must be supplied as XML */ - public static final String TEST_NAMESPACE = "testNamespace"; - - protected ConfigurableApplicationContext applicationContext; - - /** Subclass must register this */ - protected TestListener listener = new TestListener(); - - protected TestListener parentListener = new TestListener(); - - @Override - protected void setUp() throws Exception { - this.applicationContext = createContext(); - } - - @Override - protected BeanFactory getBeanFactory() { - return applicationContext; - } - - protected ApplicationContext getApplicationContext() { - return applicationContext; - } - - /** - * Must register a TestListener. - * Must register standard beans. - * Parent must register rod with name Roderick - * and father with name Albert. - */ - protected abstract ConfigurableApplicationContext createContext() throws Exception; - - public void testContextAwareSingletonWasCalledBack() throws Exception { - ACATester aca = (ACATester) applicationContext.getBean("aca"); - assertTrue("has had context set", aca.getApplicationContext() == applicationContext); - Object aca2 = applicationContext.getBean("aca"); - assertTrue("Same instance", aca == aca2); - assertTrue("Says is singleton", applicationContext.isSingleton("aca")); - } - - public void testContextAwarePrototypeWasCalledBack() throws Exception { - ACATester aca = (ACATester) applicationContext.getBean("aca-prototype"); - assertTrue("has had context set", aca.getApplicationContext() == applicationContext); - Object aca2 = applicationContext.getBean("aca-prototype"); - assertTrue("NOT Same instance", aca != aca2); - assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype")); - } - - public void testParentNonNull() { - assertTrue("parent isn't null", applicationContext.getParent() != null); - } - - public void testGrandparentNull() { - assertTrue("grandparent is null", applicationContext.getParent().getParent() == null); - } - - public void testOverrideWorked() throws Exception { - TestBean rod = (TestBean) applicationContext.getParent().getBean("rod"); - assertTrue("Parent's name differs", rod.getName().equals("Roderick")); - } - - public void testGrandparentDefinitionFound() throws Exception { - TestBean dad = (TestBean) applicationContext.getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testGrandparentTypedDefinitionFound() throws Exception { - TestBean dad = applicationContext.getBean("father", TestBean.class); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testCloseTriggersDestroy() { - LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle"); - assertTrue("Not destroyed", !lb.isDestroyed()); - applicationContext.close(); - if (applicationContext.getParent() != null) { - ((ConfigurableApplicationContext) applicationContext.getParent()).close(); - } - assertTrue("Destroyed", lb.isDestroyed()); - applicationContext.close(); - if (applicationContext.getParent() != null) { - ((ConfigurableApplicationContext) applicationContext.getParent()).close(); - } - assertTrue("Destroyed", lb.isDestroyed()); - } - - public void testMessageSource() throws NoSuchMessageException { - assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault())); - assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault())); - - try { - applicationContext.getMessage("code0", null, Locale.getDefault()); - fail("looking for code0 should throw a NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // that's how it should be - } - } - - public void testEvents() throws Exception { - listener.zeroCounter(); - parentListener.zeroCounter(); - assertTrue("0 events before publication", listener.getEventCount() == 0); - assertTrue("0 parent events before publication", parentListener.getEventCount() == 0); - this.applicationContext.publishEvent(new MyEvent(this)); - assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1); - assertTrue("1 parent events after publication", parentListener.getEventCount() == 1); - } - - public void testBeanAutomaticallyHearsEvents() throws Exception { - //String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class); - //assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens")); - BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens"); - b.zero(); - assertTrue("0 events before publication", b.getEventCount() == 0); - this.applicationContext.publishEvent(new MyEvent(this)); - assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1); - } - - - @SuppressWarnings("serial") - public static class MyEvent extends ApplicationEvent { - - public MyEvent(Object source) { - super(source); - } - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/AbstractBeanFactoryTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/AbstractBeanFactoryTests.java deleted file mode 100644 index e51cb8d151..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/context/AbstractBeanFactoryTests.java +++ /dev/null @@ -1,337 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.web.context; - -import java.beans.PropertyEditorSupport; -import java.util.StringTokenizer; - -import junit.framework.TestCase; - -import org.springframework.beans.BeansException; -import org.springframework.beans.PropertyBatchUpdateException; -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanIsNotAFactoryException; -import org.springframework.beans.factory.BeanNotOfRequiredTypeException; -import org.springframework.beans.factory.DummyFactory; -import org.springframework.beans.factory.LifecycleBean; -import org.springframework.beans.factory.MustBeInitialized; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; - -/** - * Subclasses must implement setUp() to initialize bean factory - * and any other variables they need. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractBeanFactoryTests extends TestCase { - - protected abstract BeanFactory getBeanFactory(); - - /** - * Roderick beans inherits from rod, overriding name only. - */ - public void testInheritance() { - assertTrue(getBeanFactory().containsBean("rod")); - assertTrue(getBeanFactory().containsBean("roderick")); - TestBean rod = (TestBean) getBeanFactory().getBean("rod"); - TestBean roderick = (TestBean) getBeanFactory().getBean("roderick"); - assertTrue("not == ", rod != roderick); - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick")); - assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge()); - } - - public void testGetBeanWithNullArg() { - try { - getBeanFactory().getBean((String) null); - fail("Can't get null bean"); - } - catch (IllegalArgumentException ex) { - // OK - } - } - - /** - * Test that InitializingBean objects receive the afterPropertiesSet() callback - */ - public void testInitializingBeanCallback() { - MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized"); - // The dummy business method will throw an exception if the - // afterPropertiesSet() callback wasn't invoked - mbi.businessMethod(); - } - - /** - * Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the - * afterPropertiesSet() callback before BeanFactoryAware callbacks - */ - public void testLifecycleCallbacks() { - LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle"); - assertEquals("lifecycle", lb.getBeanName()); - // The dummy business method will throw an exception if the - // necessary callbacks weren't invoked in the right order. - lb.businessMethod(); - assertTrue("Not destroyed", !lb.isDestroyed()); - } - - public void testFindsValidInstance() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - TestBean rod = (TestBean) o; - assertTrue("rod.name is Rod", rod.getName().equals("Rod")); - assertTrue("rod.age is 31", rod.getAge() == 31); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testGetInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetInstanceByNonmatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass()); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testGetSharedInstanceByMatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance with matching class"); - } - } - - public void testGetSharedInstanceByMatchingClassNoCatch() { - Object o = getBeanFactory().getBean("rod", TestBean.class); - assertTrue("Rod bean is a TestBean", o instanceof TestBean); - } - - public void testGetSharedInstanceByNonmatchingClass() { - try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); - fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); - } - catch (BeanNotOfRequiredTypeException ex) { - // So far, so good - assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod")); - assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class)); - assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType())); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testSharedInstancesAreEqual() { - try { - Object o = getBeanFactory().getBean("rod"); - assertTrue("Rod bean1 is a TestBean", o instanceof TestBean); - Object o1 = getBeanFactory().getBean("rod"); - assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean); - assertTrue("Object equals applies", o == o1); - } - catch (Exception ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testPrototypeInstancesAreIndependent() { - TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy"); - TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy"); - assertTrue("ref equal DOES NOT apply", tb1 != tb2); - assertTrue("object equal true", tb1.equals(tb2)); - tb1.setAge(1); - tb2.setAge(2); - assertTrue("1 age independent = 1", tb1.getAge() == 1); - assertTrue("2 age independent = 2", tb2.getAge() == 2); - assertTrue("object equal now false", !tb1.equals(tb2)); - } - - public void testNotThere() { - assertFalse(getBeanFactory().containsBean("Mr Squiggle")); - try { - Object o = getBeanFactory().getBean("Mr Squiggle"); - fail("Can't find missing bean"); - } - catch (BeansException ex) { - //ex.printStackTrace(); - //fail("Shouldn't throw exception on getting valid instance"); - } - } - - public void testValidEmpty() { - try { - Object o = getBeanFactory().getBean("validEmpty"); - assertTrue("validEmpty bean is a TestBean", o instanceof TestBean); - TestBean ve = (TestBean) o; - assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null); - } - catch (BeansException ex) { - ex.printStackTrace(); - fail("Shouldn't throw exception on valid empty"); - } - } - - public void xtestTypeMismatch() { - try { - Object o = getBeanFactory().getBean("typeMismatch"); - fail("Shouldn't succeed with type mismatch"); - } - catch (BeanCreationException wex) { - assertEquals("typeMismatch", wex.getBeanName()); - assertTrue(wex.getCause() instanceof PropertyBatchUpdateException); - PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause(); - // Further tests - assertTrue("Has one error ", ex.getExceptionCount() == 1); - assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null); - assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x")); - } - } - - public void testGrandparentDefinitionFoundInBeanFactory() throws Exception { - TestBean dad = (TestBean) getBeanFactory().getBean("father"); - assertTrue("Dad has correct name", dad.getName().equals("Albert")); - } - - public void testFactorySingleton() throws Exception { - assertTrue(getBeanFactory().isSingleton("&singletonFactory")); - assertTrue(getBeanFactory().isSingleton("singletonFactory")); - TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME)); - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory"); - assertTrue("Singleton references ==", tb == tb2); - assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null); - } - - public void testFactoryPrototype() throws Exception { - assertTrue(getBeanFactory().isSingleton("&prototypeFactory")); - assertFalse(getBeanFactory().isSingleton("prototypeFactory")); - TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME)); - TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory"); - assertTrue("Prototype references !=", tb != tb2); - } - - /** - * Check that we can get the factory bean itself. - * This is only possible if we're dealing with a factory - * @throws Exception - */ - public void testGetFactoryItself() throws Exception { - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue(factory != null); - } - - /** - * Check that afterPropertiesSet gets called on factory - * @throws Exception - */ - public void testFactoryIsInitialized() throws Exception { - TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); - DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); - assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized()); - } - - /** - * It should be illegal to dereference a normal bean - * as a factory - */ - public void testRejectsFactoryGetOnNormalBean() { - try { - getBeanFactory().getBean("&rod"); - fail("Shouldn't permit factory get on normal bean"); - } - catch (BeanIsNotAFactoryException ex) { - // Ok - } - } - - // TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory) - // and rename this class - public void testAliasing() { - BeanFactory bf = getBeanFactory(); - if (!(bf instanceof ConfigurableBeanFactory)) { - return; - } - ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf; - - String alias = "rods alias"; - try { - cbf.getBean(alias); - fail("Shouldn't permit factory get on normal bean"); - } - catch (NoSuchBeanDefinitionException ex) { - // Ok - assertTrue(alias.equals(ex.getBeanName())); - } - - // Create alias - cbf.registerAlias("rod", alias); - Object rod = getBeanFactory().getBean("rod"); - Object aliasRod = getBeanFactory().getBean(alias); - assertTrue(rod == aliasRod); - } - - - public static class TestBeanEditor extends PropertyEditorSupport { - - @Override - public void setAsText(String text) { - TestBean tb = new TestBean(); - StringTokenizer st = new StringTokenizer(text, "_"); - tb.setName(st.nextToken()); - tb.setAge(Integer.parseInt(st.nextToken())); - setValue(tb); - } - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/AbstractListableBeanFactoryTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/AbstractListableBeanFactoryTests.java deleted file mode 100644 index 2b089f8748..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/context/AbstractListableBeanFactoryTests.java +++ /dev/null @@ -1,71 +0,0 @@ -package org.springframework.web.context; - -import org.springframework.beans.TestBean; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.ListableBeanFactory; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests { - - /** Subclasses must initialize this */ - protected ListableBeanFactory getListableBeanFactory() { - BeanFactory bf = getBeanFactory(); - if (!(bf instanceof ListableBeanFactory)) { - throw new IllegalStateException("ListableBeanFactory required"); - } - return (ListableBeanFactory) bf; - } - - /** - * Subclasses can override this. - */ - public void testCount() { - assertCount(13); - } - - protected final void assertCount(int count) { - String[] defnames = getListableBeanFactory().getBeanDefinitionNames(); - assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count); - } - - public void assertTestBeanCount(int count) { - String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false); - assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " + - defNames.length, defNames.length == count); - - int countIncludingFactoryBeans = count + 2; - String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true); - assertTrue("We should have " + countIncludingFactoryBeans + - " beans for class org.springframework.beans.TestBean, not " + names.length, - names.length == countIncludingFactoryBeans); - } - - public void testGetDefinitionsForNoSuchClass() { - String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class); - assertTrue("No string definitions", defnames.length == 0); - } - - /** - * Check that count refers to factory class, not bean class. (We don't know - * what type factories may return, and it may even change over time.) - */ - public void testGetCountForFactoryClass() { - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); - - assertTrue("Should have 2 factories, not " + - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length, - getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2); - } - - public void testContainsBeanDefinition() { - assertTrue(getListableBeanFactory().containsBeanDefinition("rod")); - assertTrue(getListableBeanFactory().containsBeanDefinition("roderick")); - } - -} \ No newline at end of file diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java index a84b83f7ad..15a7e36fea 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/ContextLoaderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,10 +36,10 @@ import javax.servlet.ServletContextListener; import org.junit.Test; import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanDefinitionStoreException; -import org.springframework.beans.factory.LifecycleBean; +import org.springframework.tests.sample.beans.LifecycleBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextException; diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/ResourceBundleMessageSourceTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/ResourceBundleMessageSourceTests.java deleted file mode 100644 index b9710dd798..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/context/ResourceBundleMessageSourceTests.java +++ /dev/null @@ -1,281 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.web.context; - -import java.util.Date; -import java.util.Locale; - -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.MessageSource; -import org.springframework.context.NoSuchMessageException; -import org.springframework.context.support.AbstractMessageSource; -import org.springframework.mock.web.test.MockServletContext; -import org.springframework.ui.context.Theme; -import org.springframework.ui.context.ThemeSource; -import org.springframework.web.context.support.StaticWebApplicationContext; -import org.springframework.web.context.support.XmlWebApplicationContext; -import org.springframework.web.servlet.theme.AbstractThemeResolver; - -/** - * Creates a WebApplicationContext that points to a "web.xml" file that - * contains the entry for what file to use for the applicationContext - * (file "org/springframework/web/context/WEB-INF/applicationContext.xml"). - * That file then has an entry for a bean called "messageSource". - * Whatever the basename property is set to for this bean is what the name of - * a properties file in the classpath must be (in our case the name is - * "messages" - note no package names). - * Thus the catalog filename will be in the root of where the classes are compiled - * to and will be called "messages_XX_YY.properties" where "XX" and "YY" are the - * language and country codes known by the ResourceBundle class. - * - *

NOTE: The main method of this class is the "createWebApplicationContext(...)" method, - * and it was copied from org.springframework.web.context.XmlWebApplicationContextTests. - * - * @author Rod Johnson - * @author Jean-Pierre Pawlak - */ -public class ResourceBundleMessageSourceTests extends AbstractApplicationContextTests { - - /** - * We use ticket WAR root for file structure. - * We don't attempt to read web.xml. - */ - public static final String WAR_ROOT = "/org/springframework/web/context"; - - private ConfigurableWebApplicationContext root; - - private MessageSource themeMsgSource; - - @Override - protected ConfigurableApplicationContext createContext() throws Exception { - root = new XmlWebApplicationContext(); - MockServletContext sc = new MockServletContext(); - root.setServletContext(sc); - root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"}); - root.refresh(); - - ConfigurableWebApplicationContext wac = new XmlWebApplicationContext(); - wac.setParent(root); - wac.setServletContext(sc); - wac.setNamespace("test-servlet"); - wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"}); - wac.refresh(); - - Theme theme = ((ThemeSource) wac).getTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME); - assertNotNull(theme); - assertTrue("Theme name has to be the default theme name", AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME.equals(theme.getName())); - themeMsgSource = theme.getMessageSource(); - assertNotNull(themeMsgSource); - return wac; - } - - @Override - public void testCount() { - assertTrue("should have 14 beans, not " + - this.applicationContext.getBeanDefinitionCount(), - this.applicationContext.getBeanDefinitionCount() == 14); - } - - /** - * Overridden as we can't trust superclass method. - * @see org.springframework.context.AbstractApplicationContextTests#testEvents() - */ - @Override - public void testEvents() throws Exception { - // Do nothing - } - - public void testRootMessageSourceWithUseCodeAsDefaultMessage() throws NoSuchMessageException { - AbstractMessageSource messageSource = (AbstractMessageSource) root.getBean("messageSource"); - messageSource.setUseCodeAsDefaultMessage(true); - - assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault())); - assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault())); - - try { - applicationContext.getMessage("code0", null, Locale.getDefault()); - fail("looking for code0 should throw a NoSuchMessageException"); - } - catch (NoSuchMessageException ex) { - // that's how it should be - } - } - - /** - * @see org.springframework.context.support.AbstractMessageSource for more details. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files. - */ - public void testGetMessageWithDefaultPassedInAndFoundInMsgCatalog() { - assertTrue("valid msg from resourcebundle with default msg passed in returned default msg. Expected msg from catalog.", - getApplicationContext().getMessage("message.format.example2", null, "This is a default msg if not found in msg.cat.", Locale.US - ) - .equals("This is a test message in the message catalog with no args.")); - // getApplicationContext().getTheme("theme").getMessageSource().getMessage() - } - - /** - * @see org.springframework.context.support.AbstractMessageSource for more details. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files. - */ - public void testGetMessageWithDefaultPassedInAndNotFoundInMsgCatalog() { - assertTrue("bogus msg from resourcebundle with default msg passed in returned default msg", - getApplicationContext().getMessage("bogus.message", null, "This is a default msg if not found in msg.cat.", Locale.UK - ) - .equals("This is a default msg if not found in msg.cat.")); - } - - /** - * The underlying implementation uses a hashMap to cache messageFormats - * once a message has been asked for. This test is an attempt to - * make sure the cache is being used properly. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files. - * @see org.springframework.context.support.AbstractMessageSource for more details. - */ - public void testGetMessageWithMessageAlreadyLookedFor() throws Exception { - Object[] arguments = { - new Integer(7), new Date(System.currentTimeMillis()), - "a disturbance in the Force" - }; - - // The first time searching, we don't care about for this test - getApplicationContext().getMessage("message.format.example1", arguments, Locale.US); - - // Now msg better be as expected - assertTrue("2nd search within MsgFormat cache returned expected message for Locale.US", - getApplicationContext().getMessage("message.format.example1", arguments, Locale.US - ) - .indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1); - - Object[] newArguments = { - new Integer(8), new Date(System.currentTimeMillis()), - "a disturbance in the Force" - }; - - // Now msg better be as expected even with different args - assertTrue("2nd search within MsgFormat cache with different args returned expected message for Locale.US", - getApplicationContext().getMessage("message.format.example1", newArguments, Locale.US - ) - .indexOf("there was \"a disturbance in the Force\" on planet 8.") != -1); - } - - /** - * @see org.springframework.context.support.AbstractMessageSource for more details. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files. - * Example taken from the javadocs for the java.text.MessageFormat class - */ - public void testGetMessageWithNoDefaultPassedInAndFoundInMsgCatalog() throws Exception { - Object[] arguments = { - new Integer(7), new Date(System.currentTimeMillis()), - "a disturbance in the Force" - }; - - /* - Try with Locale.US - Since the msg has a time value in it, we will use String.indexOf(...) - to just look for a substring without the time. This is because it is - possible that by the time we store a time variable in this method - and the time the ResourceBundleMessageSource resolves the msg the - minutes of the time might not be the same. - */ - assertTrue("msg from resourcebundle for Locale.US substituting args for placeholders is as expected", - getApplicationContext().getMessage("message.format.example1", arguments, Locale.US - ) - .indexOf("there was \"a disturbance in the Force\" on planet 7.") != -1); - - // Try with Locale.UK - assertTrue("msg from resourcebundle for Locale.UK substituting args for placeholders is as expected", - getApplicationContext().getMessage("message.format.example1", arguments, Locale.UK - ) - .indexOf("there was \"a disturbance in the Force\" on station number 7.") != -1); - - // Try with Locale.US - different test msg that requires no args - assertTrue("msg from resourcebundle that requires no args for Locale.US is as expected", - getApplicationContext().getMessage("message.format.example2", null, Locale.US) - .equals("This is a test message in the message catalog with no args.")); - } - - /** - * @see org.springframework.context.support.AbstractMessageSource for more details. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/messagesXXX.properties" files. - */ - public void testGetMessageWithNoDefaultPassedInAndNotFoundInMsgCatalog() { - // Expecting an exception - try { - getApplicationContext().getMessage("bogus.message", null, Locale.UK); - fail("bogus msg from resourcebundle without default msg should have thrown exception"); - } - catch (NoSuchMessageException tExcept) { - assertTrue("bogus msg from resourcebundle without default msg threw expected exception", - true); - } - } - - public void testGetMultipleBasenamesForMessageSource() throws NoSuchMessageException { - assertEquals("message1", getApplicationContext().getMessage("code1", null, Locale.UK)); - assertEquals("message2", getApplicationContext().getMessage("code2", null, Locale.UK)); - assertEquals("message3", getApplicationContext().getMessage("code3", null, Locale.UK)); - } - - /** - * @see org.springframework.context.support.AbstractMessageSource for more details. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/themeXXX.properties" files. - */ - public void testGetMessageWithDefaultPassedInAndFoundInThemeCatalog() { - // Try with Locale.US - String msg = getThemeMessage("theme.example1", null, "This is a default theme msg if not found in theme cat.", Locale.US); - assertTrue("valid msg from theme resourcebundle with default msg passed in returned default msg. Expected msg from catalog. Received: " + msg, - msg.equals("This is a test message in the theme message catalog.")); - // Try with Locale.UK - msg = getThemeMessage("theme.example1", null, "This is a default theme msg if not found in theme cat.", Locale.UK); - assertTrue("valid msg from theme resourcebundle with default msg passed in returned default msg. Expected msg from catalog.", - msg.equals("This is a test message in the theme message catalog with no args.")); - } - - /** - * @see org.springframework.context.support.AbstractMessageSource for more details. - * NOTE: Messages are contained within the "test/org/springframework/web/context/WEB-INF/themeXXX.properties" files. - */ - public void testGetMessageWithDefaultPassedInAndNotFoundInThemeCatalog() { - assertTrue("bogus msg from theme resourcebundle with default msg passed in returned default msg", - getThemeMessage("bogus.message", null, "This is a default msg if not found in theme cat.", Locale.UK - ) - .equals("This is a default msg if not found in theme cat.")); - } - - public void testThemeSourceNesting() throws NoSuchMessageException { - String overriddenMsg = getThemeMessage("theme.example2", null, null, Locale.UK); - MessageSource ms = ((ThemeSource) root).getTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME).getMessageSource(); - String originalMsg = ms.getMessage("theme.example2", null, Locale.UK); - assertTrue("correct overridden msg", "test-message2".equals(overriddenMsg)); - assertTrue("correct original msg", "message2".equals(originalMsg)); - } - - public void testThemeSourceNestingWithParentDefault() throws NoSuchMessageException { - StaticWebApplicationContext leaf = new StaticWebApplicationContext(); - leaf.setParent(getApplicationContext()); - leaf.refresh(); - assertNotNull("theme still found", leaf.getTheme("theme")); - MessageSource ms = leaf.getTheme("theme").getMessageSource(); - String msg = ms.getMessage("theme.example2", null, null, Locale.UK); - assertEquals("correct overridden msg", "test-message2", msg); - } - - private String getThemeMessage(String code, Object args[], String defaultMessage, Locale locale) { - return themeMsgSource.getMessage(code, args, defaultMessage, locale); - } - -} diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml index e25d331737..6080b76eb0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml +++ b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/ContextLoaderTests-acc-context.xml @@ -3,7 +3,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> - + diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/applicationContext.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/applicationContext.xml index 3a59552ded..b4d7c366f2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/applicationContext.xml +++ b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/applicationContext.xml @@ -9,7 +9,7 @@ - + - + dummy @@ -45,7 +45,7 @@ Tests of lifecycle callbacks --> + class="org.springframework.tests.sample.beans.MustBeInitialized"> 31 - + - + Kerry 34 - + typeMismatch 34x @@ -31,20 +31,20 @@ + class="org.springframework.tests.sample.beans.factory.DummyFactory"> + class="org.springframework.tests.sample.beans.factory.DummyFactory"> false - + listenerVeto 66 - + diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/contextInclude.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/contextInclude.xml index 2e4938383b..5f178d50eb 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/contextInclude.xml +++ b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/contextInclude.xml @@ -1,6 +1,6 @@ - + yetanotherdummy diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml index 7da590d1f2..eb7bf0f6ea 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml +++ b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml @@ -3,12 +3,12 @@ - + - + diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/test-servlet.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/test-servlet.xml index 4002703b21..85885f238d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/test-servlet.xml +++ b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/test-servlet.xml @@ -15,7 +15,7 @@ - + Rod 31 @@ -28,32 +28,32 @@ 31 - + - + Kerry 34 - + typeMismatch 34x - + - + false - + listenerVeto 66 - + diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/testNamespace.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/testNamespace.xml index dd10e5fcab..89c42365d4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/testNamespace.xml +++ b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/testNamespace.xml @@ -3,12 +3,12 @@ - + Rod 31 - + Kerry 34 diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java index 3423fd8e88..4dce1e9fac 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/XmlWebApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,12 +21,13 @@ import java.util.Locale; import javax.servlet.ServletException; import org.springframework.beans.BeansException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.AbstractApplicationContextTests; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.NoSuchMessageException; import org.springframework.context.TestListener; diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java index 9e0784f251..07823327e6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import java.util.Set; import org.junit.Test; import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.config.ConstructorArgumentValues; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java index 1e44c2f815..b5b4f0206f 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/ComplexWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -131,7 +131,7 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext { registerSingleton("viewResolver2", InternalResourceViewResolver.class, pvs); pvs = new MutablePropertyValues(); - pvs.add("commandClass", "org.springframework.beans.TestBean"); + pvs.add("commandClass", "org.springframework.tests.sample.beans.TestBean"); pvs.add("formView", "form"); registerSingleton("formHandler", SimpleFormController.class, pvs); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index 287ea086eb..147875e4ca 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import junit.framework.TestCase; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.core.env.ConfigurableEnvironment; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java index dbbb25fe5a..ce525f937d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/SimpleWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,7 +50,7 @@ public class SimpleWebApplicationContext extends StaticWebApplicationContext { @Override public void refresh() throws BeansException { MutablePropertyValues pvs = new MutablePropertyValues(); - pvs.add("commandClass", "org.springframework.beans.TestBean"); + pvs.add("commandClass", "org.springframework.tests.sample.beans.TestBean"); pvs.add("formView", "form"); registerSingleton("/form.do", SimpleFormController.class, pvs); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java index 1c270ae571..40f10ea7e6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import java.util.List; import org.junit.Before; import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.convert.converter.Converter; import org.springframework.core.io.FileSystemResourceLoader; import org.springframework.format.FormatterRegistry; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CancellableFormControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CancellableFormControllerTests.java index ea1b09ed21..ff3ebd962f 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CancellableFormControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CancellableFormControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.validation.BindException; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CommandControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CommandControllerTests.java index 4749c85df7..da2da2e174 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CommandControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/CommandControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.mock.web.test.MockHttpServletRequest; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/FormControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/FormControllerTests.java index d62174ab26..3c40caacd6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/FormControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/FormControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,8 +28,8 @@ import javax.servlet.http.HttpServletResponse; import junit.framework.TestCase; -import org.springframework.beans.IndexedTestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.support.StaticApplicationContext; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WizardFormControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WizardFormControllerTests.java index 705ac4ea81..1d37caff85 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WizardFormControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/WizardFormControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import javax.servlet.http.HttpSession; import junit.framework.TestCase; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.util.ObjectUtils; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java index 05e0f3c2a5..bbfa7e2990 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -59,12 +59,12 @@ import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreato import org.springframework.aop.interceptor.SimpleTraceInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.BeansException; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.GenericBean; -import org.springframework.beans.ITestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.GenericBean; +import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -329,7 +329,7 @@ public class ServletAnnotationControllerTests { request.addParameter("testBeanSet", new String[] {"1", "2"}); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); - assertEquals("[1, 2]-org.springframework.beans.TestBean", response.getContentAsString()); + assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java index 32ac81d668..33307032e5 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ExtendedServletRequestDataBinderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.WebDataBinder; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java index 54d187f91a..e0a515c3b0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ModelAndViewResolverMethodReturnValueHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import java.util.List; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.MethodParameter; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.ui.ExtendedModelMap; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java index 450315e6de..caa7fbcea6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,7 +44,7 @@ import javax.validation.Valid; import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.core.MethodParameter; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java index 3d77c29237..a15466aabc 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,13 +36,13 @@ import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.http.client.FreePortScanner; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; import org.springframework.stereotype.Controller; +import org.springframework.tests.web.FreePortScanner; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SerlvetModelAttributeMethodProcessorTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SerlvetModelAttributeMethodProcessorTests.java index 21ef1b1959..26e95d0c33 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SerlvetModelAttributeMethodProcessorTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/SerlvetModelAttributeMethodProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.MethodParameter; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.mock.web.test.MockHttpServletRequest; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java index e42ccb2969..6c5c7327e0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,10 +64,10 @@ import org.junit.Test; import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.aop.interceptor.SimpleTraceInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; -import org.springframework.beans.DerivedTestBean; -import org.springframework.beans.GenericBean; -import org.springframework.beans.ITestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.GenericBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -283,7 +283,7 @@ public class ServletAnnotationControllerHandlerMethodTests extends AbstractServl request.addParameter("testBeanSet", new String[] {"1", "2"}); MockHttpServletResponse response = new MockHttpServletResponse(); getServlet().service(request, response); - assertEquals("[1, 2]-org.springframework.beans.TestBean", response.getContentAsString()); + assertEquals("[1, 2]-org.springframework.tests.sample.beans.TestBean", response.getContentAsString()); } @Test diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java index 18ae25f7e0..64de09b05a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,7 @@ import javax.servlet.http.HttpSession; import junit.framework.TestCase; import org.springframework.beans.FatalBeanException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ApplicationContextException; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java index 852c95fd8a..fe492bab94 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultHandlerExceptionResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,7 @@ import java.util.Collections; import org.junit.Before; import org.junit.Test; import org.springframework.beans.ConversionNotSupportedException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.TypeMismatchException; import org.springframework.core.MethodParameter; import org.springframework.http.MediaType; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java index 8a0518c560..cb7b41e9d6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/RedirectAttributesModelMapTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.convert.converter.Converter; import org.springframework.format.support.DefaultFormattingConversionService; import org.springframework.format.support.FormattingConversionService; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java index 9876450099..4af3a47cde 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/BindTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,9 @@ import javax.servlet.jsp.JspException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.IndexedTestBean; -import org.springframework.beans.NestedTestBean; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.IndexedTestBean; +import org.springframework.tests.sample.beans.NestedTestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractFormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractFormTagTests.java index e380397ed4..f1b27c493e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractFormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/AbstractFormTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.web.servlet.tags.form; import javax.servlet.jsp.JspException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockPageContext; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java index 1d299c222a..b471438f1e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ButtonTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ import java.io.Writer; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Rossen Stoyanchev diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java index 70aae8f0e4..657aab3c24 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,9 +32,9 @@ import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; -import org.springframework.beans.Colour; -import org.springframework.beans.Pet; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.Colour; +import org.springframework.tests.sample.beans.Pet; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java index 055580d5a3..9ffeefbf2c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/CheckboxesTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,9 +36,9 @@ import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; -import org.springframework.beans.Colour; -import org.springframework.beans.Pet; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.Colour; +import org.springframework.tests.sample.beans.Pet; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.format.Formatter; import org.springframework.format.support.FormattingConversionService; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java index 6e11e06331..a36012bb60 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/ErrorsTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockBodyContent; import org.springframework.mock.web.test.MockPageContext; import org.springframework.validation.BeanPropertyBindingResult; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java index 60beaccb6d..613196224c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/HiddenInputTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.web.servlet.tags.form; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BeanPropertyBindingResult; /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java index 7ca869480b..52ba57f9f2 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/InputTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import java.io.Writer; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.web.servlet.support.BindStatus; import org.springframework.web.servlet.tags.BindTag; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java index 5654062ff7..23b9016c74 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/LabelTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.web.servlet.tags.form; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockPageContext; import org.springframework.web.servlet.tags.NestedPathTag; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java index 7144652045..aa853b99bf 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagEnumTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,8 +19,8 @@ package org.springframework.web.servlet.tags.form; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.CustomEnum; -import org.springframework.beans.GenericBean; +import org.springframework.tests.sample.beans.CustomEnum; +import org.springframework.tests.sample.beans.GenericBean; import org.springframework.web.servlet.support.BindStatus; /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java index 3acacbb8b8..1d554f5ef4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ import java.util.List; import javax.servlet.jsp.tagext.BodyTag; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.Colour; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.Colour; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.StringArrayPropertyEditor; import org.springframework.mock.web.test.MockBodyContent; import org.springframework.mock.web.test.MockHttpServletRequest; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java index 92290c23cc..964e2d412f 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/OptionsTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockPageContext; import org.springframework.validation.BeanPropertyBindingResult; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java index bcb5eeebaf..42190d39f8 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,8 +27,8 @@ import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; -import org.springframework.beans.Pet; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.Pet; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java index 93f6a04080..702e790c9a 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/RadioButtonsTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,9 +34,9 @@ import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.SAXReader; -import org.springframework.beans.Colour; -import org.springframework.beans.Pet; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.Colour; +import org.springframework.tests.sample.beans.Pet; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindingResult; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java index 8786a091fa..8dfc3e3e0c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/SelectTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.format.Formatter; import org.springframework.format.support.FormattingConversionService; @@ -337,7 +337,7 @@ public class SelectTagTests extends AbstractFormTagTests { catch (JspException expected) { String message = expected.getMessage(); assertTrue(message.indexOf("items") > -1); - assertTrue(message.indexOf("org.springframework.beans.TestBean") > -1); + assertTrue(message.indexOf("org.springframework.tests.sample.beans.TestBean") > -1); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TestBeanWithRealCountry.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TestBeanWithRealCountry.java index e1a6a313d0..4ea337bbd7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TestBeanWithRealCountry.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TestBeanWithRealCountry.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ package org.springframework.web.servlet.tags.form; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java index 4684b5b659..bfa9bd8dbe 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/TextareaTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,7 @@ package org.springframework.web.servlet.tags.form; import javax.servlet.jsp.tagext.Tag; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.validation.BeanPropertyBindingResult; /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java index d252550f18..d3c45fb249 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/RedirectViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ import junit.framework.AssertionFailedError; import org.easymock.EasyMock; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.http.HttpStatus; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ViewResolverTests.java index fadc606373..3836559480 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ import org.junit.Test; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.context.ApplicationContextException; import org.springframework.core.io.ClassPathResource; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java index d3af0683f4..17a4c4f50c 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,7 +31,7 @@ import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.mock.web.test.MockHttpServletRequest; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java index 3ed4276550..04c8497df3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityMacroTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.apache.velocity.Template; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.context.Context; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityRenderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityRenderTests.java index ff477a97f4..b07a53716e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityRenderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityRenderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.springframework.beans.TestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletContext; diff --git a/spring-webmvc/src/test/resources/org/springframework/web/context/WEB-INF/sessionContext.xml b/spring-webmvc/src/test/resources/org/springframework/web/context/WEB-INF/sessionContext.xml index 7da590d1f2..eb7bf0f6ea 100644 --- a/spring-webmvc/src/test/resources/org/springframework/web/context/WEB-INF/sessionContext.xml +++ b/spring-webmvc/src/test/resources/org/springframework/web/context/WEB-INF/sessionContext.xml @@ -3,12 +3,12 @@ - + - + diff --git a/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests-context.xml b/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests-context.xml index 4be55f0ea7..49e480a664 100644 --- a/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests-context.xml +++ b/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests-context.xml @@ -11,19 +11,19 @@ - + - + - + - + diff --git a/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java b/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java index 7472033a36..8a3c178627 100644 --- a/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java +++ b/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,20 +17,22 @@ package org.springframework.aop.config; import static java.lang.String.format; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; -import test.beans.ITestBean; -import test.beans.TestBean; -import test.util.SerializationTestUtils; - import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; import org.springframework.context.ApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpSession; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ClassUtils; +import org.springframework.util.SerializationTestUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.support.XmlWebApplicationContext; diff --git a/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests-context.xml b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests-context.xml index 4f9a0361c0..c5b04a53df 100644 --- a/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests-context.xml +++ b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests-context.xml @@ -22,20 +22,20 @@ 9 false - + 11 true - + true - - + + @@ -71,37 +71,37 @@ - + - - - - - + + + + + - test.beans.ITestBean.getName + org.springframework.tests.sample.beans.ITestBean.getName - + - + 4 - + - + - + diff --git a/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java index 74ff0825e6..d2fbb3e1e0 100644 --- a/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java +++ b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,9 @@ package org.springframework.aop.framework.autoproxy; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import java.io.IOException; import java.lang.reflect.Method; @@ -30,16 +32,13 @@ import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.tests.aop.advice.CountingBeforeAdvice; +import org.springframework.tests.aop.advice.MethodCounter; +import org.springframework.tests.aop.interceptor.NopInterceptor; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.NoTransactionException; -import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.interceptor.TransactionInterceptor; -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -import org.springframework.transaction.support.DefaultTransactionStatus; - -import test.advice.CountingBeforeAdvice; -import test.advice.MethodCounter; -import test.beans.ITestBean; -import test.interceptor.NopInterceptor; /** * Integration tests for auto proxy creation by advisor recognition working in @@ -316,43 +315,3 @@ class Rollback { } } - - -@SuppressWarnings("serial") -class CallCountingTransactionManager extends AbstractPlatformTransactionManager { - - public TransactionDefinition lastDefinition; - public int begun; - public int commits; - public int rollbacks; - public int inflight; - - @Override - protected Object doGetTransaction() { - return new Object(); - } - - @Override - protected void doBegin(Object transaction, TransactionDefinition definition) { - this.lastDefinition = definition; - ++begun; - ++inflight; - } - - @Override - protected void doCommit(DefaultTransactionStatus status) { - ++commits; - --inflight; - } - - @Override - protected void doRollback(DefaultTransactionStatus status) { - ++rollbacks; - --inflight; - } - - public void clear() { - begun = commits = rollbacks = inflight = 0; - } - -} diff --git a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java index fae32ac8f5..aca10a3fb2 100644 --- a/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java +++ b/src/test/java/org/springframework/scheduling/annotation/ScheduledAndTransactionalAnnotationIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,18 @@ package org.springframework.scheduling.annotation; +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.replay; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.greaterThan; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; - import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -31,16 +38,11 @@ import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.stereotype.Repository; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.Transactional; -import static org.easymock.EasyMock.*; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - /** * Integration tests cornering bug SPR-8651, which revealed that @Scheduled methods may * not work well with beans that have already been proxied for other reasons such diff --git a/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java b/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java deleted file mode 100644 index ff94b0dd22..0000000000 --- a/src/test/java/org/springframework/transaction/CallCountingTransactionManager.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.transaction; - - - -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -import org.springframework.transaction.support.DefaultTransactionStatus; - -/** - * @author Rod Johnson - * @author Juergen Hoeller - */ -@SuppressWarnings("serial") -public class CallCountingTransactionManager extends AbstractPlatformTransactionManager { - - public TransactionDefinition lastDefinition; - public int begun; - public int commits; - public int rollbacks; - public int inflight; - - @Override - protected Object doGetTransaction() { - return new Object(); - } - - @Override - protected void doBegin(Object transaction, TransactionDefinition definition) { - this.lastDefinition = definition; - ++begun; - ++inflight; - } - - @Override - protected void doCommit(DefaultTransactionStatus status) { - ++commits; - --inflight; - } - - @Override - protected void doRollback(DefaultTransactionStatus status) { - ++rollbacks; - --inflight; - } - - public void clear() { - begun = commits = rollbacks = inflight = 0; - } - -} diff --git a/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java b/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java index d4f33e642e..54511e7e7b 100644 --- a/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java +++ b/src/test/java/org/springframework/transaction/annotation/EnableTransactionManagementIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.stereotype.Repository; -import org.springframework.transaction.CallCountingTransactionManager; +import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.interceptor.BeanFactoryTransactionAttributeSourceAdvisor; diff --git a/src/test/java/test/advice/CountingAfterReturningAdvice.java b/src/test/java/test/advice/CountingAfterReturningAdvice.java deleted file mode 100644 index a8a3a01e3a..0000000000 --- a/src/test/java/test/advice/CountingAfterReturningAdvice.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.advice; - -import java.lang.reflect.Method; - -import org.springframework.aop.AfterReturningAdvice; - -/** - * Simple before advice example that we can use for counting checks. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class CountingAfterReturningAdvice extends MethodCounter implements AfterReturningAdvice { - - @Override - public void afterReturning(Object o, Method m, Object[] args, Object target) throws Throwable { - count(m); - } - -} \ No newline at end of file diff --git a/src/test/java/test/advice/CountingBeforeAdvice.java b/src/test/java/test/advice/CountingBeforeAdvice.java deleted file mode 100644 index 5aa37b61e1..0000000000 --- a/src/test/java/test/advice/CountingBeforeAdvice.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.advice; - -import java.lang.reflect.Method; - -import org.springframework.aop.MethodBeforeAdvice; - -/** - * Simple before advice example that we can use for counting checks. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class CountingBeforeAdvice extends MethodCounter implements MethodBeforeAdvice { - - @Override - public void before(Method m, Object[] args, Object target) throws Throwable { - count(m); - } - -} diff --git a/src/test/java/test/beans/Colour.java b/src/test/java/test/beans/Colour.java deleted file mode 100644 index 533d0df36e..0000000000 --- a/src/test/java/test/beans/Colour.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import org.springframework.core.enums.ShortCodedLabeledEnum; - -/** - * @author Rob Harrop - */ -@SuppressWarnings("serial") -public class Colour extends ShortCodedLabeledEnum { - - public static final Colour RED = new Colour(0, "RED"); - public static final Colour BLUE = new Colour(1, "BLUE"); - public static final Colour GREEN = new Colour(2, "GREEN"); - public static final Colour PURPLE = new Colour(3, "PURPLE"); - - private Colour(int code, String label) { - super(code, label); - } - -} diff --git a/src/test/java/test/beans/INestedTestBean.java b/src/test/java/test/beans/INestedTestBean.java deleted file mode 100644 index 2b63908467..0000000000 --- a/src/test/java/test/beans/INestedTestBean.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -public interface INestedTestBean { - - public String getCompany(); - -} diff --git a/src/test/java/test/beans/IOther.java b/src/test/java/test/beans/IOther.java deleted file mode 100644 index f0c6aa7bf4..0000000000 --- a/src/test/java/test/beans/IOther.java +++ /dev/null @@ -1,24 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -public interface IOther { - - void absquatulate(); - -} diff --git a/src/test/java/test/beans/ITestBean.java b/src/test/java/test/beans/ITestBean.java deleted file mode 100644 index 0434b6ad11..0000000000 --- a/src/test/java/test/beans/ITestBean.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.io.IOException; - -/** - * Interface used for {@link TestBean}. - * - *

Two methods are the same as on Person, but if this - * extends person it breaks quite a few tests.. - * - * @author Rod Johnson - * @author Juergen Hoeller - */ -public interface ITestBean { - - int getAge(); - - void setAge(int age); - - String getName(); - - void setName(String name); - - ITestBean getSpouse(); - - void setSpouse(ITestBean spouse); - - ITestBean[] getSpouses(); - - String[] getStringArray(); - - void setStringArray(String[] stringArray); - - /** - * Throws a given (non-null) exception. - */ - void exceptional(Throwable t) throws Throwable; - - Object returnsThis(); - - INestedTestBean getDoctor(); - - INestedTestBean getLawyer(); - - IndexedTestBean getNestedIndexedBean(); - - /** - * Increment the age by one. - * @return the previous age - */ - int haveBirthday(); - - void unreliableFileOperation() throws IOException; - -} diff --git a/src/test/java/test/beans/IndexedTestBean.java b/src/test/java/test/beans/IndexedTestBean.java deleted file mode 100644 index 160681e556..0000000000 --- a/src/test/java/test/beans/IndexedTestBean.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; - -/** - * @author Juergen Hoeller - * @since 11.11.2003 - */ -public class IndexedTestBean { - - private TestBean[] array; - - private Collection collection; - - private List list; - - private Set set; - - private SortedSet sortedSet; - - private Map map; - - private SortedMap sortedMap; - - - public IndexedTestBean() { - this(true); - } - - public IndexedTestBean(boolean populate) { - if (populate) { - populate(); - } - } - - public void populate() { - TestBean tb0 = new TestBean("name0", 0); - TestBean tb1 = new TestBean("name1", 0); - TestBean tb2 = new TestBean("name2", 0); - TestBean tb3 = new TestBean("name3", 0); - TestBean tb4 = new TestBean("name4", 0); - TestBean tb5 = new TestBean("name5", 0); - TestBean tb6 = new TestBean("name6", 0); - TestBean tb7 = new TestBean("name7", 0); - TestBean tbX = new TestBean("nameX", 0); - TestBean tbY = new TestBean("nameY", 0); - this.array = new TestBean[] {tb0, tb1}; - this.list = new ArrayList(); - this.list.add(tb2); - this.list.add(tb3); - this.set = new TreeSet(); - this.set.add(tb6); - this.set.add(tb7); - this.map = new HashMap(); - this.map.put("key1", tb4); - this.map.put("key2", tb5); - this.map.put("key.3", tb5); - List list = new ArrayList(); - list.add(tbX); - list.add(tbY); - this.map.put("key4", list); - } - - - public TestBean[] getArray() { - return array; - } - - public void setArray(TestBean[] array) { - this.array = array; - } - - public Collection getCollection() { - return collection; - } - - public void setCollection(Collection collection) { - this.collection = collection; - } - - public List getList() { - return list; - } - - public void setList(List list) { - this.list = list; - } - - public Set getSet() { - return set; - } - - public void setSet(Set set) { - this.set = set; - } - - public SortedSet getSortedSet() { - return sortedSet; - } - - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } - - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - public SortedMap getSortedMap() { - return sortedMap; - } - - public void setSortedMap(SortedMap sortedMap) { - this.sortedMap = sortedMap; - } - -} diff --git a/src/test/java/test/beans/NestedTestBean.java b/src/test/java/test/beans/NestedTestBean.java deleted file mode 100644 index c6d1acd27b..0000000000 --- a/src/test/java/test/beans/NestedTestBean.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -/** - * Simple nested test bean used for testing bean factories, AOP framework etc. - * - * @author Trevor D. Cook - * @since 30.09.2003 - */ -public class NestedTestBean implements INestedTestBean { - - private String company = ""; - - public NestedTestBean() { - } - - public NestedTestBean(String company) { - setCompany(company); - } - - public void setCompany(String company) { - this.company = (company != null ? company : ""); - } - - @Override - public String getCompany() { - return company; - } - - public boolean equals(Object obj) { - if (!(obj instanceof NestedTestBean)) { - return false; - } - NestedTestBean ntb = (NestedTestBean) obj; - return this.company.equals(ntb.company); - } - - public int hashCode() { - return this.company.hashCode(); - } - - public String toString() { - return "NestedTestBean: " + this.company; - } - -} diff --git a/src/test/java/test/beans/Pet.java b/src/test/java/test/beans/Pet.java deleted file mode 100644 index f81ac4f092..0000000000 --- a/src/test/java/test/beans/Pet.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -/** - * @author Rob Harrop - * @since 2.0 - */ -public class Pet { - - private String name; - - public Pet(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public String toString() { - return getName(); - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - final Pet pet = (Pet) o; - - if (name != null ? !name.equals(pet.name) : pet.name != null) return false; - - return true; - } - - public int hashCode() { - return (name != null ? name.hashCode() : 0); - } - -} diff --git a/src/test/java/test/beans/TestBean.java b/src/test/java/test/beans/TestBean.java deleted file mode 100644 index b76f12a75e..0000000000 --- a/src/test/java/test/beans/TestBean.java +++ /dev/null @@ -1,457 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.beans; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanNameAware; -import org.springframework.util.ObjectUtils; - -/** - * Simple test bean used for testing bean factories, the AOP framework etc. - * - * @author Rod Johnson - * @author Juergen Hoeller - * @since 15 April 2001 - */ -public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable { - - private String beanName; - - private String country; - - private BeanFactory beanFactory; - - private boolean postProcessed; - - private String name; - - private String sex; - - private int age; - - private boolean jedi; - - private ITestBean[] spouses; - - private String touchy; - - private String[] stringArray; - - private Integer[] someIntegerArray; - - private Date date = new Date(); - - private Float myFloat = new Float(0.0); - - private Collection friends = new LinkedList(); - - private Set someSet = new HashSet(); - - private Map someMap = new HashMap(); - - private List someList = new ArrayList(); - - private Properties someProperties = new Properties(); - - private INestedTestBean doctor = new NestedTestBean(); - - private INestedTestBean lawyer = new NestedTestBean(); - - private IndexedTestBean nestedIndexedBean; - - private boolean destroyed; - - private Number someNumber; - - private Colour favouriteColour; - - private Boolean someBoolean; - - private List otherColours; - - private List pets; - - - public TestBean() { - } - - public TestBean(String name) { - this.name = name; - } - - public TestBean(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - public TestBean(String name, int age) { - this.name = name; - this.age = age; - } - - public TestBean(ITestBean spouse, Properties someProperties) { - this.spouses = new ITestBean[] {spouse}; - this.someProperties = someProperties; - } - - public TestBean(List someList) { - this.someList = someList; - } - - public TestBean(Set someSet) { - this.someSet = someSet; - } - - public TestBean(Map someMap) { - this.someMap = someMap; - } - - public TestBean(Properties someProperties) { - this.someProperties = someProperties; - } - - - @Override - public void setBeanName(String beanName) { - this.beanName = beanName; - } - - public String getBeanName() { - return beanName; - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) { - this.beanFactory = beanFactory; - } - - public BeanFactory getBeanFactory() { - return beanFactory; - } - - public void setPostProcessed(boolean postProcessed) { - this.postProcessed = postProcessed; - } - - public boolean isPostProcessed() { - return postProcessed; - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String name) { - this.name = name; - } - - public String getSex() { - return sex; - } - - public void setSex(String sex) { - this.sex = sex; - if (this.name == null) { - this.name = sex; - } - } - - @Override - public int getAge() { - return age; - } - - @Override - public void setAge(int age) { - this.age = age; - } - - public boolean isJedi() { - return jedi; - } - - public void setJedi(boolean jedi) { - this.jedi = jedi; - } - - @Override - public ITestBean getSpouse() { - return (spouses != null ? spouses[0] : null); - } - - @Override - public void setSpouse(ITestBean spouse) { - this.spouses = new ITestBean[] {spouse}; - } - - @Override - public ITestBean[] getSpouses() { - return spouses; - } - - public String getTouchy() { - return touchy; - } - - public void setTouchy(String touchy) throws Exception { - if (touchy.indexOf('.') != -1) { - throw new Exception("Can't contain a ."); - } - if (touchy.indexOf(',') != -1) { - throw new NumberFormatException("Number format exception: contains a ,"); - } - this.touchy = touchy; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - @Override - public String[] getStringArray() { - return stringArray; - } - - @Override - public void setStringArray(String[] stringArray) { - this.stringArray = stringArray; - } - - public Integer[] getSomeIntegerArray() { - return someIntegerArray; - } - - public void setSomeIntegerArray(Integer[] someIntegerArray) { - this.someIntegerArray = someIntegerArray; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Float getMyFloat() { - return myFloat; - } - - public void setMyFloat(Float myFloat) { - this.myFloat = myFloat; - } - - public Collection getFriends() { - return friends; - } - - public void setFriends(Collection friends) { - this.friends = friends; - } - - public Set getSomeSet() { - return someSet; - } - - public void setSomeSet(Set someSet) { - this.someSet = someSet; - } - - public Map getSomeMap() { - return someMap; - } - - public void setSomeMap(Map someMap) { - this.someMap = someMap; - } - - public List getSomeList() { - return someList; - } - - public void setSomeList(List someList) { - this.someList = someList; - } - - public Properties getSomeProperties() { - return someProperties; - } - - public void setSomeProperties(Properties someProperties) { - this.someProperties = someProperties; - } - - @Override - public INestedTestBean getDoctor() { - return doctor; - } - - public void setDoctor(INestedTestBean doctor) { - this.doctor = doctor; - } - - @Override - public INestedTestBean getLawyer() { - return lawyer; - } - - public void setLawyer(INestedTestBean lawyer) { - this.lawyer = lawyer; - } - - public Number getSomeNumber() { - return someNumber; - } - - public void setSomeNumber(Number someNumber) { - this.someNumber = someNumber; - } - - public Colour getFavouriteColour() { - return favouriteColour; - } - - public void setFavouriteColour(Colour favouriteColour) { - this.favouriteColour = favouriteColour; - } - - public Boolean getSomeBoolean() { - return someBoolean; - } - - public void setSomeBoolean(Boolean someBoolean) { - this.someBoolean = someBoolean; - } - - @Override - public IndexedTestBean getNestedIndexedBean() { - return nestedIndexedBean; - } - - public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) { - this.nestedIndexedBean = nestedIndexedBean; - } - - public List getOtherColours() { - return otherColours; - } - - public void setOtherColours(List otherColours) { - this.otherColours = otherColours; - } - - public List getPets() { - return pets; - } - - public void setPets(List pets) { - this.pets = pets; - } - - - /** - * @see ITestBean#exceptional(Throwable) - */ - @Override - public void exceptional(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - } - - @Override - public void unreliableFileOperation() throws IOException { - throw new IOException(); - } - /** - * @see ITestBean#returnsThis() - */ - @Override - public Object returnsThis() { - return this; - } - - /** - * @see IOther#absquatulate() - */ - @Override - public void absquatulate() { - } - - @Override - public int haveBirthday() { - return age++; - } - - - public void destroy() { - this.destroyed = true; - } - - public boolean wasDestroyed() { - return destroyed; - } - - - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (other == null || !(other instanceof TestBean)) { - return false; - } - TestBean tb2 = (TestBean) other; - return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age); - } - - public int hashCode() { - return this.age; - } - - @Override - public int compareTo(Object other) { - if (this.name != null && other instanceof TestBean) { - return this.name.compareTo(((TestBean) other).getName()); - } - else { - return 1; - } - } - - public String toString() { - return this.name; - } - -} diff --git a/src/test/java/test/interceptor/NopInterceptor.java b/src/test/java/test/interceptor/NopInterceptor.java deleted file mode 100644 index b1cdf832a4..0000000000 --- a/src/test/java/test/interceptor/NopInterceptor.java +++ /dev/null @@ -1,59 +0,0 @@ - -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.interceptor; - -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; - -/** - * Trivial interceptor that can be introduced in a chain to display it. - * - * @author Rod Johnson - */ -public class NopInterceptor implements MethodInterceptor { - - private int count; - - /** - * @see org.aopalliance.intercept.MethodInterceptor#invoke(MethodInvocation) - */ - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - increment(); - return invocation.proceed(); - } - - public int getCount() { - return this.count; - } - - protected void increment() { - ++count; - } - - public boolean equals(Object other) { - if (!(other instanceof NopInterceptor)) { - return false; - } - if (this == other) { - return true; - } - return this.count == ((NopInterceptor) other).count; - } - -} diff --git a/src/test/java/test/interceptor/SerializableNopInterceptor.java b/src/test/java/test/interceptor/SerializableNopInterceptor.java deleted file mode 100644 index d2fbdc584a..0000000000 --- a/src/test/java/test/interceptor/SerializableNopInterceptor.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.interceptor; - -import java.io.Serializable; - - -/** - * Subclass of NopInterceptor that is serializable and - * can be used to test proxy serialization. - * - * @author Rod Johnson - */ -@SuppressWarnings("serial") -public class SerializableNopInterceptor extends NopInterceptor implements Serializable { - - /** - * We must override this field and the related methods as - * otherwise count won't be serialized from the non-serializable - * NopInterceptor superclass. - */ - private int count; - - @Override - public int getCount() { - return this.count; - } - - @Override - protected void increment() { - ++count; - } - -} \ No newline at end of file diff --git a/src/test/java/test/util/SerializationTestUtils.java b/src/test/java/test/util/SerializationTestUtils.java deleted file mode 100644 index e9bc9fee04..0000000000 --- a/src/test/java/test/util/SerializationTestUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package test.util; - -import java.awt.*; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.NotSerializableException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.io.OutputStream; -import java.io.Serializable; - -import static org.junit.Assert.*; -import org.junit.Test; -import test.beans.TestBean; - -/** - * Utilities for testing serializability of objects. - * Exposes static methods for use in other test cases. - * Contains {@link org.junit.Test} methods to test itself. - * - * @author Rod Johnson - * @author Chris Beams - */ -public final class SerializationTestUtils { - - public static void testSerialization(Object o) throws IOException { - OutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - } - - public static boolean isSerializable(Object o) throws IOException { - try { - testSerialization(o); - return true; - } - catch (NotSerializableException ex) { - return false; - } - } - - public static Object serializeAndDeserialize(Object o) throws IOException, ClassNotFoundException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); - oos.flush(); - baos.flush(); - byte[] bytes = baos.toByteArray(); - - ByteArrayInputStream is = new ByteArrayInputStream(bytes); - ObjectInputStream ois = new ObjectInputStream(is); - Object o2 = ois.readObject(); - return o2; - } - - - @Test(expected=NotSerializableException.class) - public void testWithNonSerializableObject() throws IOException { - TestBean o = new TestBean(); - assertFalse(o instanceof Serializable); - assertFalse(isSerializable(o)); - - testSerialization(o); - } - - @Test - public void testWithSerializableObject() throws Exception { - int x = 5; - int y = 10; - Point p = new Point(x, y); - assertTrue(p instanceof Serializable); - - testSerialization(p); - - assertTrue(isSerializable(p)); - - Point p2 = (Point) serializeAndDeserialize(p); - assertNotSame(p, p2); - assertEquals(x, (int) p2.getX()); - assertEquals(y, (int) p2.getY()); - } - -} From d1e6dbe74aea3503181f87b1879d925b3c80490b Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 10:29:11 +0100 Subject: [PATCH 005/311] Update Apache license headers for affected sources --- .../springframework/cache/aspectj/AspectJAnnotationTests.java | 2 +- .../springframework/scheduling/quartz/QuartzSupportTests.java | 2 +- .../org/springframework/aop/aspectj/DeclareParentsTests.java | 2 +- .../scripting/groovy/GroovyScriptFactoryTests.java | 2 +- .../scripting/jruby/JRubyScriptFactoryTests.java | 2 +- .../test/java/org/springframework/core/ConventionsTests.java | 2 +- .../core/GenericCollectionTypeResolverTests.java | 2 +- .../core/LocalVariableTableParameterNameDiscovererTests.java | 2 +- .../core/PrioritizedParameterNameDiscovererTests.java | 2 +- .../test/java/org/springframework/core/type/TestAutowired.java | 2 +- .../test/java/org/springframework/core/type/TestQualifier.java | 2 +- .../test/java/org/springframework/tests/TestResourceUtils.java | 2 +- .../src/test/java/org/springframework/tests/TimeStamped.java | 2 +- .../java/org/springframework/util/AutoPopulatingListTests.java | 2 +- .../src/test/java/org/springframework/util/ClassUtilsTests.java | 2 +- .../java/org/springframework/util/ReflectionUtilsTests.java | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java index 43af45e80d..c85d84d083 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java +++ b/spring-aspects/src/test/java/org/springframework/cache/aspectj/AspectJAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java index 5c0cc1c0e3..a5160ac464 100644 --- a/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/scheduling/quartz/QuartzSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java index 145617f07a..18c49440c4 100644 --- a/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java +++ b/spring-context/src/test/java/org/springframework/aop/aspectj/DeclareParentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index e472a7064e..2d92b357d9 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java index 8071e6309e..1a27e4a099 100644 --- a/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/jruby/JRubyScriptFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java index b906164710..cdc94380d0 100644 --- a/spring-core/src/test/java/org/springframework/core/ConventionsTests.java +++ b/spring-core/src/test/java/org/springframework/core/ConventionsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java b/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java index c598269137..08fbaa96a2 100644 --- a/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java index a151571379..bc659f61d4 100644 --- a/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/LocalVariableTableParameterNameDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java b/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java index cd16ed0446..19c16d1512 100644 --- a/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java +++ b/spring-core/src/test/java/org/springframework/core/PrioritizedParameterNameDiscovererTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/core/type/TestAutowired.java b/spring-core/src/test/java/org/springframework/core/type/TestAutowired.java index 28000349fa..c1a1b1d218 100644 --- a/spring-core/src/test/java/org/springframework/core/type/TestAutowired.java +++ b/spring-core/src/test/java/org/springframework/core/type/TestAutowired.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/core/type/TestQualifier.java b/spring-core/src/test/java/org/springframework/core/type/TestQualifier.java index d33d044db8..9698ec7151 100644 --- a/spring-core/src/test/java/org/springframework/core/type/TestQualifier.java +++ b/spring-core/src/test/java/org/springframework/core/type/TestQualifier.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/tests/TestResourceUtils.java b/spring-core/src/test/java/org/springframework/tests/TestResourceUtils.java index 9958110f3c..93aab19448 100644 --- a/spring-core/src/test/java/org/springframework/tests/TestResourceUtils.java +++ b/spring-core/src/test/java/org/springframework/tests/TestResourceUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/tests/TimeStamped.java b/spring-core/src/test/java/org/springframework/tests/TimeStamped.java index 60042247b7..ad653a50d9 100644 --- a/spring-core/src/test/java/org/springframework/tests/TimeStamped.java +++ b/spring-core/src/test/java/org/springframework/tests/TimeStamped.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java index 460e81b297..550b826f9c 100644 --- a/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java +++ b/spring-core/src/test/java/org/springframework/util/AutoPopulatingListTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java index f99216bbbe..f4078360de 100644 --- a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java index 44025a090f..6b791a154b 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 51b307681a8ee7d89180f58f967856b9c4bf9232 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 11:04:54 +0100 Subject: [PATCH 006/311] Fix warnings due to unused import statements Issue: SPR-9431 --- .../CustomizableTraceInterceptorTests.java | 4 +--- .../SimpleTraceInterceptorTests.java | 4 +--- .../support/BeanFactoryGenericsTests.java | 2 -- .../beans/support/PagedListHolderTests.java | 2 -- .../beans/CollectingReaderEventListener.java | 3 +-- ...SimpleRemoteSlsbInvokerInterceptorTests.java | 3 +-- .../jdbc/core/AbstractRowMapperTests.java | 3 +-- .../core/simple/TableMetaDataContextTests.java | 17 ++++++++++++++++- .../portlet/bind/PortletRequestUtilsTests.java | 4 +--- .../support/ServletContextSupportTests.java | 1 - 10 files changed, 22 insertions(+), 21 deletions(-) diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java index 77aad8e9ff..0c1c50c9c5 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/CustomizableTraceInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.lang.reflect.Method; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java index 6efc651d27..96501f2c14 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import java.lang.reflect.Method; - import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.junit.Test; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java index cab03e3823..2480f64fac 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java @@ -47,8 +47,6 @@ import org.springframework.core.io.UrlResource; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import org.springframework.tests.Assume; -import org.springframework.tests.TestGroup; import org.springframework.tests.sample.beans.GenericBean; import org.springframework.tests.sample.beans.GenericIntegerBean; import org.springframework.tests.sample.beans.GenericSetOfIntegerBean; diff --git a/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java index 9e5bd8911a..7e7694767c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/support/PagedListHolderTests.java @@ -24,8 +24,6 @@ import org.junit.Test; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; -import org.springframework.tests.Assume; -import org.springframework.tests.TestGroup; import org.springframework.tests.sample.beans.TestBean; import static org.junit.Assert.*; diff --git a/spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java b/spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java index 8779f9ed5e..b581a05f03 100644 --- a/spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java +++ b/spring-beans/src/test/java/org/springframework/tests/beans/CollectingReaderEventListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,6 @@ import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.parsing.DefaultsDefinition; import org.springframework.beans.factory.parsing.ImportDefinition; import org.springframework.beans.factory.parsing.ReaderEventListener; -import org.springframework.core.CollectionFactory; /** * @author Rob Harrop diff --git a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java index c0fa18c2c3..0c03c57c69 100644 --- a/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ package org.springframework.ejb.access; import static org.junit.Assert.*; import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java index aeffd6f6bb..98016c6113 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/AbstractRowMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import java.math.BigDecimal; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; -import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java index a6d22145b9..34572961a8 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/simple/TableMetaDataContextTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.jdbc.core.simple; import static org.junit.Assert.*; @@ -9,7 +25,6 @@ import static org.mockito.Mockito.verify; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; -import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; import java.util.Date; diff --git a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java index 8092d835b3..9c3e7b045d 100644 --- a/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java +++ b/spring-webmvc-portlet/src/test/java/org/springframework/web/portlet/bind/PortletRequestUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,6 @@ package org.springframework.web.portlet.bind; -import junit.framework.TestCase; - import org.junit.Test; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java index 07823327e6..77bc44cca5 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/context/support/ServletContextSupportTests.java @@ -41,7 +41,6 @@ import org.springframework.beans.factory.support.ManagedList; import org.springframework.beans.factory.support.ManagedMap; import org.springframework.beans.factory.support.ManagedSet; import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.Resource; import org.springframework.mock.web.test.MockServletContext; From 15e9fe638c631c8c75d3499a083c103ddef594a8 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 11:38:58 +0100 Subject: [PATCH 007/311] Remove duplicate test resources The files deleted in this commit existed in identical form in two places within a given module; typically in src/test/java and src/test/resources. The version within src/test/resources has been favored in all cases. This change was prompted by associated Eclipse warnings, which have now been quelled. Issue: SPR-9431 --- .../jdbc/support/custom-error-codes.xml | 24 ------------ .../jdbc/support/test-error-codes.xml | 14 ------- .../jdbc/support/wildcard-error-codes.xml | 38 ------------------- .../orm/hibernate3/filterDefinitions.xml | 30 --------------- .../orm/hibernate3/typeDefinitions.xml | 32 ---------------- .../springframework/orm/jdo/test.properties | 1 - .../web/context/WEB-INF/empty-servlet.xml | 12 ------ .../web/context/WEB-INF/sessionContext.xml | 16 -------- .../web/servlet/complexviews.properties | 3 -- 9 files changed, 170 deletions(-) delete mode 100644 spring-jdbc/src/test/java/org/springframework/jdbc/support/custom-error-codes.xml delete mode 100644 spring-jdbc/src/test/java/org/springframework/jdbc/support/test-error-codes.xml delete mode 100644 spring-jdbc/src/test/java/org/springframework/jdbc/support/wildcard-error-codes.xml delete mode 100644 spring-orm/src/test/java/org/springframework/orm/hibernate3/filterDefinitions.xml delete mode 100644 spring-orm/src/test/java/org/springframework/orm/hibernate3/typeDefinitions.xml delete mode 100644 spring-orm/src/test/java/org/springframework/orm/jdo/test.properties delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/empty-servlet.xml delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml delete mode 100644 spring-webmvc/src/test/java/org/springframework/web/servlet/complexviews.properties diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/custom-error-codes.xml b/spring-jdbc/src/test/java/org/springframework/jdbc/support/custom-error-codes.xml deleted file mode 100644 index a2aa189832..0000000000 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/custom-error-codes.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - 1,2 - 1,1400,1722 - - - - 999 - - org.springframework.jdbc.support.CustomErrorCodeException - - - - - - - diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/test-error-codes.xml b/spring-jdbc/src/test/java/org/springframework/jdbc/support/test-error-codes.xml deleted file mode 100644 index dd3fc33004..0000000000 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/test-error-codes.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - 1,2 - 1,1400,1722 - - - diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/wildcard-error-codes.xml b/spring-jdbc/src/test/java/org/springframework/jdbc/support/wildcard-error-codes.xml deleted file mode 100644 index b44c0a9c1b..0000000000 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/wildcard-error-codes.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - 1,2,942 - 1,1400,1722 - - - - *DB0 - -204,1,2 - 3,4 - - - - DB1* - -204,1,2 - 3,4 - - - - *DB2* - -204,1,2 - 3,4 - - - - *DB3* - -204,1,2 - 3,4 - - - diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/filterDefinitions.xml b/spring-orm/src/test/java/org/springframework/orm/hibernate3/filterDefinitions.xml deleted file mode 100644 index 96b19990ac..0000000000 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/filterDefinitions.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - string - long - - - - - - - - integer - - - - - - - - diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/typeDefinitions.xml b/spring-orm/src/test/java/org/springframework/orm/hibernate3/typeDefinitions.xml deleted file mode 100644 index bd12f319b7..0000000000 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/typeDefinitions.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - value1 - othervalue - - - - - - - - - myvalue - - - - - - - - diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/test.properties b/spring-orm/src/test/java/org/springframework/orm/jdo/test.properties deleted file mode 100644 index cd4acea927..0000000000 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/test.properties +++ /dev/null @@ -1 +0,0 @@ -myKey=myValue diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/empty-servlet.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/empty-servlet.xml deleted file mode 100644 index b49584e11d..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/empty-servlet.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml b/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml deleted file mode 100644 index eb7bf0f6ea..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/context/WEB-INF/sessionContext.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/complexviews.properties b/spring-webmvc/src/test/java/org/springframework/web/servlet/complexviews.properties deleted file mode 100644 index 6917be2162..0000000000 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/complexviews.properties +++ /dev/null @@ -1,3 +0,0 @@ -form.(class)=org.springframework.web.servlet.view.InternalResourceView -form.requestContextAttribute=rc -form.url=myform.jsp From 662a02b952126c726fe0db16179a6b4595cc08b9 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 11:41:49 +0100 Subject: [PATCH 008/311] Fix several miscellaneous compiler/Eclipse warnings - Suppress an (intentional) AspectJ warning - Remove unused imports - Suppress a [hiding] warning - Fix a generics warning related to extension of final types Issue: SPR-9431 --- .../aop/aspectj/autoproxy/CodeStyleAspect.aj | 5 ++++- .../AnnotationProcessorPerformanceTests.java | 1 - .../BeanMethodPolymorphismTests.java | 18 +++++++++++++++++- .../ScheduledExecutorFactoryBeanTests.java | 1 - .../core/BridgeMethodResolverTests.java | 4 ++-- 5 files changed, 23 insertions(+), 6 deletions(-) diff --git a/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/CodeStyleAspect.aj b/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/CodeStyleAspect.aj index 0758d3a403..77da43176a 100644 --- a/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/CodeStyleAspect.aj +++ b/spring-aspects/src/test/java/org/springframework/aop/aspectj/autoproxy/CodeStyleAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.aop.aspectj.autoproxy; +import org.aspectj.lang.annotation.SuppressAjWarnings; + /** * @author Adrian Colyer */ @@ -25,6 +27,7 @@ public aspect CodeStyleAspect { pointcut somePC() : call(* someMethod()); + @SuppressAjWarnings("adviceDidNotMatch") before() : somePC() { System.out.println("match"); } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java index 0a9cfdf655..578748f4fd 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationProcessorPerformanceTests.java @@ -17,7 +17,6 @@ package org.springframework.context.annotation; import static org.junit.Assert.*; -import static org.junit.Assume.assumeFalse; import javax.annotation.Resource; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java index 4797aae61b..655324d1c7 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package org.springframework.context.annotation; import static org.hamcrest.CoreMatchers.equalTo; @@ -31,7 +47,7 @@ public class BeanMethodPolymorphismTests { @Test public void beanMethodOverloadingWithoutInheritance() { - @SuppressWarnings("unused") + @SuppressWarnings({ "unused", "hiding" }) @Configuration class Config { @Bean String aString() { return "na"; } @Bean String aString(Integer dependency) { return "na"; } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java index 4f5b69735e..095f930c61 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBeanTests.java @@ -28,7 +28,6 @@ import org.springframework.tests.TestGroup; import static org.junit.Assert.*; import static org.mockito.BDDMockito.*; -import static org.mockito.Mockito.*; /** * @author Rick Evans diff --git a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java index b4c32171cf..c013f3d3db 100644 --- a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1048,7 +1048,7 @@ public class BridgeMethodResolverTests { } - public class GenericSqlMapIntegerDao extends GenericSqlMapDao { + public class GenericSqlMapIntegerDao extends GenericSqlMapDao { @Override public void saveOrUpdate(T t) { From 42729014b67e8d63e70420f3aa4c058f00b07b45 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 11:56:26 +0100 Subject: [PATCH 009/311] Move namespace tests to root integration module Prior to this change, spring-beans contained its own META-INF containing spring.handlers and spring.schemas files in src/main/resources; it also had files of the same name within src/test/resources/META-INF, causing 'duplicate resource' warnings and confusion in general. This commit moves the com.foo test package, it's associated namespace parsing tests and test versions of META-INF files to the root project and it's src/test integration testing folder. Issue: SPR-9431 --- {spring-beans/src => src}/test/java/com/foo/Component.java | 0 .../test/java/com/foo/ComponentBeanDefinitionParser.java | 0 .../test/java/com/foo/ComponentBeanDefinitionParserTests.java | 2 +- .../src => src}/test/java/com/foo/ComponentFactoryBean.java | 0 .../test/java/com/foo/ComponentNamespaceHandler.java | 0 .../src => src}/test/resources/META-INF/spring.handlers | 0 .../src => src}/test/resources/META-INF/spring.schemas | 0 .../src => src}/test/resources/com/foo/component-config.xml | 0 {spring-beans/src => src}/test/resources/com/foo/component.xsd | 0 9 files changed, 1 insertion(+), 1 deletion(-) rename {spring-beans/src => src}/test/java/com/foo/Component.java (100%) rename {spring-beans/src => src}/test/java/com/foo/ComponentBeanDefinitionParser.java (100%) rename spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java => src/test/java/com/foo/ComponentBeanDefinitionParserTests.java (97%) rename {spring-beans/src => src}/test/java/com/foo/ComponentFactoryBean.java (100%) rename {spring-beans/src => src}/test/java/com/foo/ComponentNamespaceHandler.java (100%) rename {spring-beans/src => src}/test/resources/META-INF/spring.handlers (100%) rename {spring-beans/src => src}/test/resources/META-INF/spring.schemas (100%) rename {spring-beans/src => src}/test/resources/com/foo/component-config.xml (100%) rename {spring-beans/src => src}/test/resources/com/foo/component.xsd (100%) diff --git a/spring-beans/src/test/java/com/foo/Component.java b/src/test/java/com/foo/Component.java similarity index 100% rename from spring-beans/src/test/java/com/foo/Component.java rename to src/test/java/com/foo/Component.java diff --git a/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParser.java b/src/test/java/com/foo/ComponentBeanDefinitionParser.java similarity index 100% rename from spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParser.java rename to src/test/java/com/foo/ComponentBeanDefinitionParser.java diff --git a/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java similarity index 97% rename from spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java rename to src/test/java/com/foo/ComponentBeanDefinitionParserTests.java index 97e77c5740..b28d1d4160 100644 --- a/spring-beans/src/test/java/com/foo/ComponentBeanDefinitionParserTest.java +++ b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java @@ -30,7 +30,7 @@ import org.springframework.core.io.ClassPathResource; /** * @author Costin Leau */ -public class ComponentBeanDefinitionParserTest { +public class ComponentBeanDefinitionParserTests { private static DefaultListableBeanFactory bf; diff --git a/spring-beans/src/test/java/com/foo/ComponentFactoryBean.java b/src/test/java/com/foo/ComponentFactoryBean.java similarity index 100% rename from spring-beans/src/test/java/com/foo/ComponentFactoryBean.java rename to src/test/java/com/foo/ComponentFactoryBean.java diff --git a/spring-beans/src/test/java/com/foo/ComponentNamespaceHandler.java b/src/test/java/com/foo/ComponentNamespaceHandler.java similarity index 100% rename from spring-beans/src/test/java/com/foo/ComponentNamespaceHandler.java rename to src/test/java/com/foo/ComponentNamespaceHandler.java diff --git a/spring-beans/src/test/resources/META-INF/spring.handlers b/src/test/resources/META-INF/spring.handlers similarity index 100% rename from spring-beans/src/test/resources/META-INF/spring.handlers rename to src/test/resources/META-INF/spring.handlers diff --git a/spring-beans/src/test/resources/META-INF/spring.schemas b/src/test/resources/META-INF/spring.schemas similarity index 100% rename from spring-beans/src/test/resources/META-INF/spring.schemas rename to src/test/resources/META-INF/spring.schemas diff --git a/spring-beans/src/test/resources/com/foo/component-config.xml b/src/test/resources/com/foo/component-config.xml similarity index 100% rename from spring-beans/src/test/resources/com/foo/component-config.xml rename to src/test/resources/com/foo/component-config.xml diff --git a/spring-beans/src/test/resources/com/foo/component.xsd b/src/test/resources/com/foo/component.xsd similarity index 100% rename from spring-beans/src/test/resources/com/foo/component.xsd rename to src/test/resources/com/foo/component.xsd From 676231644ddd38d14826dd961b20672f6ea1bda8 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 11:57:22 +0100 Subject: [PATCH 010/311] Update Apache license headers for moved files Issue: SPR-9431 --- src/test/java/com/foo/Component.java | 16 ++++++++++++++++ .../com/foo/ComponentBeanDefinitionParser.java | 16 ++++++++++++++++ .../foo/ComponentBeanDefinitionParserTests.java | 1 + src/test/java/com/foo/ComponentFactoryBean.java | 16 ++++++++++++++++ .../java/com/foo/ComponentNamespaceHandler.java | 16 ++++++++++++++++ 5 files changed, 65 insertions(+) diff --git a/src/test/java/com/foo/Component.java b/src/test/java/com/foo/Component.java index 5c5d61ec81..759954c41d 100644 --- a/src/test/java/com/foo/Component.java +++ b/src/test/java/com/foo/Component.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.foo; import java.util.ArrayList; diff --git a/src/test/java/com/foo/ComponentBeanDefinitionParser.java b/src/test/java/com/foo/ComponentBeanDefinitionParser.java index 94dd439bfb..9fb2213c2b 100644 --- a/src/test/java/com/foo/ComponentBeanDefinitionParser.java +++ b/src/test/java/com/foo/ComponentBeanDefinitionParser.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.foo; import java.util.List; diff --git a/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java index b28d1d4160..4a036f6c27 100644 --- a/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java +++ b/src/test/java/com/foo/ComponentBeanDefinitionParserTests.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.foo; import static org.hamcrest.CoreMatchers.equalTo; diff --git a/src/test/java/com/foo/ComponentFactoryBean.java b/src/test/java/com/foo/ComponentFactoryBean.java index ac47c4efea..2b126d4f4e 100644 --- a/src/test/java/com/foo/ComponentFactoryBean.java +++ b/src/test/java/com/foo/ComponentFactoryBean.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.foo; import java.util.List; diff --git a/src/test/java/com/foo/ComponentNamespaceHandler.java b/src/test/java/com/foo/ComponentNamespaceHandler.java index b29eeca061..b1a830c83b 100644 --- a/src/test/java/com/foo/ComponentNamespaceHandler.java +++ b/src/test/java/com/foo/ComponentNamespaceHandler.java @@ -1,3 +1,19 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.foo; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; From cf68cc5f0b2650bb1cd34064d7e43747f79285a4 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 12:08:58 +0100 Subject: [PATCH 011/311] Eliminate AJ @Async warning in test case Prior to this commit, ClassWithAsyncAnnotation#return5 forced an unsuppressable warning in Eclipse, making it virtually impossible to get to a zero-warnings state in the codebase. The 'solution' here is simply to comment out the method and it's associated test case. The 'declare warnings' functionality around @Async is well-understood and has long been stable. Also, the entire AnnotationAsyncExecutionAspectTests class has been added to TestGroup#PERFORMANCE (SPR-9984), as opposed to just asyncMethodGetsRoutedAsynchronously as it was previously, the rationale being that all tests are actually timing dependent. Issue: SPR-9431, SPR-9984 --- .../aspectj/AnnotationAsyncExecutionAspectTests.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java index b95ee6b807..d82367ddb0 100644 --- a/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/scheduling/aspectj/AnnotationAsyncExecutionAspectTests.java @@ -49,14 +49,14 @@ public class AnnotationAsyncExecutionAspectTests { @Before public void setUp() { + Assume.group(TestGroup.PERFORMANCE); + executor = new CountingExecutor(); AnnotationAsyncExecutionAspect.aspectOf().setExecutor(executor); } @Test public void asyncMethodGetsRoutedAsynchronously() { - Assume.group(TestGroup.PERFORMANCE); - ClassWithoutAsyncAnnotation obj = new ClassWithoutAsyncAnnotation(); obj.incrementAsync(); executor.waitForCompletion(); @@ -107,6 +107,7 @@ public class AnnotationAsyncExecutionAspectTests { assertEquals(1, executor.submitCompleteCounter); } + /* @Test public void methodReturningNonVoidNonFutureInAsyncClassGetsRoutedSynchronously() { ClassWithAsyncAnnotation obj = new ClassWithAsyncAnnotation(); @@ -115,6 +116,7 @@ public class AnnotationAsyncExecutionAspectTests { assertEquals(0, executor.submitStartCounter); assertEquals(0, executor.submitCompleteCounter); } + */ @Test public void qualifiedAsyncMethodsAreRoutedToCorrectExecutor() throws InterruptedException, ExecutionException { @@ -198,9 +200,11 @@ public class AnnotationAsyncExecutionAspectTests { // Manually check that there is a warning from the 'declare warning' statement in // AnnotationAsyncExecutionAspect + /* public int return5() { return 5; } + */ public Future incrementReturningAFuture() { counter++; From 4c0a30694367c00c90656526d2fd0ddb4e3704cf Mon Sep 17 00:00:00 2001 From: Stevo Slavic Date: Sat, 5 Jan 2013 23:06:09 +0100 Subject: [PATCH 012/311] Mark all IsFastEnough tests as performance tests This patch marks remaining/missed tests as ones belonging to performance tests group. Issue: SPR-9984 --- .../org/springframework/web/bind/ServletRequestUtilsTests.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java index ada52ec33c..334f4b0d78 100644 --- a/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java +++ b/spring-web/src/test/java/org/springframework/web/bind/ServletRequestUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -388,6 +388,7 @@ public class ServletRequestUtilsTests { @Test public void testGetIntParameterWithDefaultValueHandlingIsFastEnough() { + Assume.group(TestGroup.PERFORMANCE); MockHttpServletRequest request = new MockHttpServletRequest(); StopWatch sw = new StopWatch(); sw.start(); From 00a86c37222d92b1477f2480b7bdfaebd12c2d1a Mon Sep 17 00:00:00 2001 From: Glyn Normington Date: Thu, 3 Jan 2013 14:50:45 +0000 Subject: [PATCH 013/311] Detect split packages at build time Split packages are a well-known anti-pattern for OSGi and a blocker for Eclipse Virgo (which prevents split packages being accessed via its Import-Library construct). Split packages are also unhelpful with a traditional linear classpath as a split package name does not uniquely identify the Spring framework JAR from which it came, thus complicating problem diagnosis and maintenance. Juergen Hoeller supports this position in the following comment in SPR-9990: >FWIW, I generally find split packages a bad practice, even without >OSGi in the mix. For the Spring Framework codebase, I consider a >split-package arrangement a design accident that we want to detect >in any case - and that we're willing to fix if it happened. > >I'm actually equally concerned about the source perspective: After >all, we want a package to be comprehensible from a single glance >at the project, not requiring the developer to jump into several >source modules to understand the overall layout of a package. Split packages have crept into Spring framework twice in recent months - see SPR-9811 and SPR-9988. Currently, they are only detected once the Spring framework has been converted to OSGi bundles and these bundles have been tested with Eclipse Virgo. This commit adds a build-time check for split packages to the Spring framework build. Issue: SPR-9990 Conflicts: build.gradle --- build.gradle | 6 ++ .../build/gradle/SplitPackageDetector.groovy | 85 +++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy diff --git a/build.gradle b/build.gradle index 8c0a1b4245..b9a5e2e838 100644 --- a/build.gradle +++ b/build.gradle @@ -8,6 +8,11 @@ buildscript { } } +configure(rootProject) { + def splitFound = new org.springframework.build.gradle.SplitPackageDetector('.', logger).diagnoseSplitPackages(); + assert !splitFound // see error log messages for details of split packages +} + configure(allprojects) { project -> group = "org.springframework" version = qualifyVersionIfNecessary(version) @@ -954,6 +959,7 @@ configure(rootProject) { "set GRADLE_OPTS=$gradleBatOpts %GRADLE_OPTS%\nset DEFAULT_JVM_OPTS=") } } + } /* diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy new file mode 100644 index 0000000000..b17f859de1 --- /dev/null +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy @@ -0,0 +1,85 @@ +/* + * Copyright 2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.build.gradle + +class SplitPackageDetector { + + private static final String HIDDEN_DIRECTORY_PREFIX = "." + + private static final String JAVA_FILE_SUFFIX = ".java" + + private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" + + private final Map> pkgMap = [:] + + private final logger + + SplitPackageDetector(baseDir, logger) { + this.logger = logger + dirList(baseDir).each { File dir -> + def packages = getPackagesInDirectory(dir) + if (!packages.isEmpty()) { + pkgMap.put(dir, packages) + } + } + } + + private File[] dirList(String dir) { + dirList(new File(dir)) + } + + private File[] dirList(File dir) { + dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) + } + + private Set getPackagesInDirectory(File dir) { + def pkgs = new HashSet() + addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") + return pkgs; + } + + boolean diagnoseSplitPackages() { + def splitFound = false; + def dirs = pkgMap.keySet().toArray() + def numDirs = dirs.length + for (int i = 0; i < numDirs - 1; i++) { + for (int j = i + 1; j < numDirs - 1; j++) { + def di = dirs[i] + def pi = new HashSet(pkgMap.get(di)) + def dj = dirs[j] + def pj = pkgMap.get(dj) + pi.retainAll(pj) + if (!pi.isEmpty()) { + logger.error("Packages $pi are split between directories '$di' and '$dj'") + splitFound = true + } + } + } + return splitFound + } + + private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { + def scanDir = new File(dir, pkg) + def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) + if (javaFiles != null && javaFiles.length != 0) { + packages.add(pkg) + } + dirList(scanDir).each { File subDir -> + addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) + } + } +} \ No newline at end of file From a27a3be76c5812a97f7439187838c7bbaedaff97 Mon Sep 17 00:00:00 2001 From: Rob Winch Date: Thu, 3 Jan 2013 13:04:51 -0600 Subject: [PATCH 014/311] Example SplitPackageDetectorPlugin --- build.gradle | 7 +- .../build/gradle/SplitPackageDetector.groovy | 85 ------------ .../gradle/SplitPackageDetectorPlugin.groovy | 125 ++++++++++++++++++ 3 files changed, 130 insertions(+), 87 deletions(-) delete mode 100644 buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy create mode 100644 buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy diff --git a/build.gradle b/build.gradle index b9a5e2e838..6ab6f444de 100644 --- a/build.gradle +++ b/build.gradle @@ -9,8 +9,11 @@ buildscript { } configure(rootProject) { - def splitFound = new org.springframework.build.gradle.SplitPackageDetector('.', logger).diagnoseSplitPackages(); - assert !splitFound // see error log messages for details of split packages + apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin + + diagnoseSplitPackages { + inputDir = project.projectDir + } } configure(allprojects) { project -> diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy deleted file mode 100644 index b17f859de1..0000000000 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetector.groovy +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.build.gradle - -class SplitPackageDetector { - - private static final String HIDDEN_DIRECTORY_PREFIX = "." - - private static final String JAVA_FILE_SUFFIX = ".java" - - private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" - - private final Map> pkgMap = [:] - - private final logger - - SplitPackageDetector(baseDir, logger) { - this.logger = logger - dirList(baseDir).each { File dir -> - def packages = getPackagesInDirectory(dir) - if (!packages.isEmpty()) { - pkgMap.put(dir, packages) - } - } - } - - private File[] dirList(String dir) { - dirList(new File(dir)) - } - - private File[] dirList(File dir) { - dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) - } - - private Set getPackagesInDirectory(File dir) { - def pkgs = new HashSet() - addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") - return pkgs; - } - - boolean diagnoseSplitPackages() { - def splitFound = false; - def dirs = pkgMap.keySet().toArray() - def numDirs = dirs.length - for (int i = 0; i < numDirs - 1; i++) { - for (int j = i + 1; j < numDirs - 1; j++) { - def di = dirs[i] - def pi = new HashSet(pkgMap.get(di)) - def dj = dirs[j] - def pj = pkgMap.get(dj) - pi.retainAll(pj) - if (!pi.isEmpty()) { - logger.error("Packages $pi are split between directories '$di' and '$dj'") - splitFound = true - } - } - } - return splitFound - } - - private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { - def scanDir = new File(dir, pkg) - def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) - if (javaFiles != null && javaFiles.length != 0) { - packages.add(pkg) - } - dirList(scanDir).each { File subDir -> - addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) - } - } -} \ No newline at end of file diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy new file mode 100644 index 0000000000..ed7e421223 --- /dev/null +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy @@ -0,0 +1,125 @@ +/* + * 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.build.gradle + +import java.io.File; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.gradle.api.* +import org.gradle.api.artifacts.Configuration +import org.gradle.api.artifacts.ProjectDependency; +import org.gradle.api.artifacts.maven.Conf2ScopeMapping +import org.gradle.api.plugins.MavenPlugin +import org.gradle.api.tasks.* +import org.gradle.plugins.ide.eclipse.EclipsePlugin +import org.gradle.plugins.ide.eclipse.model.EclipseClasspath; +import org.gradle.plugins.ide.idea.IdeaPlugin +import org.gradle.api.invocation.* + + +class SplitPackageDetectorPlugin implements Plugin { + public void apply(Project project) { + Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) + diagnoseSplitPackages.setDescription('Detects split packages') + //project.tasks.findByName('build').dependsOn(diagnoseSplitPackages) + } +} + +public class SplitPackageDetectorTask extends DefaultTask { + @InputDirectory + File inputDir + + @TaskAction + public final void diagnoseSplitPackages() { + def projects = project.subprojects.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } + projects.each { p -> + println ' > The project directory '+ p.projectDir + ' will merge into ' + p.merge.into.projectDir + } + def splitFound = new org.springframework.build.gradle.SplitPackageDetector(inputDir.absolutePath, project.logger).diagnoseSplitPackages(); + assert !splitFound + } +} + +class SplitPackageDetector { + + private static final String HIDDEN_DIRECTORY_PREFIX = "." + + private static final String JAVA_FILE_SUFFIX = ".java" + + private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" + + private final Map> pkgMap = [:] + + private final logger + + SplitPackageDetector(baseDir, logger) { + this.logger = logger + dirList(baseDir).each { File dir -> + def packages = getPackagesInDirectory(dir) + if (!packages.isEmpty()) { + pkgMap.put(dir, packages) + } + } + } + + private File[] dirList(String dir) { + dirList(new File(dir)) + } + + private File[] dirList(File dir) { + dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) + } + + private Set getPackagesInDirectory(File dir) { + def pkgs = new HashSet() + addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") + return pkgs; + } + + boolean diagnoseSplitPackages() { + def splitFound = false; + def dirs = pkgMap.keySet().toArray() + def numDirs = dirs.length + for (int i = 0; i < numDirs - 1; i++) { + for (int j = i + 1; j < numDirs - 1; j++) { + def di = dirs[i] + def pi = new HashSet(pkgMap.get(di)) + def dj = dirs[j] + def pj = pkgMap.get(dj) + pi.retainAll(pj) + if (!pi.isEmpty()) { + logger.error("Packages $pi are split between directories '$di' and '$dj'") + splitFound = true + } + } + } + return splitFound + } + + private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { + def scanDir = new File(dir, pkg) + def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) + if (javaFiles != null && javaFiles.length != 0) { + packages.add(pkg) + } + dirList(scanDir).each { File subDir -> + addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) + } + } +} \ No newline at end of file From 2df08bdfbdb4efc9da46866eb1a3f6411a045e9e Mon Sep 17 00:00:00 2001 From: Glyn Normington Date: Fri, 4 Jan 2013 11:34:16 +0000 Subject: [PATCH 015/311] Rework split package detection code Allow packages to be split across projects which will be merged into a single JAR file. Make split package detection a dependency of the 'check' task. This is idiomatic gradle as well as allowing the 'test' task (another dependency of 'check') to be executed without split packages being detected. Omit the project spring-instructment-tomcat from the check on the basis of SPR-10150. Issues: SPR-9990, SPR-10150 Conflicts: build.gradle --- build.gradle | 19 +- .../gradle/SplitPackageDetectorPlugin.groovy | 170 +++++++++--------- 2 files changed, 97 insertions(+), 92 deletions(-) diff --git a/build.gradle b/build.gradle index 6ab6f444de..697cdbea53 100644 --- a/build.gradle +++ b/build.gradle @@ -8,14 +8,6 @@ buildscript { } } -configure(rootProject) { - apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin - - diagnoseSplitPackages { - inputDir = project.projectDir - } -} - configure(allprojects) { project -> group = "org.springframework" version = qualifyVersionIfNecessary(version) @@ -761,13 +753,18 @@ configure(rootProject) { apply plugin: "docbook-reference" apply plugin: "groovy" apply from: "${gradleScriptDir}/jdiff.gradle" + apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin - reference { + reference { sourceDir = file("src/reference/docbook") pdfFilename = "spring-framework-reference.pdf" } - // don"t publish the default jar for the root project + diagnoseSplitPackages { + projectsToScan = project.subprojects - project(":spring-instrument-tomcat") // SPR-10150 + } + + // don"t publish the default jar for the root project configurations.archives.artifacts.clear() dependencies { // for integration tests @@ -791,6 +788,8 @@ configure(rootProject) { testCompile("hsqldb:hsqldb:${hsqldbVersion}") } + check.dependsOn diagnoseSplitPackages + task api(type: Javadoc) { group = "Documentation" description = "Generates aggregated Javadoc API documentation." diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy index ed7e421223..01c36fad7a 100644 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,110 +16,116 @@ package org.springframework.build.gradle -import java.io.File; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import org.gradle.api.* +import org.gradle.api.DefaultTask +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.Task import org.gradle.api.artifacts.Configuration -import org.gradle.api.artifacts.ProjectDependency; +import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.artifacts.maven.Conf2ScopeMapping import org.gradle.api.plugins.MavenPlugin -import org.gradle.api.tasks.* +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.TaskAction import org.gradle.plugins.ide.eclipse.EclipsePlugin -import org.gradle.plugins.ide.eclipse.model.EclipseClasspath; +import org.gradle.plugins.ide.eclipse.model.EclipseClasspath import org.gradle.plugins.ide.idea.IdeaPlugin -import org.gradle.api.invocation.* - class SplitPackageDetectorPlugin implements Plugin { - public void apply(Project project) { - Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) - diagnoseSplitPackages.setDescription('Detects split packages') - //project.tasks.findByName('build').dependsOn(diagnoseSplitPackages) - } + public void apply(Project project) { + Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) + diagnoseSplitPackages.setDescription('Detects packages which will be split across JARs') + } } public class SplitPackageDetectorTask extends DefaultTask { - @InputDirectory - File inputDir + @Input + Set projectsToScan - @TaskAction - public final void diagnoseSplitPackages() { - def projects = project.subprojects.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } - projects.each { p -> - println ' > The project directory '+ p.projectDir + ' will merge into ' + p.merge.into.projectDir - } - def splitFound = new org.springframework.build.gradle.SplitPackageDetector(inputDir.absolutePath, project.logger).diagnoseSplitPackages(); - assert !splitFound - } + @TaskAction + public final void diagnoseSplitPackages() { + def Map mergeMap = [:] + def projects = projectsToScan.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } + projects.each { p -> + mergeMap.put(p, p.merge.into) + } + def splitFound = new org.springframework.build.gradle.SplitPackageDetector(projectsToScan, mergeMap, project.logger).diagnoseSplitPackages(); + assert !splitFound // see error log messages for details of split packages + } } class SplitPackageDetector { - private static final String HIDDEN_DIRECTORY_PREFIX = "." + private static final String HIDDEN_DIRECTORY_PREFIX = "." - private static final String JAVA_FILE_SUFFIX = ".java" + private static final String JAVA_FILE_SUFFIX = ".java" - private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" + private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" - private final Map> pkgMap = [:] + private static final String PACKAGE_SEPARATOR = "." - private final logger + private final Map mergeMap - SplitPackageDetector(baseDir, logger) { - this.logger = logger - dirList(baseDir).each { File dir -> - def packages = getPackagesInDirectory(dir) - if (!packages.isEmpty()) { - pkgMap.put(dir, packages) - } - } - } + private final Map> pkgMap = [:] - private File[] dirList(String dir) { - dirList(new File(dir)) - } + private final logger - private File[] dirList(File dir) { - dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) - } + SplitPackageDetector(projectsToScan, mergeMap, logger) { + this.mergeMap = mergeMap + this.logger = logger + projectsToScan.each { Project p -> + def dir = p.projectDir + def packages = getPackagesInDirectory(dir) + if (!packages.isEmpty()) { + pkgMap.put(p, packages) + } + } + } - private Set getPackagesInDirectory(File dir) { - def pkgs = new HashSet() - addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") - return pkgs; - } + private File[] dirList(String dir) { + dirList(new File(dir)) + } - boolean diagnoseSplitPackages() { - def splitFound = false; - def dirs = pkgMap.keySet().toArray() - def numDirs = dirs.length - for (int i = 0; i < numDirs - 1; i++) { - for (int j = i + 1; j < numDirs - 1; j++) { - def di = dirs[i] - def pi = new HashSet(pkgMap.get(di)) - def dj = dirs[j] - def pj = pkgMap.get(dj) - pi.retainAll(pj) - if (!pi.isEmpty()) { - logger.error("Packages $pi are split between directories '$di' and '$dj'") - splitFound = true - } - } - } - return splitFound - } + private File[] dirList(File dir) { + dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) + } - private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { - def scanDir = new File(dir, pkg) - def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) - if (javaFiles != null && javaFiles.length != 0) { - packages.add(pkg) - } - dirList(scanDir).each { File subDir -> - addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) - } - } + private Set getPackagesInDirectory(File dir) { + def pkgs = new HashSet() + addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") + return pkgs; + } + + boolean diagnoseSplitPackages() { + def splitFound = false; + def projs = pkgMap.keySet().toArray() + def numProjects = projs.length + for (int i = 0; i < numProjects - 1; i++) { + for (int j = i + 1; j < numProjects - 1; j++) { + def pi = projs[i] + def pkgi = new HashSet(pkgMap.get(pi)) + def pj = projs[j] + def pkgj = pkgMap.get(pj) + pkgi.retainAll(pkgj) + if (!pkgi.isEmpty() && mergeMap.get(pi) != pj && mergeMap.get(pj) != pi) { + pkgi.each { pkg -> + def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) + logger.error("Package '$readablePkg' is split between $pi and $pj") + } + splitFound = true + } + } + } + return splitFound + } + + private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { + def scanDir = new File(dir, pkg) + def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) + if (javaFiles != null && javaFiles.length != 0) { + packages.add(pkg) + } + dirList(scanDir).each { File subDir -> + addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) + } + } } \ No newline at end of file From f92f58d0b37c5bc03a355b9e3e1a0a99fe14478c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 7 Jan 2013 13:06:59 -0800 Subject: [PATCH 016/311] Gradle 'api' task depends on 'jar' tasks Update the gradle 'api' task to depend on the 'jar' task of all subprojects. This intern ensures that the 'asmRepackJar' and 'cglibRepackJar' tasks run which is critical for JavaDoc generation. --- build.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build.gradle b/build.gradle index 8c0a1b4245..b9533242d5 100644 --- a/build.gradle +++ b/build.gradle @@ -788,6 +788,11 @@ configure(rootProject) { description = "Generates aggregated Javadoc API documentation." title = "${rootProject.description} ${version} API" + dependsOn { + subprojects.collect { + it.tasks.getByName("jar") + } + } options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED options.author = true options.header = rootProject.description From 153508a300772db262c6123f57fbc4bcbf89b4f4 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 7 Jan 2013 16:55:09 -0500 Subject: [PATCH 017/311] Support "X-Forwarded-Host" in UriComponentsBuilder ServletUriComponentsBuilder now supports setting the host to the value held in the X-Forwarded-Host [0] header used in reverse proxy scenarios. [0] http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10 Issue: SPR-10110 --- .../servlet/support/ServletUriComponentsBuilder.java | 12 +++++++++--- .../support/ServletUriComponentsBuilderTests.java | 12 +++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java index 8aa5864390..7ad0d49b78 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/ServletUriComponentsBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -95,9 +95,12 @@ public class ServletUriComponentsBuilder extends UriComponentsBuilder { String scheme = request.getScheme(); int port = request.getServerPort(); + String header = request.getHeader("X-Forwarded-Host"); + String host = StringUtils.hasText(header) ? header: request.getServerName(); + ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder(); builder.scheme(scheme); - builder.host(request.getServerName()); + builder.host(host); if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443)) { builder.port(port); } @@ -138,7 +141,10 @@ public class ServletUriComponentsBuilder extends UriComponentsBuilder { return fromRequest(getCurrentRequest()); } - private static HttpServletRequest getCurrentRequest() { + /** + * Obtain the request through {@link RequestContextHolder}. + */ + protected static HttpServletRequest getCurrentRequest() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder"); Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java index d87212008c..02ee04662d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/support/ServletUriComponentsBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -83,6 +83,16 @@ public class ServletUriComponentsBuilderTests { assertEquals("http://localhost/mvc-showcase/data/param", result); } + @Test + public void fromRequestWithForwardedHostHeader() { + request.addHeader("X-Forwarded-Host", "anotherHost"); + request.setRequestURI("/mvc-showcase/data/param"); + request.setQueryString("foo=123"); + String result = ServletUriComponentsBuilder.fromRequest(request).build().toUriString(); + + assertEquals("http://anotherHost/mvc-showcase/data/param?foo=123", result); + } + @Test public void fromContextPath() { request.setRequestURI("/mvc-showcase/data/param"); From 7bc9667913571d17c38f2c1854af9eebadffa832 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 7 Jan 2013 18:03:40 -0500 Subject: [PATCH 018/311] Add support for placeholders in @RequestMapping @RequestMapping annotations now support ${...} placeholders. Issue: SPR-9935 --- .../web/bind/annotation/RequestMapping.java | 1 + .../RequestMappingHandlerMapping.java | 36 ++++++++++++++++--- .../RequestMappingHandlerMappingTests.java | 17 ++++++++- src/reference/docbook/mvc.xml | 12 +++++++ 4 files changed, 61 insertions(+), 5 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java index ff4849e35e..320bb95d13 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestMapping.java @@ -266,6 +266,7 @@ public @interface RequestMapping { * Ant-style path patterns are also supported (e.g. "/myPath/*.do"). * At the method level, relative paths (e.g. "edit.do") are supported * within the primary mapping expressed at the type level. + * Path mapping URIs may contain placeholders (e.g. "/${connect}") *

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

Supported at the type level as well as at the method level! diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java index 315cf8f68e..5700b8def7 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,9 +20,11 @@ import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; +import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.stereotype.Controller; import org.springframework.util.Assert; +import org.springframework.util.StringValueResolver; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition; @@ -46,7 +48,8 @@ import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMappi * @author Rossen Stoyanchev * @since 3.1 */ -public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping { +public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping + implements EmbeddedValueResolverAware { private boolean useSuffixPatternMatch = true; @@ -58,6 +61,8 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi private final List fileExtensions = new ArrayList(); + private StringValueResolver embeddedValueResolver; + /** * Whether to use suffix pattern match (".*") when matching patterns to @@ -101,6 +106,11 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi this.useTrailingSlashMatch = useTrailingSlashMatch; } + @Override + public void setEmbeddedValueResolver(StringValueResolver resolver) { + this.embeddedValueResolver = resolver; + } + /** * Set the {@link ContentNegotiationManager} to use to determine requested media types. * If not set, the default constructor is used. @@ -142,7 +152,7 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi * Return the file extensions to use for suffix pattern matching. */ public List getFileExtensions() { - return fileExtensions; + return this.fileExtensions; } @Override @@ -227,8 +237,9 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi * Created a RequestMappingInfo from a RequestMapping annotation. */ private RequestMappingInfo createRequestMappingInfo(RequestMapping annotation, RequestCondition customCondition) { + String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value()); return new RequestMappingInfo( - new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), + new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions), new RequestMethodsRequestCondition(annotation.method()), new ParamsRequestCondition(annotation.params()), @@ -238,4 +249,21 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi customCondition); } + /** + * Resolve placeholder values in the given array of patterns. + * @return a new array with updated patterns + */ + protected String[] resolveEmbeddedValuesInPatterns(String[] patterns) { + if (this.embeddedValueResolver == null) { + return patterns; + } + else { + String[] resolvedPatterns = new String[patterns.length]; + for (int i=0; i < patterns.length; i++) { + resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]); + } + return resolvedPatterns; + } + } + } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java index b5a6bd139e..5c4d0776a4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; +import org.springframework.util.StringValueResolver; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; import org.springframework.web.context.support.StaticWebApplicationContext; @@ -78,4 +79,18 @@ public class RequestMappingHandlerMappingTests { this.handlerMapping.useSuffixPatternMatch()); } + @Test + public void resolveEmbeddedValuesInPatterns() { + this.handlerMapping.setEmbeddedValueResolver(new StringValueResolver() { + public String resolveStringValue(String value) { + return "/${pattern}/bar".equals(value) ? "/foo/bar" : value; + } + }); + + String[] patterns = new String[] { "/foo", "/${pattern}/bar" }; + String[] result = this.handlerMapping.resolveEmbeddedValuesInPatterns(patterns); + + assertArrayEquals(new String[] { "/foo", "/foo/bar" }, result); + } + } diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index ffe081c1e0..279a76ec15 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -1073,6 +1073,18 @@ public class RelativePathUriTemplateController { /owners/*/pets/{petId}). +

+ Patterns with Placeholders + + Patterns in @RequestMapping annotations + support ${...} placeholders against local properties and/or system properties + and environment variables. This may be useful in cases where the path a + controller is mapped to may need to be customized through configuration. + For more information on placeholders see the Javadoc for + PropertyPlaceholderConfigurer. + +
+
Matrix Variables From b8f223c404db419927d4f9763d71e10ca38d37dd Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 8 Jan 2013 11:30:22 +0100 Subject: [PATCH 019/311] Add 3.1 migration section to reference docs Address error raised when using component-scan against the unqualified "org" base package. Issue: SPR-9843 --- src/reference/docbook/index.xml | 3 ++ src/reference/docbook/migration-3.1.xml | 37 +++++++++++++++++++++++++ src/reference/docbook/new-in-3.1.xml | 3 +- 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/reference/docbook/migration-3.1.xml diff --git a/src/reference/docbook/index.xml b/src/reference/docbook/index.xml index 393858cecd..de4af30072 100644 --- a/src/reference/docbook/index.xml +++ b/src/reference/docbook/index.xml @@ -471,6 +471,9 @@ + + diff --git a/src/reference/docbook/migration-3.1.xml b/src/reference/docbook/migration-3.1.xml new file mode 100644 index 0000000000..15ca8d4979 --- /dev/null +++ b/src/reference/docbook/migration-3.1.xml @@ -0,0 +1,37 @@ + + + Migrating to Spring Framework 3.1 + + In this appendix we discuss what users will want to know when upgrading to + Spring Framework 3.1. For a general overview of features, please see + + +
+ Component scanning against the "org" base package + Spring Framework 3.1 introduces a number of @Configuration + classes such as org.springframework.cache.annotation.ProxyCachingConfiguration + and + org.springframework.scheduling.annotation.ProxyAsyncConfiguration. + Because @Configuration is ultimately meta-annotated with Spring's + @Component annotation, these classes will inadvertently be scanned + and processed by the container for any component-scanning directive against the + unqualified "org" package, e.g.: + + <context:component-scan base-package="org"/> + Therefore, in order to avoid errors like the one reported in SPR-9843, + any such directives should be updated to at least one more level of qualification e.g.: + + <context:component-scan base-package="org.xyz"/> + Alternatively, an exclude-filter may be used. See + context:component-scan + documentation for details. +
+
diff --git a/src/reference/docbook/new-in-3.1.xml b/src/reference/docbook/new-in-3.1.xml index ef69b647d0..8a56bfd647 100644 --- a/src/reference/docbook/new-in-3.1.xml +++ b/src/reference/docbook/new-in-3.1.xml @@ -11,7 +11,8 @@ This is a list of new features for Spring Framework 3.1. A number of features do not have dedicated reference documentation but do have complete Javadoc. In such - cases, fully-qualified class names are given. + cases, fully-qualified class names are given. See also +
Cache Abstraction From 23912771154c54f63fdc0034c181edee07f9bb89 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 06:57:58 -0500 Subject: [PATCH 020/311] Fix issue in BufferedImageHttpMessageConverter This change ensures BufferedImageHttpMessageConverter writes when "*/*" is requested. Issue: SPR-7763 --- .../http/converter/BufferedImageHttpMessageConverter.java | 4 ++-- .../converter/BufferedImageHttpMessageConverterTests.java | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java index b9392d0d95..bd9f32d146 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java @@ -132,7 +132,7 @@ public class BufferedImageHttpMessageConverter implements HttpMessageConverter imageWriters = ImageIO.getImageWritersByMIMEType(mediaType.toString()); @@ -191,7 +191,7 @@ public class BufferedImageHttpMessageConverter implements HttpMessageConverter 0); BufferedImage result = ImageIO.read(new ByteArrayInputStream(outputMessage.getBodyAsBytes())); From 87109b348cf1fcae2d4aefe64f9ce6b8fcf389a0 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 09:21:17 -0500 Subject: [PATCH 021/311] Add decoding matrix variable values Issue: SPR-10140 --- .../web/util/UrlPathHelper.java | 29 ++++++++++++ .../RequestMappingInfoHandlerMapping.java | 9 ++-- ...RequestMappingInfoHandlerMappingTests.java | 47 ++++++++++++------- 3 files changed, 66 insertions(+), 19 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java index 67b7a4c024..72b592108a 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java +++ b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java @@ -27,6 +27,8 @@ import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; /** @@ -491,6 +493,33 @@ public class UrlPathHelper { } } + /** + * Decode the given matrix variables via + * {@link #decodeRequestString(HttpServletRequest, String)} unless + * {@link #setUrlDecode(boolean)} is set to {@code true} in which case it is + * assumed the URL path from which the variables were extracted is already + * decoded through a call to + * {@link #getLookupPathForRequest(HttpServletRequest)}. + * + * @param request current HTTP request + * @param vars URI variables extracted from the URL path + * @return the same Map or a new Map instance + */ + public MultiValueMap decodeMatrixVariables(HttpServletRequest request, MultiValueMap vars) { + if (this.urlDecode) { + return vars; + } + else { + MultiValueMap decodedVars = new LinkedMultiValueMap (vars.size()); + for (String key : vars.keySet()) { + for (String value : vars.get(key)) { + decodedVars.add(key, decodeInternal(request, value)); + } + } + return decodedVars; + } + } + private boolean shouldRemoveTrailingServletPathSlash(HttpServletRequest request) { if (request.getAttribute(WEBSPHERE_URI_ATTRIBUTE) == null) { // Regular servlet container: behaves as expected in any case, diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java index dfdfc05ed2..7654d31498 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java @@ -100,7 +100,7 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, decodedUriVariables); if (isMatrixVariableContentAvailable()) { - request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, extractMatrixVariables(uriVariables)); + request.setAttribute(HandlerMapping.MATRIX_VARIABLES_ATTRIBUTE, extractMatrixVariables(request, uriVariables)); } if (!info.getProducesCondition().getProducibleMediaTypes().isEmpty()) { @@ -113,7 +113,9 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe return !getUrlPathHelper().shouldRemoveSemicolonContent(); } - private Map> extractMatrixVariables(Map uriVariables) { + private Map> extractMatrixVariables( + HttpServletRequest request, Map uriVariables) { + Map> result = new LinkedHashMap>(); for (Entry uriVar : uriVariables.entrySet()) { String uriVarValue = uriVar.getValue(); @@ -134,7 +136,8 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe uriVariables.put(uriVar.getKey(), uriVarValue.substring(0, semicolonIndex)); } - result.put(uriVar.getKey(), WebUtils.parseMatrixVariables(matrixVariables)); + MultiValueMap vars = WebUtils.parseMatrixVariables(matrixVariables); + result.put(uriVar.getKey(), getUrlPathHelper().decodeMatrixVariables(request, vars)); } return result; } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index e0764f7e7b..841318af71 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -310,48 +310,63 @@ public class RequestMappingInfoHandlerMappingTests { MultiValueMap matrixVariables; Map uriVariables; - String lookupPath = "/cars;colors=red,blue,green;year=2012"; - - // Pattern "/{cars}" : matrix variables stripped from "cars" variable - request = new MockHttpServletRequest(); - testHandleMatch(request, "/{cars}", lookupPath); + testHandleMatch(request, "/{cars}", "/cars;colors=red,blue,green;year=2012"); matrixVariables = getMatrixVariables(request, "cars"); + uriVariables = getUriTemplateVariables(request); + assertNotNull(matrixVariables); assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); assertEquals("2012", matrixVariables.getFirst("year")); - - uriVariables = getUriTemplateVariables(request); assertEquals("cars", uriVariables.get("cars")); - // Pattern "/{cars:[^;]+}{params}" : "cars" and "params" variables unchanged - request = new MockHttpServletRequest(); - testHandleMatch(request, "/{cars:[^;]+}{params}", lookupPath); + testHandleMatch(request, "/{cars:[^;]+}{params}", "/cars;colors=red,blue,green;year=2012"); matrixVariables = getMatrixVariables(request, "params"); + uriVariables = getUriTemplateVariables(request); + assertNotNull(matrixVariables); assertEquals(Arrays.asList("red", "blue", "green"), matrixVariables.get("colors")); assertEquals("2012", matrixVariables.getFirst("year")); - - uriVariables = getUriTemplateVariables(request); assertEquals("cars", uriVariables.get("cars")); assertEquals(";colors=red,blue,green;year=2012", uriVariables.get("params")); - // matrix variables not present : "params" variable is empty - request = new MockHttpServletRequest(); testHandleMatch(request, "/{cars:[^;]+}{params}", "/cars"); matrixVariables = getMatrixVariables(request, "params"); - assertNull(matrixVariables); - uriVariables = getUriTemplateVariables(request); + + assertNull(matrixVariables); assertEquals("cars", uriVariables.get("cars")); assertEquals("", uriVariables.get("params")); } + @Test + public void matrixVariablesDecoding() { + + MockHttpServletRequest request; + + UrlPathHelper urlPathHelper = new UrlPathHelper(); + urlPathHelper.setUrlDecode(false); + urlPathHelper.setRemoveSemicolonContent(false); + + this.handlerMapping.setUrlPathHelper(urlPathHelper ); + + request = new MockHttpServletRequest(); + testHandleMatch(request, "/path{filter}", "/path;mvar=a%2fb"); + + MultiValueMap matrixVariables = getMatrixVariables(request, "filter"); + Map uriVariables = getUriTemplateVariables(request); + + assertNotNull(matrixVariables); + assertEquals(Arrays.asList("a/b"), matrixVariables.get("mvar")); + assertEquals(";mvar=a/b", uriVariables.get("filter")); + } + + private void testHandleMatch(MockHttpServletRequest request, String pattern, String lookupPath) { PatternsRequestCondition patterns = new PatternsRequestCondition(pattern); RequestMappingInfo info = new RequestMappingInfo(patterns, null, null, null, null, null, null); From 2ac4a8c5411f8642ac2c40503678e5d7a4b56dbf Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 09:32:48 -0500 Subject: [PATCH 022/311] Update mvc chapter on annotations and proxies Issue: SPR-10132 --- src/reference/docbook/mvc.xml | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index 279a76ec15..f4d3e3e802 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -867,7 +867,10 @@ public class ClinicController { @Transactional methods). Usually you will introduce an interface for the controller in order to use JDK dynamic proxies. To make this work you must move the - @RequestMapping annotations to the + @RequestMapping annotations, as well as + any other type and method-level annotations (e.g. + @ModelAttribute, + @InitBinder) to the interface as well as the mapping mechanism can only "see" the interface exposed by the proxy. Alternatively, you could activate proxy-target-class="true" in the configuration for the @@ -876,6 +879,10 @@ public class ClinicController { that CGLIB-based subclass proxies should be used instead of interface-based JDK proxies. For more information on various proxying mechanisms see . + + Note however that method argument annotations, e.g. + @RequestParam, must be present in + the method signatures of the controller class.
From c7d0054a9e60b89a1cfbe184e9bbcb983f9231cb Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 09:36:19 -0500 Subject: [PATCH 023/311] Remove closing tag in form tag's extra hidden fields The fields returned from a RequestDataValueProcessor are now written as hidden fields without a closing tag. Before: After: Issue: SPR-10103 --- .../org/springframework/web/servlet/tags/form/FormTag.java | 4 ++-- .../springframework/web/servlet/tags/form/FormTagTests.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java index f827631d62..17e30d88d3 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java @@ -469,8 +469,8 @@ public class FormTag extends AbstractHtmlElementTag { if (hiddenFields != null) { for (String name : hiddenFields.keySet()) { this.tagWriter.appendValue(""); - this.tagWriter.appendValue("\n"); + this.tagWriter.appendValue("name=\"" + name + "\" value=\"" + hiddenFields.get(name) + "\" "); + this.tagWriter.appendValue("/>\n"); } } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index 3bd879a1ea..b22930686d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -293,7 +293,7 @@ public class FormTagTests extends AbstractHtmlElementTagTests { String output = getOutput(); - assertEquals("", getInputTag(output)); + assertEquals("", getInputTag(output)); assertFormTagOpened(output); assertFormTagClosed(output); From a56d8f28fe3c434d04d92ec6cd7ff60848cf8a2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arnaud=20Cogolu=C3=A8gnes?= Date: Fri, 14 Dec 2012 10:05:25 +0100 Subject: [PATCH 024/311] Add support for HTTP OPTIONS in Spring MVC Test Issue: SPR-10093 --- .../web/servlet/MockMvcBuilderSupport.java | 3 +- .../request/MockMvcRequestBuilders.java | 11 +++ .../servlet/setup/DefaultMockMvcBuilder.java | 16 +++- .../test/web/servlet/Spr10093Tests.java | 94 +++++++++++++++++++ 4 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java index 75a50db9df..c39e3dbee0 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java @@ -43,11 +43,12 @@ public abstract class MockMvcBuilderSupport { protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servletConfig, WebApplicationContext webAppContext, RequestBuilder defaultRequestBuilder, - List globalResultMatchers, List globalResultHandlers) { + List globalResultMatchers, List globalResultHandlers, Boolean dispatchOptions) { ServletContext servletContext = webAppContext.getServletContext(); TestDispatcherServlet dispatcherServlet = new TestDispatcherServlet(webAppContext); + dispatcherServlet.setDispatchOptionsRequest(dispatchOptions); try { dispatcherServlet.init(servletConfig); } diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java index da96fd9cd2..fbbc9b026d 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java @@ -80,6 +80,17 @@ public abstract class MockMvcRequestBuilders { return new MockHttpServletRequestBuilder(HttpMethod.DELETE, urlTemplate, urlVariables); } + /** + * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request. + * + * @param urlTemplate a URL template; the resulting URL will be encoded + * @param urlVariables zero or more URL variables + */ + public static MockHttpServletRequestBuilder options(String urlTemplate, Object... urlVariables) { + return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables); + } + + /** * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method. * diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java index a97b38aeee..984be0c854 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java @@ -31,6 +31,7 @@ import org.springframework.test.web.servlet.ResultHandler; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.util.Assert; import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; /** * An concrete implementation of {@link MockMvcBuilder} with methods for @@ -53,6 +54,8 @@ public class DefaultMockMvcBuilder extends MockMvcB private final List globalResultMatchers = new ArrayList(); private final List globalResultHandlers = new ArrayList(); + + private Boolean dispatchOptions = Boolean.FALSE; /** @@ -177,6 +180,17 @@ public class DefaultMockMvcBuilder extends MockMvcB this.globalResultHandlers.add(resultHandler); return (T) this; } + + /** + * Should the {@link DispatcherServlet} dispatch OPTIONS request to controllers. + * @param dispatchOptions + * @see {@link DispatcherServlet#setDispatchOptionsRequest(boolean)} + */ + @SuppressWarnings("unchecked") + public final T dispatchOptions(boolean dispatchOptions) { + this.dispatchOptions = dispatchOptions; + return (T) this; + } /** * Build a {@link MockMvc} instance. @@ -191,7 +205,7 @@ public class DefaultMockMvcBuilder extends MockMvcB Filter[] filterArray = this.filters.toArray(new Filter[this.filters.size()]); return super.createMockMvc(filterArray, mockServletConfig, this.webAppContext, - this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers); + this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers,this.dispatchOptions); } /** diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java new file mode 100644 index 0000000000..32713e951c --- /dev/null +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/Spr10093Tests.java @@ -0,0 +1,94 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.test.web.servlet; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Controller; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Tests for SPR-10093 (support for OPTIONS requests). + * @author Arnaud Cogoluègnes + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration +public class Spr10093Tests { + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = webAppContextSetup(this.wac).dispatchOptions(true).build(); + } + + @Test + public void test() throws Exception { + MyController controller = this.wac.getBean(MyController.class); + int initialCount = controller.counter.get(); + this.mockMvc.perform(options("/myUrl")).andExpect(status().isOk()); + + Assert.assertEquals(initialCount+1,controller.counter.get()); + } + + + @Configuration + @EnableWebMvc + static class WebConfig extends WebMvcConfigurerAdapter { + + @Bean + public MyController myController() { + return new MyController(); + } + } + + @Controller + private static class MyController { + + private AtomicInteger counter = new AtomicInteger(0); + + @RequestMapping(value="/myUrl",method=RequestMethod.OPTIONS) + @ResponseBody + public void handle() { + counter.incrementAndGet(); + } + } + + +} From 0829cbfdd3adc4459e47b6c4e1411dba796f964a Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 8 Jan 2013 16:23:46 +0100 Subject: [PATCH 025/311] Update license header for recently modified files Issue: SPR-7763, SPR-10140, SPR-10132, SPR-10093, SPR-10103 --- .../springframework/test/web/servlet/MockMvcBuilderSupport.java | 2 +- .../test/web/servlet/request/MockMvcRequestBuilders.java | 2 +- .../test/web/servlet/setup/DefaultMockMvcBuilder.java | 2 +- .../http/converter/BufferedImageHttpMessageConverter.java | 2 +- .../main/java/org/springframework/web/util/UrlPathHelper.java | 2 +- .../http/converter/BufferedImageHttpMessageConverterTests.java | 2 +- .../servlet/mvc/method/RequestMappingInfoHandlerMapping.java | 2 +- .../java/org/springframework/web/servlet/tags/form/FormTag.java | 2 +- .../mvc/method/RequestMappingInfoHandlerMappingTests.java | 2 +- .../org/springframework/web/servlet/tags/form/FormTagTests.java | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java index c39e3dbee0..d2e1054a63 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java index fbbc9b026d..bb0c109a09 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java index 984be0c854..19c50002de 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java index bd9f32d146..74c1772558 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/BufferedImageHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java index 72b592108a..7f98ee2369 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java +++ b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java index 6bfca8ae21..0dcb8703bf 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/BufferedImageHttpMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java index 7654d31498..e55ec1a3ca 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java index 17e30d88d3..d3b6752ade 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index 841318af71..1d9168926b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index b22930686d..23bacd5b94 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 24ffa5a706d1b8538ff1359c635905f0f9af9fb5 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 10:47:25 -0500 Subject: [PATCH 026/311] Update info on RestTemplate related to 401 status code Issue: SPR-9367 --- src/reference/docbook/remoting.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/reference/docbook/remoting.xml b/src/reference/docbook/remoting.xml index 4bd5acc920..f642f9d653 100644 --- a/src/reference/docbook/remoting.xml +++ b/src/reference/docbook/remoting.xml @@ -1401,6 +1401,12 @@ String result = can in turn be configured with credentials information or connection pooling functionality. + Note that the java.net implementation for + HTTP requests may raise an exception when accessing the status of a response + that represents an error (e.g. 401). If this is an issue, switch to + HttpComponentsClientHttpRequestFactory instead. + + The previous example using Apache HttpComponents HttpClient directly rewritten to use the RestTemplate is shown below From 68d4a70f8e7315d227b7727b087a65e64f4b0f9e Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 11:44:24 -0500 Subject: [PATCH 027/311] Add option to always append 'must-revalidate' Issue: SPR-9248 --- .../servlet/support/WebContentGenerator.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java index 7f759e8c97..ec1cf27cc3 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/WebContentGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,9 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.util.StringUtils; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.HttpSessionRequiredException; +import org.springframework.web.context.request.WebRequest; import org.springframework.web.context.support.WebApplicationObjectSupport; +import org.springframework.web.servlet.mvc.LastModified; /** * Convenient superclass for any kind of web content generator, @@ -79,6 +81,8 @@ public abstract class WebContentGenerator extends WebApplicationObjectSupport { private int cacheSeconds = -1; + private boolean alwaysMustRevalidate = false; + /** * Create a new WebContentGenerator which supports @@ -194,6 +198,25 @@ public abstract class WebContentGenerator extends WebApplicationObjectSupport { return this.useCacheControlNoStore; } + /** + * An option to add 'must-revalidate' to every Cache-Control header. This + * may be useful with annotated controller methods, which can + * programmatically do a lastModified calculation as described in + * {@link WebRequest#checkNotModified(long)}. Default is "false", + * effectively relying on whether the handler implements + * {@link LastModified} or not. + */ + public void setAlwaysMustRevalidate(boolean mustRevalidate) { + this.alwaysMustRevalidate = mustRevalidate; + } + + /** + * Return whether 'must-revaliate' is added to every Cache-Control header. + */ + public boolean isAlwaysMustRevalidate() { + return alwaysMustRevalidate; + } + /** * Cache content for the given number of seconds. Default is -1, * indicating no generation of cache-related headers. @@ -313,7 +336,7 @@ public abstract class WebContentGenerator extends WebApplicationObjectSupport { if (this.useCacheControlHeader) { // HTTP 1.1 header String headerValue = "max-age=" + seconds; - if (mustRevalidate) { + if (mustRevalidate || this.alwaysMustRevalidate) { headerValue += ", must-revalidate"; } response.setHeader(HEADER_CACHE_CONTROL, headerValue); From f185c3a3c18f11770494060182780af61a8c9e55 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 8 Jan 2013 12:03:51 -0500 Subject: [PATCH 028/311] Add option to not trim path segments in AntPathMatch Issue: SPR-8687 --- .../org/springframework/util/AntPathMatcher.java | 16 +++++++++++----- .../util/AntPathMatcherTests.java | 10 +++++++++- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java b/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java index bbceda14dc..0ae86e0879 100644 --- a/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java +++ b/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -60,12 +60,18 @@ public class AntPathMatcher implements PathMatcher { private final Map stringMatcherCache = new ConcurrentHashMap(256); + private boolean trimTokens = true; + /** Set the path separator to use for pattern parsing. Default is "/", as in Ant. */ public void setPathSeparator(String pathSeparator) { this.pathSeparator = (pathSeparator != null ? pathSeparator : DEFAULT_PATH_SEPARATOR); } + /** Whether to trim tokenized paths and patterns. */ + public void setTrimTokens(boolean trimTokens) { + this.trimTokens = trimTokens; + } public boolean isPattern(String path) { return (path.indexOf('*') != -1 || path.indexOf('?') != -1); @@ -95,8 +101,8 @@ public class AntPathMatcher implements PathMatcher { return false; } - String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator); - String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator); + String[] pattDirs = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator, this.trimTokens, true); + String[] pathDirs = StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); int pattIdxStart = 0; int pattIdxEnd = pattDirs.length - 1; @@ -246,8 +252,8 @@ public class AntPathMatcher implements PathMatcher { * does not enforce this. */ public String extractPathWithinPattern(String pattern, String path) { - String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator); - String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator); + String[] patternParts = StringUtils.tokenizeToStringArray(pattern, this.pathSeparator, this.trimTokens, true); + String[] pathParts = StringUtils.tokenizeToStringArray(path, this.pathSeparator, this.trimTokens, true); StringBuilder builder = new StringBuilder(); diff --git a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java index e960a62ea6..0a34e1c470 100644 --- a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java +++ b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -542,6 +542,14 @@ public class AntPathMatcherTests { paths.clear(); } + // SPR-8687 + @Test + public void trimTokensOff() { + pathMatcher.setTrimTokens(false); + + assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/sales/members")); + assertTrue(pathMatcher.match("/group/{groupName}/members", "/group/ sales/members")); + } } From 2f6e45ff0615ec98114025eb3b78db8ab963d029 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Wed, 9 Jan 2013 05:44:23 -0500 Subject: [PATCH 029/311] Add protected method to AbstractHandlerMethodMapping --- .../handler/AbstractHandlerMethodMapping.java | 38 ++++++++++++------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java index 28fbe1efbc..c8f11c8175 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java @@ -165,25 +165,17 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap * under the same mapping */ protected void registerHandlerMethod(Object handler, Method method, T mapping) { - HandlerMethod handlerMethod; - if (handler instanceof String) { - String beanName = (String) handler; - handlerMethod = new HandlerMethod(beanName, getApplicationContext(), method); - } - else { - handlerMethod = new HandlerMethod(handler, method); - } - + HandlerMethod newHandlerMethod = createHandlerMethod(handler, method); HandlerMethod oldHandlerMethod = handlerMethods.get(mapping); - if (oldHandlerMethod != null && !oldHandlerMethod.equals(handlerMethod)) { - throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + handlerMethod.getBean() - + "' bean method \n" + handlerMethod + "\nto " + mapping + ": There is already '" + if (oldHandlerMethod != null && !oldHandlerMethod.equals(newHandlerMethod)) { + throw new IllegalStateException("Ambiguous mapping found. Cannot map '" + newHandlerMethod.getBean() + + "' bean method \n" + newHandlerMethod + "\nto " + mapping + ": There is already '" + oldHandlerMethod.getBean() + "' bean method\n" + oldHandlerMethod + " mapped."); } - this.handlerMethods.put(mapping, handlerMethod); + this.handlerMethods.put(mapping, newHandlerMethod); if (logger.isInfoEnabled()) { - logger.info("Mapped \"" + mapping + "\" onto " + handlerMethod); + logger.info("Mapped \"" + mapping + "\" onto " + newHandlerMethod); } Set patterns = getMappingPathPatterns(mapping); @@ -194,6 +186,24 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap } } + /** + * Create the HandlerMethod instance. + * @param handler either a bean name or an actual handler instance + * @param method the target method + * @return the created HandlerMethod + */ + protected HandlerMethod createHandlerMethod(Object handler, Method method) { + HandlerMethod handlerMethod; + if (handler instanceof String) { + String beanName = (String) handler; + handlerMethod = new HandlerMethod(beanName, getApplicationContext(), method); + } + else { + handlerMethod = new HandlerMethod(handler, method); + } + return handlerMethod; + } + /** * Extract and return the URL paths contained in a mapping. */ From ee1ddc90ecc0b8013757d332a299dd3b8c41bd84 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 9 Jan 2013 17:42:12 -0800 Subject: [PATCH 030/311] Replace EasyMock with Mockito in spring-orm Issue: SPR-10126 --- build.gradle | 2 +- .../hibernate3/HibernateInterceptorTests.java | 556 ++-- .../HibernateJtaTransactionTests.java | 1180 +++----- .../hibernate3/HibernateTemplateTests.java | 2404 +++++------------ .../HibernateTransactionManagerTests.java | 1216 +++------ .../LocalSessionFactoryBeanTests.java | 48 +- .../support/HibernateDaoSupportTests.java | 19 +- .../orm/hibernate3/support/LobTypeTests.java | 342 +-- .../support/OpenSessionInViewTests.java | 383 +-- .../orm/ibatis/SqlMapClientTests.java | 276 +- .../ibatis/support/LobTypeHandlerTests.java | 136 +- .../orm/jdo/JdoInterceptorTests.java | 43 +- .../orm/jdo/JdoTemplateTests.java | 540 ++-- .../orm/jdo/JdoTransactionManagerTests.java | 746 ++--- .../LocalPersistenceManagerFactoryTests.java | 24 +- .../orm/jdo/support/JdoDaoSupportTests.java | 20 +- .../OpenPersistenceManagerInViewTests.java | 80 +- ...AbstractEntityManagerFactoryBeanTests.java | 39 +- .../orm/jpa/DefaultJpaDialectTests.java | 46 +- .../EntityManagerFactoryBeanSupportTests.java | 18 +- .../jpa/EntityManagerFactoryUtilsTests.java | 40 +- .../orm/jpa/JpaInterceptorTests.java | 124 +- .../orm/jpa/JpaTemplateTests.java | 262 +- .../orm/jpa/JpaTransactionManagerTests.java | 490 +--- ...ontainerEntityManagerFactoryBeanTests.java | 164 +- .../LocalEntityManagerFactoryBeanTests.java | 24 +- .../orm/jpa/support/JpaDaoSupportTests.java | 30 +- .../support/OpenEntityManagerInViewTests.java | 157 +- .../support/PersistenceInjectionTests.java | 206 +- .../SharedEntityManagerFactoryTests.java | 38 +- 30 files changed, 3017 insertions(+), 6636 deletions(-) diff --git a/build.gradle b/build.gradle index 8c0a1b4245..02af542134 100644 --- a/build.gradle +++ b/build.gradle @@ -71,7 +71,7 @@ configure(allprojects) { project -> testCompile("junit:junit:${junitVersion}") testCompile("org.hamcrest:hamcrest-all:1.3") testCompile("org.mockito:mockito-core:1.9.5") - if (project.name in ["spring", "spring-jms", "spring-orm", + if (project.name in ["spring", "spring-jms", "spring-orm-hibernate4", "spring-oxm", "spring-struts", "spring-test", "spring-test-mvc", "spring-tx", "spring-web", "spring-webmvc", "spring-webmvc-portlet", "spring-webmvc-tiles3"]) { diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java index ba1415f640..498005295e 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,389 +16,293 @@ package org.springframework.orm.hibernate3; -import java.lang.reflect.AccessibleObject; -import java.lang.reflect.Method; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import java.sql.SQLException; -import junit.framework.TestCase; -import org.aopalliance.intercept.Interceptor; -import org.aopalliance.intercept.Invocation; import org.aopalliance.intercept.MethodInvocation; -import org.easymock.MockControl; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.hibernate.exception.ConstraintViolationException; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.beans.factory.BeanFactory; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -public class HibernateInterceptorTests extends TestCase { +public class HibernateInterceptorTests { + private SessionFactory sessionFactory; + private Session session; + private MethodInvocation invocation; + + @Before + public void setUp() throws Throwable { + this.sessionFactory = mock(SessionFactory.class); + this.session = mock(Session.class); + this.invocation = mock(MethodInvocation.class); + given(sessionFactory.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sessionFactory); + given(invocation.proceed()).willAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + if (!TransactionSynchronizationManager.hasResource(sessionFactory)) { + throw new IllegalStateException("Session not bound"); + } + return null; + } + }); + } + + @After + public void tearDown() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + } + + @Test public void testInterceptorWithNewSession() throws HibernateException { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testInterceptorWithNewSessionAndFlushNever() throws HibernateException { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setFlushModeName("FLUSH_NEVER"); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } - - sfControl.verify(); - sessionControl.verify(); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session, never()).flush(); + verify(session).close(); } + @Test public void testInterceptorWithNewSessionAndFilter() throws HibernateException { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setFilterName("myFilter"); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testInterceptorWithThreadBound() { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + verify(session, never()).flush(); + verify(session, never()).close(); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - - sfControl.verify(); - sessionControl.verify(); } + @Test public void testInterceptorWithThreadBoundAndFlushEager() throws HibernateException { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); } + @Test public void testInterceptorWithThreadBoundAndFlushEagerSwitch() throws HibernateException { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.NEVER, 1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.NEVER); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.NEVER); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).flush(); + ordered.verify(session).setFlushMode(FlushMode.NEVER); } + @Test public void testInterceptorWithThreadBoundAndFlushCommit() { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.setFlushMode(FlushMode.COMMIT); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setFlushMode(HibernateInterceptor.FLUSH_COMMIT); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.COMMIT); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + verify(session, never()).flush(); } + @Test public void testInterceptorWithThreadBoundAndFlushAlways() { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.setFlushMode(FlushMode.ALWAYS); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setFlushMode(HibernateInterceptor.FLUSH_ALWAYS); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.ALWAYS); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + verify(session, never()).flush(); } + @Test public void testInterceptorWithThreadBoundAndFilter() { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.disableFilter("myFilter"); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setFilterName("myFilter"); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).enableFilter("myFilter"); + ordered.verify(session).disableFilter("myFilter"); } + @Test public void testInterceptorWithThreadBoundAndFilters() { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.enableFilter("yourFilter"); - sessionControl.setReturnValue(null, 1); - session.disableFilter("myFilter"); - sessionControl.setVoidCallable(1); - session.disableFilter("yourFilter"); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setFilterNames(new String[] {"myFilter", "yourFilter"}); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).enableFilter("myFilter"); + ordered.verify(session).enableFilter("yourFilter"); + ordered.verify(session).disableFilter("myFilter"); + ordered.verify(session).disableFilter("yourFilter"); } + @Test public void testInterceptorWithFlushFailure() throws Throwable { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); SQLException sqlEx = new SQLException("argh", "27"); - session.flush(); ConstraintViolationException jdbcEx = new ConstraintViolationException("", sqlEx, null); - sessionControl.setThrowable(jdbcEx, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); + willThrow(jdbcEx).given(session).flush(); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); fail("Should have thrown DataIntegrityViolationException"); } catch (DataIntegrityViolationException ex) { @@ -406,204 +310,72 @@ public class HibernateInterceptorTests extends TestCase { assertEquals(jdbcEx, ex.getCause()); } - sfControl.verify(); - sessionControl.verify(); + verify(session).close(); } + @Test public void testInterceptorWithThreadBoundEmptyHolder() { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - SessionHolder holder = new SessionHolder("key", session); holder.removeSession("key"); - TransactionSynchronizationManager.bindResource(sf, holder); + TransactionSynchronizationManager.bindResource(sessionFactory, holder); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testInterceptorWithEntityInterceptor() throws HibernateException { - MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); - org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock(); - interceptorControl.replay(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(entityInterceptor); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); + org.hibernate.Interceptor entityInterceptor = mock(org.hibernate.Interceptor.class); + given(sessionFactory.openSession(entityInterceptor)).willReturn(session); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setEntityInterceptor(entityInterceptor); try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } - interceptorControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testInterceptorWithEntityInterceptorBeanName() throws HibernateException { - MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); - org.hibernate.Interceptor entityInterceptor = (org.hibernate.Interceptor) interceptorControl.getMock(); - interceptorControl.replay(); - MockControl interceptor2Control = MockControl.createControl(org.hibernate.Interceptor.class); - org.hibernate.Interceptor entityInterceptor2 = (org.hibernate.Interceptor) interceptor2Control.getMock(); - interceptor2Control.replay(); + org.hibernate.Interceptor entityInterceptor = mock(org.hibernate.Interceptor.class); + org.hibernate.Interceptor entityInterceptor2 = mock(org.hibernate.Interceptor.class); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(entityInterceptor); - sfControl.setReturnValue(session, 1); - sf.openSession(entityInterceptor2); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 2); - session.flush(); - sessionControl.setVoidCallable(2); - session.close(); - sessionControl.setReturnValue(null, 2); - sfControl.replay(); - sessionControl.replay(); + given(sessionFactory.openSession(entityInterceptor)).willReturn(session); + given(sessionFactory.openSession(entityInterceptor2)).willReturn(session); - MockControl beanFactoryControl = MockControl.createControl(BeanFactory.class); - BeanFactory beanFactory = (BeanFactory) beanFactoryControl.getMock(); - beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class); - beanFactoryControl.setReturnValue(entityInterceptor, 1); - beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class); - beanFactoryControl.setReturnValue(entityInterceptor2, 1); - beanFactoryControl.replay(); + BeanFactory beanFactory = mock(BeanFactory.class); + given(beanFactory.getBean("entityInterceptor", org.hibernate.Interceptor.class)).willReturn( + entityInterceptor, entityInterceptor2); HibernateInterceptor interceptor = new HibernateInterceptor(); - interceptor.setSessionFactory(sf); + interceptor.setSessionFactory(sessionFactory); interceptor.setEntityInterceptorBeanName("entityInterceptor"); interceptor.setBeanFactory(beanFactory); for (int i = 0; i < 2; i++) { try { - interceptor.invoke(new TestInvocation(sf)); + interceptor.invoke(invocation); } catch (Throwable t) { fail("Should not have thrown Throwable: " + t.getMessage()); } } - interceptorControl.verify(); - interceptor2Control.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(session, times(2)).flush(); + verify(session, times(2)).close(); } - - @Override - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - - - private static class TestInvocation implements MethodInvocation { - - private SessionFactory sessionFactory; - - public TestInvocation(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; - } - - @Override - public Object proceed() throws Throwable { - if (!TransactionSynchronizationManager.hasResource(this.sessionFactory)) { - throw new IllegalStateException("Session not bound"); - } - return null; - } - - public int getCurrentInterceptorIndex() { - return 0; - } - - public int getNumberOfInterceptors() { - return 0; - } - - public Interceptor getInterceptor(int i) { - return null; - } - - @Override - public Method getMethod() { - return null; - } - - @Override - public AccessibleObject getStaticPart() { - return null; - } - - public Object getArgument(int i) { - return null; - } - - @Override - public Object[] getArguments() { - return null; - } - - public void setArgument(int i, Object handler) { - } - - public int getArgumentCount() { - return 0; - } - - @Override - public Object getThis() { - return null; - } - - public Object getProxy() { - return null; - } - - public Invocation cloneInstance() { - return null; - } - - public void release() { - } - } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java index 53d8210928..6f5ef6d62d 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateJtaTransactionTests.java @@ -21,6 +21,14 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willDoNothing; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.List; @@ -32,7 +40,6 @@ import javax.transaction.SystemException; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; -import org.easymock.MockControl; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Query; @@ -40,7 +47,9 @@ import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.hibernate.engine.SessionFactoryImplementor; import org.hibernate.engine.SessionImplementor; +import org.junit.After; import org.junit.Test; +import org.mockito.InOrder; import org.springframework.dao.DataAccessException; import org.springframework.tests.transaction.MockJtaTransaction; import org.springframework.transaction.TransactionDefinition; @@ -55,11 +64,19 @@ import org.springframework.transaction.support.TransactionTemplate; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -@SuppressWarnings("deprecation") public class HibernateJtaTransactionTests { + @After + public void tearDown() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + } + @Test public void testJtaTransactionCommit() throws Exception { doTestJtaTransactionCommit(Status.STATUS_NO_TRANSACTION, false); @@ -82,51 +99,25 @@ public class HibernateJtaTransactionTests { @SuppressWarnings({ "rawtypes", "unchecked" }) private void doTestJtaTransactionCommit(int status, final boolean readOnly) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - final MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - ut.getStatus(); - utControl.setReturnValue(status, 1); + UserTransaction ut = mock(UserTransaction.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Query query = mock(Query.class); if (status == Status.STATUS_NO_TRANSACTION) { - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.commit(); - utControl.setVoidCallable(1); + given(ut.getStatus()).willReturn(status, Status.STATUS_ACTIVE); } else { - ut.getStatus(); - utControl.setReturnValue(status, 1); + given(ut.getStatus()).willReturn(status); } final List list = new ArrayList(); list.add("test"); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - if (readOnly) { - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - } - query.list(); - queryControl.setReturnValue(list, 1); - - utControl.replay(); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.isOpen()).willReturn(true); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); JtaTransactionManager ptm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -163,18 +154,6 @@ public class HibernateJtaTransactionTests { } }); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); - sessionControl.verify(); - queryControl.verify(); - sessionControl.reset(); - if (!readOnly) { - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - } - session.close(); - sessionControl.setReturnValue(null, 1); - sessionControl.replay(); return htl; } catch (Error err) { @@ -188,9 +167,18 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - sfControl.verify(); - sessionControl.verify(); + if (status == Status.STATUS_NO_TRANSACTION) { + InOrder ordered = inOrder(ut); + ordered.verify(ut).begin(); + ordered.verify(ut).commit(); + } + + if (readOnly) { + verify(session).setFlushMode(FlushMode.MANUAL); + } else { + verify(session).flush(); + } + verify(session).close(); } @Test @@ -205,40 +193,24 @@ public class HibernateJtaTransactionTests { @SuppressWarnings({ "rawtypes", "unchecked" }) private void doTestJtaTransactionCommitWithJtaTm(int status) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(status, 2); + + UserTransaction ut = mock(UserTransaction.class); if (status == Status.STATUS_NO_TRANSACTION) { - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.commit(); - utControl.setVoidCallable(1); + given(ut.getStatus()).willReturn(status, status, Status.STATUS_ACTIVE); + } else { + given(ut.getStatus()).willReturn(status); } - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); + given(tm.getTransaction()).willReturn(transaction); - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 1); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - - utControl.replay(); - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.getTransactionManager()).willReturn(tm); + given(sf.openSession()).willReturn(session); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); JtaTransactionManager ptm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -278,15 +250,6 @@ public class HibernateJtaTransactionTests { } }); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); - sessionControl.verify(); - sessionControl.reset(); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sessionControl.replay(); return htl; } catch (Error err) { @@ -300,38 +263,28 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - sfControl.verify(); - sessionControl.verify(); + if (status == Status.STATUS_NO_TRANSACTION) { + InOrder ordered = inOrder(ut); + ordered.verify(ut).begin(); + ordered.verify(ut).commit(); + } + verify(session).flush(); + verify(session).close(); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testJtaTransactionWithFlushFailure() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - sfControl.replay(); - sessionControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); + + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); JtaTransactionManager ptm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -340,6 +293,7 @@ public class HibernateJtaTransactionTests { final HibernateException flushEx = new HibernateException("flush failure"); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + willThrow(flushEx).given(session).flush(); try { tt.execute(new TransactionCallback() { @@ -373,15 +327,6 @@ public class HibernateJtaTransactionTests { } }); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); - sessionControl.verify(); - sessionControl.reset(); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setThrowable(flushEx); - session.close(); - sessionControl.setReturnValue(null, 1); - sessionControl.replay(); return htl; } catch (Error err) { @@ -399,9 +344,9 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(ut).begin(); + verify(ut).rollback(); + verify(session).close(); } @Test @@ -416,32 +361,14 @@ public class HibernateJtaTransactionTests { @SuppressWarnings({ "rawtypes", "unchecked" }) private void doTestJtaTransactionRollback(final boolean flush) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - if (flush) { - session.flush(); - sessionControl.setVoidCallable(1); - } - sfControl.replay(); - sessionControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); + + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); JtaTransactionManager ptm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -450,7 +377,6 @@ public class HibernateJtaTransactionTests { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); Object result = tt.execute(new TransactionCallback() { - @Override public Object doInTransaction(TransactionStatus status) { try { @@ -468,11 +394,6 @@ public class HibernateJtaTransactionTests { status.flush(); } status.setRollbackOnly(); - sessionControl.verify(); - sessionControl.reset(); - session.close(); - sessionControl.setReturnValue(null, 1); - sessionControl.replay(); return htl; } catch (Error err) { @@ -482,11 +403,15 @@ public class HibernateJtaTransactionTests { } }); assertTrue("Correct result list", result == l); - assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - sfControl.verify(); - sessionControl.verify(); + + InOrder ordered = inOrder(ut); + ordered.verify(ut).begin(); + ordered.verify(ut).rollback(); + if (flush) { + verify(session).flush(); + } + verify(session).close(); } @Test @@ -533,49 +458,22 @@ public class HibernateJtaTransactionTests { protected void doTestJtaTransactionCommitWithPreBound(boolean jtaTm, final boolean flushNever, final boolean readOnly) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.commit(); - utControl.setVoidCallable(1); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + + TransactionManager tm = mock(TransactionManager.class); if (jtaTm) { MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getTransaction()).willReturn(transaction); } - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(ExtendedSession.class); - final ExtendedSession session = (ExtendedSession) sessionControl.getMock(); - sf.getTransactionManager(); - sfControl.setReturnValue((jtaTm ? tm : null), 1); - session.isOpen(); - sessionControl.setReturnValue(true, 5); - session.getFlushMode(); - if (flushNever) { - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - if (!readOnly) { - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - } - } - else { - sessionControl.setReturnValue(FlushMode.AUTO, 1); - } - - utControl.replay(); - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final ExtendedSession session = mock(ExtendedSession.class); + given(sf.getTransactionManager()).willReturn(jtaTm ? tm : null); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(flushNever ? FlushMode.MANUAL: FlushMode.AUTO); TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); try { @@ -610,23 +508,6 @@ public class HibernateJtaTransactionTests { }); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); } - sessionControl.verify(); - sessionControl.reset(); - if (!readOnly) { - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - if (flushNever) { - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - } - } - session.afterTransactionCompletion(true, null); - sessionControl.setVoidCallable(1); - session.disconnect(); - sessionControl.setReturnValue(null, 1); - sessionControl.replay(); return htl; } catch (Error err) { @@ -644,44 +525,40 @@ public class HibernateJtaTransactionTests { TransactionSynchronizationManager.unbindResource(sf); } - utControl.verify(); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(ut).begin(); + verify(ut).commit(); + + if (flushNever) { + if(!readOnly) { + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + } + } + if(!flushNever && !readOnly) { + verify(session).flush(); + } + verify(session).afterTransactionCompletion(true, null); + verify(session).disconnect(); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testJtaTransactionRollbackWithPreBound() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_MARKED_ROLLBACK, 2); - ut.begin(); - utControl.setVoidCallable(1); - ut.setRollbackOnly(); - utControl.setVoidCallable(1); - RollbackException rex = new RollbackException(); - ut.commit(); - utControl.setThrowable(rex, 1); - utControl.replay(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 5); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - sfControl.replay(); - sessionControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, + Status.STATUS_MARKED_ROLLBACK, Status.STATUS_MARKED_ROLLBACK); + RollbackException rex = new RollbackException(); + willThrow(rex).given(ut).commit(); + + final SessionFactory sf = mock(SessionFactory.class); + + final Session session = mock(Session.class); + given(session.getSessionFactory()).willReturn(sf); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); try { @@ -718,17 +595,6 @@ public class HibernateJtaTransactionTests { }); assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); } - sessionControl.verify(); - sessionControl.reset(); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.disconnect(); - sessionControl.setReturnValue(null, 1); - session.clear(); - sessionControl.setVoidCallable(1); - sessionControl.replay(); } catch (Error err) { err.printStackTrace(); @@ -748,9 +614,11 @@ public class HibernateJtaTransactionTests { TransactionSynchronizationManager.unbindResource(sf); } - utControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(ut).begin(); + verify(ut).setRollbackOnly(); + verify(session).flush(); + verify(session).disconnect(); + verify(session).clear(); } @Test @@ -765,75 +633,29 @@ public class HibernateJtaTransactionTests { @SuppressWarnings({ "rawtypes", "unchecked" }) protected void doTestJtaTransactionWithRequiresNew(final boolean rollback) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl tx1Control = MockControl.createControl(javax.transaction.Transaction.class); - javax.transaction.Transaction tx1 = (javax.transaction.Transaction) tx1Control.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(Session.class); - final Session session1 = (Session) session1Control.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.begin(); - utControl.setVoidCallable(2); - tm.suspend(); - tmControl.setReturnValue(tx1, 1); - tm.resume(tx1); - tmControl.setVoidCallable(1); - if (rollback) { - ut.rollback(); - } - else { - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.commit(); - } - utControl.setVoidCallable(2); + UserTransaction ut = mock(UserTransaction.class); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - sf.openSession(); - sfControl.setReturnValue(session2, 1); - session1.getSessionFactory(); - session1Control.setReturnValue(sf, 1); - session2.getSessionFactory(); - session2Control.setReturnValue(sf, 1); - session1.isOpen(); - session1Control.setReturnValue(true, 1); - session2.isOpen(); - session2Control.setReturnValue(true, 1); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); + TransactionManager tm = mock(TransactionManager.class); + javax.transaction.Transaction tx1 = mock(javax.transaction.Transaction.class); + + final SessionFactory sf = mock(SessionFactory.class); + final Session session1 = mock(Session.class); + final Session session2 = mock(Session.class); + + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + given(tm.suspend()).willReturn(tx1); + given(sf.openSession()).willReturn(session1, session2); + given(session1.getSessionFactory()).willReturn(sf); + given(session2.getSessionFactory()).willReturn(sf); + given(session1.isOpen()).willReturn(true); + given(session2.isOpen()).willReturn(true); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); if (!rollback) { - session1.getFlushMode(); - session1Control.setReturnValue(FlushMode.AUTO, 1); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); - session1.flush(); - session1Control.setVoidCallable(1); - session2.flush(); - session2Control.setVoidCallable(2); + given(session1.getFlushMode()).willReturn(FlushMode.AUTO); } - session1.disconnect(); - session1Control.setReturnValue(null, 1); - session1.close(); - session1Control.setReturnValue(null, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - - utControl.replay(); - tmControl.replay(); - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); JtaTransactionManager ptm = new JtaTransactionManager(); ptm.setUserTransaction(ut); @@ -893,11 +715,21 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); } - utControl.verify(); - tmControl.verify(); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); + verify(ut, times(2)).begin(); + verify(tm).resume(tx1); + if (rollback) { + verify(ut, times(2)).rollback(); + } + else { + verify(ut, times(2)).commit(); + } + verify(session1).disconnect(); + verify(session1).close(); + if(!rollback) { + verify(session1).flush(); + verify(session2, atLeastOnce()).flush(); + } + verify(session2).close(); } @Test @@ -912,51 +744,26 @@ public class HibernateJtaTransactionTests { @SuppressWarnings({ "rawtypes", "unchecked" }) protected void doTestJtaTransactionWithRequiresNewAndException(boolean suspendException) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl txControl = MockControl.createControl(javax.transaction.Transaction.class); - javax.transaction.Transaction tx = (javax.transaction.Transaction) txControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(Session.class); - final Session session1 = (Session) session1Control.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.begin(); - utControl.setVoidCallable(1); + UserTransaction ut = mock(UserTransaction.class); + + TransactionManager tm = mock(TransactionManager.class); + javax.transaction.Transaction tx = mock(javax.transaction.Transaction.class); + + final SessionFactory sf = mock(SessionFactory.class); + final Session session1 = mock(Session.class); + + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); if (suspendException) { - tm.suspend(); - tmControl.setThrowable(new SystemException(), 1); + given(tm.suspend()).willThrow(new SystemException()); } else { - tm.suspend(); - tmControl.setReturnValue(tx, 1); - ut.begin(); - utControl.setThrowable(new SystemException(), 1); - tm.resume(tx); - tmControl.setVoidCallable(1); + given(tm.suspend()).willReturn(tx); + willDoNothing().willThrow(new SystemException()).given(ut).begin(); } - ut.rollback(); - utControl.setVoidCallable(1); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - session1.getSessionFactory(); - session1Control.setReturnValue(sf, 1); - session1.disconnect(); - session1Control.setReturnValue(null, 1); - session1.close(); - session1Control.setReturnValue(null, 1); - - utControl.replay(); - tmControl.replay(); - sfControl.replay(); - session1Control.replay(); + given(sf.openSession()).willReturn(session1); + given(session1.getSessionFactory()).willReturn(sf); JtaTransactionManager ptm = new JtaTransactionManager(); ptm.setUserTransaction(ut); @@ -993,10 +800,13 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); } - utControl.verify(); - tmControl.verify(); - sfControl.verify(); - session1Control.verify(); + verify(ut, atLeastOnce()).begin(); + if(!suspendException) { + verify(tm).resume(tx); + } + verify(ut).rollback(); + verify(session1).disconnect(); + verify(session1).close(); } @Test @@ -1011,79 +821,30 @@ public class HibernateJtaTransactionTests { @SuppressWarnings({ "rawtypes", "unchecked" }) protected void doTestJtaTransactionWithRequiresNewAndJtaTm(final boolean rollback) throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockControl tx1Control = MockControl.createControl(javax.transaction.Transaction.class); - javax.transaction.Transaction tx1 = (javax.transaction.Transaction) tx1Control.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(Session.class); - final Session session1 = (Session) session1Control.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); + + UserTransaction ut = mock(UserTransaction.class); + + TransactionManager tm = mock(TransactionManager.class); + javax.transaction.Transaction tx1 = mock(javax.transaction.Transaction.class); + + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session1 = mock(Session.class); + final Session session2 = mock(Session.class); MockJtaTransaction transaction1 = new MockJtaTransaction(); MockJtaTransaction transaction2 = new MockJtaTransaction(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 3); - ut.begin(); - utControl.setVoidCallable(2); - tm.getTransaction(); - tmControl.setReturnValue(transaction1, 1); - tm.suspend(); - tmControl.setReturnValue(tx1, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction2, 1); - tm.resume(tx1); - tmControl.setVoidCallable(1); - if (rollback) { - ut.rollback(); - } - else { - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.commit(); - } - utControl.setVoidCallable(2); - - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 2); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - sf.openSession(); - sfControl.setReturnValue(session2, 1); - session1.isOpen(); - session1Control.setReturnValue(true, 1); - session2.isOpen(); - session2Control.setReturnValue(true, 1); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); - if (!rollback) { - session1.getFlushMode(); - session1Control.setReturnValue(FlushMode.AUTO, 1); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); - session1.flush(); - session1Control.setVoidCallable(1); - session2.flush(); - session2Control.setVoidCallable(2); - } - session1.disconnect(); - session1Control.setReturnValue(null, 1); - session1.close(); - session1Control.setReturnValue(null, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - - utControl.replay(); - tmControl.replay(); - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction1); + given(tm.suspend()).willReturn(tx1); + given(tm.getTransaction()).willReturn(transaction2); + given(sf.getTransactionManager()).willReturn(tm); + given(sf.openSession()).willReturn(session1, session2); + given(session1.isOpen()).willReturn(true); + given(session2.isOpen()).willReturn(true); + given(session1.getFlushMode()).willReturn(FlushMode.AUTO); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); JtaTransactionManager ptm = new JtaTransactionManager(); ptm.setUserTransaction(ut); @@ -1143,51 +904,34 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); } - utControl.verify(); - tmControl.verify(); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); + verify(ut, times(2)).begin(); + verify(tm).resume(tx1); + if (rollback) { + verify(ut, times(2)).rollback(); + } + else { + verify(ut, times(2)).commit(); + verify(session1).flush(); + verify(session2, times(2)).flush(); + } + verify(session1).disconnect(); + verify(session1).close(); + verify(session2).close(); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testTransactionWithPropagationSupports() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); JtaTransactionManager tm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(tm); @@ -1217,44 +961,27 @@ public class HibernateJtaTransactionTests { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).flush(); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + ordered.verify(session).close(); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void testTransactionWithPropagationSupportsAndInnerTransaction() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - ut.rollback(); - utControl.setVoidCallable(1); - utControl.replay(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 3); - session.flush(); - sessionControl.setVoidCallable(3); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); JtaTransactionManager tm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(tm); @@ -1304,40 +1031,23 @@ public class HibernateJtaTransactionTests { } }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - - sfControl.verify(); - sessionControl.verify(); + verify(session, times(3)).flush(); + verify(session).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronization() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 4); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + given(tm.getTransaction()).willReturn(transaction); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); HibernateTemplate ht = new HibernateTemplate(sf); @@ -1362,36 +1072,22 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); + verify(session).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithRollback() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 4); - session.close(); - sessionControl.setReturnValue(null, 1); - - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + given(tm.getTransaction()).willReturn(transaction); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); HibernateTemplate ht = new HibernateTemplate(sf); @@ -1415,40 +1111,22 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(session).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithRollbackByOtherThread() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 7); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 2); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 7); - session.isOpen(); - sessionControl.setReturnValue(true, 8); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 2); - - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + given(tm.getTransaction()).willReturn(transaction); + given(tm.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); final HibernateTemplate ht = new HibernateTemplate(sf); @@ -1505,43 +1183,25 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session, times(2)).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithFlushFailure() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - tm.setRollbackOnly(); - tmControl.setVoidCallable(1); - + given(tm.getTransaction()).willReturn(transaction); final HibernateException flushEx = new HibernateException("flush failure"); - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 4); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setThrowable(flushEx, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + willThrow(flushEx).given(session).flush(); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); HibernateTemplate ht = new HibernateTemplate(sf); @@ -1572,52 +1232,27 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(tm).setRollbackOnly(); + verify(session).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithSuspendedTransaction() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction1 = new MockJtaTransaction(); MockJtaTransaction transaction2 = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction1, 2); - tm.getTransaction(); - tmControl.setReturnValue(transaction2, 3); + given(tm.getTransaction()).willReturn(transaction1, transaction1, transaction2, transaction2, + transaction2); - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl session1Control = MockControl.createControl(Session.class); - final Session session1 = (Session) session1Control.getMock(); - final MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - sf.openSession(); - sfControl.setReturnValue(session2, 1); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 5); - session1.getFlushMode(); - session1Control.setReturnValue(FlushMode.AUTO, 1); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); - session1.flush(); - session1Control.setVoidCallable(1); - session2.flush(); - session2Control.setVoidCallable(1); - session1.close(); - session1Control.setReturnValue(null, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - - tmControl.replay(); - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session1 = mock(Session.class); + final Session session2 = mock(Session.class); + given(sf.openSession()).willReturn(session1, session2); + given(sf.getTransactionManager()).willReturn(tm); + given(session1.getFlushMode()).willReturn(FlushMode.AUTO); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); HibernateTemplate ht = new HibernateTemplate(sf); @@ -1654,46 +1289,27 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); + verify(session1).flush(); + verify(session2).flush(); + verify(session1).close(); + verify(session2).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithNonSessionFactoryImplementor() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl sfiControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sfi = (SessionFactoryImplementor) sfiControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sfi, 6); - sfi.getTransactionManager(); - sfiControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 4); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); - sfiControl.replay(); + given(tm.getTransaction()).willReturn(transaction); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + final SessionFactoryImplementor sfi = mock(SessionFactoryImplementor.class); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sfi); + given(sfi.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); HibernateTemplate ht = new HibernateTemplate(sf); @@ -1718,46 +1334,25 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); - sfiControl.verify(); + verify(session).flush(); + verify(session).close(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithSpringTransactionLaterOn() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + UserTransaction ut = mock(UserTransaction.class); + + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 4); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - utControl.replay(); - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); + given(ut.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); final HibernateTemplate ht = new HibernateTemplate(sf); @@ -1801,10 +1396,8 @@ public class HibernateJtaTransactionTests { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + verify(session).flush(); + verify(session).close(); } @Test @@ -1819,34 +1412,21 @@ public class HibernateJtaTransactionTests { @SuppressWarnings("rawtypes") private void doTestJtaSessionSynchronizationWithPreBound(boolean flushNever) throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 5); - session.getFlushMode(); + TransactionManager tm = mock(TransactionManager.class); + MockJtaTransaction transaction = new MockJtaTransaction(); + given(tm.getTransaction()).willReturn(transaction); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); if (flushNever) { - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL, FlushMode.AUTO, FlushMode.MANUAL); } else { - sessionControl.setReturnValue(FlushMode.AUTO, 1); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); } - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); - assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); try { @@ -1865,20 +1445,6 @@ public class HibernateJtaTransactionTests { }); } - sessionControl.verify(); - sessionControl.reset(); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - if (flushNever) { - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - } - session.disconnect(); - sessionControl.setReturnValue(null, 1); - sessionControl.replay(); - Synchronization synchronization = transaction.getSynchronization(); assertTrue("JTA synchronization registered", synchronization != null); synchronization.beforeCompletion(); @@ -1890,47 +1456,31 @@ public class HibernateJtaTransactionTests { } assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + if(flushNever) { + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + } else { + ordered.verify(session).flush(); + } + ordered.verify(session).disconnect(); } @Test @SuppressWarnings("rawtypes") public void testJtaSessionSynchronizationWithRemoteTransaction() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); - MockJtaTransaction transaction = new MockJtaTransaction(); - MockControl sfControl = MockControl.createControl(SessionFactoryImplementor.class); - final SessionFactoryImplementor sf = (SessionFactoryImplementor) sfControl.getMock(); - final MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); + MockJtaTransaction transaction = new MockJtaTransaction(); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + final Session session = mock(Session.class); + given(tm.getTransaction()).willReturn(transaction); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); for (int j = 0; j < 2; j++) { - tmControl.reset(); - sfControl.reset(); - sessionControl.reset(); - - tm.getTransaction(); - tmControl.setReturnValue(transaction, 6); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - sf.getTransactionManager(); - sfControl.setReturnValue(tm, 6); - session.isOpen(); - sessionControl.setReturnValue(true, 4); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - tmControl.replay(); - sfControl.replay(); - sessionControl.replay(); if (j == 0) { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); @@ -1975,23 +1525,13 @@ public class HibernateJtaTransactionTests { SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sf); assertTrue("Thread session holder empty", sessionHolder.isEmpty()); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - - tmControl.verify(); - sfControl.verify(); - sessionControl.verify(); } + verify(session, times(2)).flush(); + verify(session, times(2)).close(); TransactionSynchronizationManager.unbindResource(sf); } - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - } - - /** * Interface that combines Hibernate's Session and SessionImplementor * interface. Necessary for creating a mock that implements both interfaces. diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java index a9ef28ff59..fd1ae832b3 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTemplateTests.java @@ -16,6 +16,20 @@ package org.springframework.orm.hibernate3; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.SQLException; @@ -24,8 +38,6 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; -import junit.framework.TestCase; -import org.easymock.MockControl; import org.hibernate.Criteria; import org.hibernate.Filter; import org.hibernate.FlushMode; @@ -54,152 +66,123 @@ import org.hibernate.exception.GenericJDBCException; import org.hibernate.exception.JDBCConnectionException; import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.SQLGrammarException; - -import org.springframework.tests.sample.beans.TestBean; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; import org.springframework.dao.CannotAcquireLockException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.InvalidDataAccessResourceUsageException; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -public class HibernateTemplateTests extends TestCase { +public class HibernateTemplateTests { - private MockControl sfControl; - private SessionFactory sf; - private MockControl sessionControl; + private SessionFactory sessionFactory; private Session session; + private HibernateTemplate hibernateTemplate; - @Override - protected void setUp() { - sfControl = MockControl.createControl(SessionFactory.class); - sf = (SessionFactory) sfControl.getMock(); - sessionControl = MockControl.createControl(Session.class); - session = (Session) sessionControl.getMock(); + @Before + public void setUp() { + this.sessionFactory = mock(SessionFactory.class); + this.session = mock(Session.class); + this.hibernateTemplate = new HibernateTemplate(sessionFactory); + given(sessionFactory.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sessionFactory); } + @After + public void tearDown() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + } + + @Test public void testExecuteWithNewSession() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - assertTrue("Correct allowCreate default", ht.isAllowCreate()); - assertTrue("Correct flushMode default", ht.getFlushMode() == HibernateTemplate.FLUSH_AUTO); + assertTrue("Correct allowCreate default", hibernateTemplate.isAllowCreate()); + assertTrue("Correct flushMode default", hibernateTemplate.getFlushMode() == HibernateTemplate.FLUSH_AUTO); final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; } }); assertTrue("Correct result list", result == l); + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithNewSessionAndFlushNever() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFlushMode(HibernateTemplate.FLUSH_NEVER); + hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; } }); assertTrue("Correct result list", result == l); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).close(); } + @Test public void testExecuteWithNewSessionAndFilter() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFilterName("myFilter"); + hibernateTemplate.setFilterName("myFilter"); final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; } }); assertTrue("Correct result list", result == l); + verify(session).enableFilter("myFilter"); + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithNewSessionAndFilters() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.enableFilter("yourFilter"); - sessionControl.setReturnValue(null, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFilterNames(new String[] {"myFilter", "yourFilter"}); + hibernateTemplate.setFilterNames(new String[] {"myFilter", "yourFilter"}); final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; } }); assertTrue("Correct result list", result == l); + InOrder ordered = inOrder(session); + ordered.verify(session).enableFilter("myFilter"); + ordered.verify(session).enableFilter("yourFilter"); + ordered.verify(session).flush(); + ordered.verify(session).close(); } + @Test public void testExecuteWithNotAllowCreate() { - sf.getCurrentSession(); - sfControl.setThrowable(new HibernateException("")); - sfControl.replay(); - + reset(sessionFactory); + given(sessionFactory.getCurrentSession()).willThrow(new HibernateException("")); HibernateTemplate ht = new HibernateTemplate(); - ht.setSessionFactory(sf); + ht.setSessionFactory(sessionFactory); ht.setAllowCreate(false); try { - ht.execute(new HibernateCallback() { + ht.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return null; @@ -212,17 +195,14 @@ public class HibernateTemplateTests extends TestCase { } } + @Test public void testExecuteWithNotAllowCreateAndThreadBound() { - sf.getCurrentSession(); - sfControl.setReturnValue(session); - sfControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setAllowCreate(false); + given(sessionFactory.getCurrentSession()).willReturn(session); + hibernateTemplate.setAllowCreate(false); final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; @@ -231,26 +211,16 @@ public class HibernateTemplateTests extends TestCase { assertTrue("Correct result list", result == l); } + @Test public void testExecuteWithThreadBoundAndFlushEager() throws HibernateException { - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.flush(); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFlushModeName("FLUSH_EAGER"); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.setFlushModeName("FLUSH_EAGER"); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; @@ -259,30 +229,21 @@ public class HibernateTemplateTests extends TestCase { assertTrue("Correct result list", result == l); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + verify(session).flush(); } + @Test public void testExecuteWithThreadBoundAndFilter() { - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.disableFilter("myFilter"); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); + hibernateTemplate.setFilterName("myFilter"); - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFilterName("myFilter"); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; @@ -291,34 +252,23 @@ public class HibernateTemplateTests extends TestCase { assertTrue("Correct result list", result == l); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + InOrder ordered = inOrder(session); + ordered.verify(session).enableFilter("myFilter"); + ordered.verify(session).disableFilter("myFilter"); } + @Test public void testExecuteWithThreadBoundAndFilters() { - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.enableFilter("yourFilter"); - sessionControl.setReturnValue(null, 1); - session.disableFilter("myFilter"); - sessionControl.setVoidCallable(1); - session.disableFilter("yourFilter"); - sessionControl.setVoidCallable(1); - sfControl.replay(); - sessionControl.replay(); + given(session.isOpen()).willReturn(true); + hibernateTemplate.setFilterNames(new String[] {"myFilter", "yourFilter"}); - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFilterNames(new String[] {"myFilter", "yourFilter"}); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; @@ -327,96 +277,72 @@ public class HibernateTemplateTests extends TestCase { assertTrue("Correct result list", result == l); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + InOrder ordered = inOrder(session); + ordered.verify(session).enableFilter("myFilter"); + ordered.verify(session).enableFilter("yourFilter"); + ordered.verify(session).disableFilter("myFilter"); + ordered.verify(session).disableFilter("yourFilter"); } + @Test public void testExecuteWithThreadBoundAndParameterizedFilter() { - MockControl filterControl = MockControl.createControl(Filter.class); - Filter filter = (Filter) filterControl.getMock(); + Filter filter = mock(Filter.class); + given(session.isOpen()).willReturn(true); + given(session.enableFilter("myFilter")).willReturn(filter); + hibernateTemplate.setAllowCreate(false); + hibernateTemplate.setFilterName("myFilter"); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getEnabledFilter("myFilter"); - sessionControl.setReturnValue(null, 1); - session.enableFilter("myFilter"); - sessionControl.setReturnValue(filter, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setAllowCreate(false); - ht.setFilterName("myFilter"); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); - Filter f = ht.enableFilter("myFilter"); + Filter f = hibernateTemplate.enableFilter("myFilter"); assertTrue("Correct filter", f == filter); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + InOrder ordered = inOrder(session); + ordered.verify(session).getEnabledFilter("myFilter"); + ordered.verify(session).enableFilter("myFilter"); } + @Test public void testExecuteWithThreadBoundAndParameterizedExistingFilter() { - MockControl filterControl = MockControl.createControl(Filter.class); - Filter filter = (Filter) filterControl.getMock(); + Filter filter = mock(Filter.class); + given(session.isOpen()).willReturn(true); + given(session.enableFilter("myFilter")).willReturn(filter); + hibernateTemplate.setAllowCreate(false); + hibernateTemplate.setFilterName("myFilter"); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getEnabledFilter("myFilter"); - sessionControl.setReturnValue(filter, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setAllowCreate(false); - ht.setFilterName("myFilter"); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); try { final List l = new ArrayList(); l.add("test"); - Filter f = ht.enableFilter("myFilter"); + Filter f = hibernateTemplate.enableFilter("myFilter"); assertTrue("Correct filter", f == filter); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + verify(session).getEnabledFilter("myFilter"); } + @Test public void testExecuteWithThreadBoundAndNewSession() throws HibernateException { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - Session session2 = (Session) session2Control.getMock(); + Connection con = mock(Connection.class); + Session session2 = mock(Session.class); + given(session2.connection()).willReturn(con); + given(sessionFactory.openSession(con)).willReturn(session); + hibernateTemplate.setAlwaysUseNewSession(true); - session2.connection(); - session2Control.setReturnValue(con, 1); - sf.openSession(con); - sfControl.setReturnValue(session, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - session2Control.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setAlwaysUseNewSession(true); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session2)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session2)); try { final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; @@ -425,40 +351,27 @@ public class HibernateTemplateTests extends TestCase { assertTrue("Correct result list", result == l); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithThreadBoundAndNewSessionAndEntityInterceptor() throws HibernateException { - MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); - Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock(); + Interceptor entityInterceptor = mock(Interceptor.class); + Connection con = mock(Connection.class); + Session session2 = mock(Session.class); + given(session2.connection()).willReturn(con); + given(sessionFactory.openSession(con, entityInterceptor)).willReturn(session); + hibernateTemplate.setAlwaysUseNewSession(true); + hibernateTemplate.setEntityInterceptor(entityInterceptor); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - Session session2 = (Session) session2Control.getMock(); - - session2.connection(); - session2Control.setReturnValue(con, 1); - sf.openSession(con, entityInterceptor); - sfControl.setReturnValue(session, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - session2Control.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setAlwaysUseNewSession(true); - ht.setEntityInterceptor(entityInterceptor); - - TransactionSynchronizationManager.bindResource(sf, new SessionHolder(session2)); + TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session2)); try { final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; @@ -467,75 +380,44 @@ public class HibernateTemplateTests extends TestCase { assertTrue("Correct result list", result == l); } finally { - TransactionSynchronizationManager.unbindResource(sf); + TransactionSynchronizationManager.unbindResource(sessionFactory); } + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithEntityInterceptor() throws HibernateException { - MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); - Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock(); - - sf.openSession(entityInterceptor); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setEntityInterceptor(entityInterceptor); + Interceptor entityInterceptor = mock(Interceptor.class); + given(sessionFactory.openSession(entityInterceptor)).willReturn(session); + hibernateTemplate.setEntityInterceptor(entityInterceptor); final List l = new ArrayList(); l.add("test"); - List result = ht.executeFind(new HibernateCallback() { + List result = hibernateTemplate.executeFind(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { return l; } }); assertTrue("Correct result list", result == l); + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithCacheQueries() throws HibernateException { - MockControl query1Control = MockControl.createControl(Query.class); - Query query1 = (Query) query1Control.getMock(); - MockControl query2Control = MockControl.createControl(Query.class); - Query query2 = (Query) query2Control.getMock(); - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Query query1 = mock(Query.class); + Query query2 = mock(Query.class); + Criteria criteria = mock(Criteria.class); + given(session.createQuery("some query")).willReturn(query1); + given(query1.setCacheable(true)).willReturn(query1); + given(session.getNamedQuery("some query name")).willReturn(query2); + given(query2.setCacheable(true)).willReturn(query2); + given(session.createCriteria(TestBean.class)).willReturn(criteria); + given(criteria.setCacheable(true)).willReturn(criteria); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query"); - sessionControl.setReturnValue(query1); - query1.setCacheable(true); - query1Control.setReturnValue(query1, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query2); - query2.setCacheable(true); - query2Control.setReturnValue(query2, 1); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - criteria.setCacheable(true); - criteriaControl.setReturnValue(criteria, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - query1Control.replay(); - query2Control.replay(); - criteriaControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - ht.execute(new HibernateCallback() { + hibernateTemplate.setCacheQueries(true); + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session sess) throws HibernateException { assertNotSame(session, sess); @@ -549,55 +431,28 @@ public class HibernateTemplateTests extends TestCase { } }); - query1Control.verify(); - query2Control.verify(); - criteriaControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithCacheQueriesAndCacheRegion() throws HibernateException { - MockControl query1Control = MockControl.createControl(Query.class); - Query query1 = (Query) query1Control.getMock(); - MockControl query2Control = MockControl.createControl(Query.class); - Query query2 = (Query) query2Control.getMock(); - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Query query1 = mock(Query.class); + Query query2 = mock(Query.class); + Criteria criteria = mock(Criteria.class); + given(session.createQuery("some query")).willReturn(query1); + given(query1.setCacheable(true)).willReturn(query1); + given(query1.setCacheRegion("myRegion")).willReturn(query1); + given(session.getNamedQuery("some query name")).willReturn(query2); + given(query2.setCacheable(true)).willReturn(query2); + given(query2.setCacheRegion("myRegion")).willReturn(query2); + given(session.createCriteria(TestBean.class)).willReturn(criteria); + given(criteria.setCacheable(true)).willReturn(criteria); + given(criteria.setCacheRegion("myRegion")).willReturn(criteria); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query"); - sessionControl.setReturnValue(query1); - query1.setCacheable(true); - query1Control.setReturnValue(query1, 1); - query1.setCacheRegion("myRegion"); - query1Control.setReturnValue(query1, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query2); - query2.setCacheable(true); - query2Control.setReturnValue(query2, 1); - query2.setCacheRegion("myRegion"); - query2Control.setReturnValue(query2, 1); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - criteria.setCacheable(true); - criteriaControl.setReturnValue(criteria, 1); - criteria.setCacheRegion("myRegion"); - criteriaControl.setReturnValue(criteria, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - query1Control.replay(); - query2Control.replay(); - criteriaControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - ht.setQueryCacheRegion("myRegion"); - ht.execute(new HibernateCallback() { + hibernateTemplate.setCacheQueries(true); + hibernateTemplate.setQueryCacheRegion("myRegion"); + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session sess) throws HibernateException { assertNotSame(session, sess); @@ -611,44 +466,24 @@ public class HibernateTemplateTests extends TestCase { } }); - query1Control.verify(); - query2Control.verify(); - criteriaControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithCacheQueriesAndCacheRegionAndNativeSession() throws HibernateException { - MockControl query1Control = MockControl.createControl(Query.class); - Query query1 = (Query) query1Control.getMock(); - MockControl query2Control = MockControl.createControl(Query.class); - Query query2 = (Query) query2Control.getMock(); - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Query query1 = mock(Query.class); + Query query2 = mock(Query.class); + Criteria criteria = mock(Criteria.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query"); - sessionControl.setReturnValue(query1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query2); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - query1Control.replay(); - query2Control.replay(); - criteriaControl.replay(); + given(session.createQuery("some query")).willReturn(query1); + given(session.getNamedQuery("some query name")).willReturn(query2); + given(session.createCriteria(TestBean.class)).willReturn(criteria); - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setExposeNativeSession(true); - ht.setCacheQueries(true); - ht.setQueryCacheRegion("myRegion"); - ht.execute(new HibernateCallback() { + hibernateTemplate.setExposeNativeSession(true); + hibernateTemplate.setCacheQueries(true); + hibernateTemplate.setQueryCacheRegion("myRegion"); + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session sess) throws HibernateException { assertSame(session, sess); @@ -659,55 +494,29 @@ public class HibernateTemplateTests extends TestCase { } }); - query1Control.verify(); - query2Control.verify(); - criteriaControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testExecuteWithFetchSizeAndMaxResults() throws HibernateException { - MockControl query1Control = MockControl.createControl(Query.class); - Query query1 = (Query) query1Control.getMock(); - MockControl query2Control = MockControl.createControl(Query.class); - Query query2 = (Query) query2Control.getMock(); - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Query query1 = mock(Query.class); + Query query2 = mock(Query.class); + Criteria criteria = mock(Criteria.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query"); - sessionControl.setReturnValue(query1); - query1.setFetchSize(10); - query1Control.setReturnValue(query1, 1); - query1.setMaxResults(20); - query1Control.setReturnValue(query1, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query2); - query2.setFetchSize(10); - query2Control.setReturnValue(query2, 1); - query2.setMaxResults(20); - query2Control.setReturnValue(query2, 1); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - criteria.setFetchSize(10); - criteriaControl.setReturnValue(criteria, 1); - criteria.setMaxResults(20); - criteriaControl.setReturnValue(criteria, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - query1Control.replay(); - query2Control.replay(); - criteriaControl.replay(); + given(session.createQuery("some query")).willReturn(query1); + given(query1.setFetchSize(10)).willReturn(query1); + given(query1.setMaxResults(20)).willReturn(query1); + given(session.getNamedQuery("some query name")).willReturn(query2); + given(query2.setFetchSize(10)).willReturn(query2); + given(query2.setMaxResults(20)).willReturn(query2); + given(session.createCriteria(TestBean.class)).willReturn(criteria); + given(criteria.setFetchSize(10)).willReturn(criteria); + given(criteria.setMaxResults(20)).willReturn(criteria); - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFetchSize(10); - ht.setMaxResults(20); - ht.execute(new HibernateCallback() { + hibernateTemplate.setFetchSize(10); + hibernateTemplate.setMaxResults(20); + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session sess) throws HibernateException { sess.createQuery("some query"); @@ -717,128 +526,66 @@ public class HibernateTemplateTests extends TestCase { } }); - query1Control.verify(); - query2Control.verify(); - criteriaControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testGet() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.get(TestBean.class, ""); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.get(TestBean.class, ""); + given(session.get(TestBean.class, "")).willReturn(tb); + Object result = hibernateTemplate.get(TestBean.class, ""); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testGetWithLockMode() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.get(TestBean.class, "", LockMode.UPGRADE_NOWAIT); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.get(TestBean.class, "", LockMode.UPGRADE_NOWAIT); + given(session.get(TestBean.class, "", LockMode.UPGRADE_NOWAIT)).willReturn(tb); + Object result = hibernateTemplate.get(TestBean.class, "", LockMode.UPGRADE_NOWAIT); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testGetWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.get("myEntity", ""); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.get("myEntity", ""); + given(session.get("myEntity", "")).willReturn(tb); + Object result = hibernateTemplate.get("myEntity", ""); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testGetWithEntityNameAndLockMode() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.get("myEntity", "", LockMode.UPGRADE_NOWAIT); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.get("myEntity", "", LockMode.UPGRADE_NOWAIT); + given(session.get("myEntity", "", LockMode.UPGRADE_NOWAIT)).willReturn(tb); + Object result = hibernateTemplate.get("myEntity", "", LockMode.UPGRADE_NOWAIT); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoad() throws HibernateException { TestBean tb = new TestBean(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.load(TestBean.class, ""); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.load(TestBean.class, ""); + given(session.load(TestBean.class, "")).willReturn(tb); + Object result = hibernateTemplate.load(TestBean.class, ""); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadWithNotFound() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.load(TestBean.class, "id"); ObjectNotFoundException onfex = new ObjectNotFoundException("id", TestBean.class.getName()); - sessionControl.setThrowable(onfex); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); + given(session.load(TestBean.class, "id")).willThrow(onfex); try { - ht.load(TestBean.class, "id"); + hibernateTemplate.load(TestBean.class, "id"); fail("Should have thrown HibernateObjectRetrievalFailureException"); } catch (HibernateObjectRetrievalFailureException ex) { @@ -847,1449 +594,723 @@ public class HibernateTemplateTests extends TestCase { assertEquals("id", ex.getIdentifier()); assertEquals(onfex, ex.getCause()); } + verify(session).close(); } + @Test public void testLoadWithLockMode() throws HibernateException { TestBean tb = new TestBean(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.load(TestBean.class, "", LockMode.UPGRADE); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.load(TestBean.class, "", LockMode.UPGRADE); + given(session.load(TestBean.class, "", LockMode.UPGRADE)).willReturn(tb); + Object result = hibernateTemplate.load(TestBean.class, "", LockMode.UPGRADE); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.load("myEntity", ""); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.load("myEntity", ""); + given(session.load("myEntity", "")).willReturn(tb); + Object result = hibernateTemplate.load("myEntity", ""); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadWithEntityNameLockMode() throws HibernateException { TestBean tb = new TestBean(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.load("myEntity", "", LockMode.UPGRADE); - sessionControl.setReturnValue(tb, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Object result = ht.load("myEntity", "", LockMode.UPGRADE); + given(session.load("myEntity", "", LockMode.UPGRADE)).willReturn(tb); + Object result = hibernateTemplate.load("myEntity", "", LockMode.UPGRADE); assertTrue("Correct result", result == tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadWithObject() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.load(tb, ""); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.load(tb, ""); + hibernateTemplate.load(tb, ""); + verify(session).load(tb, ""); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadAll() throws HibernateException { - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Criteria criteria = mock(Criteria.class); List list = new ArrayList(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); - criteriaControl.setReturnValue(criteria); - criteria.list(); - criteriaControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - criteriaControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.loadAll(TestBean.class); + given(session.createCriteria(TestBean.class)).willReturn(criteria); + given(criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)).willReturn(criteria); + given(criteria.list()).willReturn(list); + List result = hibernateTemplate.loadAll(TestBean.class); assertTrue("Correct result", result == list); - - criteriaControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadAllWithCacheable() throws HibernateException { - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Criteria criteria = mock(Criteria.class); List list = new ArrayList(); + given(session.createCriteria(TestBean.class)).willReturn(criteria); + given(criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)).willReturn(criteria); + given(criteria.setCacheable(true)).willReturn(criteria); + given(criteria.list()).willReturn(list); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); - criteriaControl.setReturnValue(criteria); - criteria.setCacheable(true); - criteriaControl.setReturnValue(criteria, 1); - criteria.list(); - criteriaControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - criteriaControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - List result = ht.loadAll(TestBean.class); + hibernateTemplate.setCacheQueries(true); + List result = hibernateTemplate.loadAll(TestBean.class); assertTrue("Correct result", result == list); - - criteriaControl.verify(); + verify(criteria).setCacheable(true); + verify(session).flush(); + verify(session).close(); } + @Test public void testLoadAllWithCacheableAndCacheRegion() throws HibernateException { - MockControl criteriaControl = MockControl.createControl(Criteria.class); - Criteria criteria = (Criteria) criteriaControl.getMock(); + Criteria criteria = mock(Criteria.class); List list = new ArrayList(); + given(session.createCriteria(TestBean.class)).willReturn(criteria); + given(criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)).willReturn(criteria); + given(criteria.setCacheable(true)).willReturn(criteria); + given(criteria.setCacheRegion("myCacheRegion")).willReturn(criteria); + given(criteria.list()).willReturn(list); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createCriteria(TestBean.class); - sessionControl.setReturnValue(criteria, 1); - criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); - criteriaControl.setReturnValue(criteria); - criteria.setCacheable(true); - criteriaControl.setReturnValue(criteria, 1); - criteria.setCacheRegion("myCacheRegion"); - criteriaControl.setReturnValue(criteria, 1); - criteria.list(); - criteriaControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - criteriaControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - ht.setQueryCacheRegion("myCacheRegion"); - List result = ht.loadAll(TestBean.class); + hibernateTemplate.setCacheQueries(true); + hibernateTemplate.setQueryCacheRegion("myCacheRegion"); + List result = hibernateTemplate.loadAll(TestBean.class); assertTrue("Correct result", result == list); - - criteriaControl.verify(); + verify(criteria).setCacheable(true); + verify(criteria).setCacheRegion("myCacheRegion"); + verify(session).flush(); + verify(session).close(); } - public void testRefresh() throws HibernateException { + @Test public void testRefresh() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.refresh(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.refresh(tb); + hibernateTemplate.refresh(tb); + verify(session).refresh(tb); + verify(session).flush(); + verify(session).close(); } - public void testContains() throws HibernateException { + @Test public void testContains() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.contains(tb); - sessionControl.setReturnValue(true, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - assertTrue(ht.contains(tb)); + given(session.contains(tb)).willReturn(true); + assertTrue(hibernateTemplate.contains(tb)); + verify(session).flush(); + verify(session).close(); } + @Test public void testEvict() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.evict(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.evict(tb); + hibernateTemplate.evict(tb); + verify(session).evict(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testLock() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.lock(tb, LockMode.WRITE); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.lock(tb, LockMode.WRITE); + hibernateTemplate.lock(tb, LockMode.WRITE); + verify(session).lock(tb, LockMode.WRITE); + verify(session).flush(); + verify(session).close(); } + @Test public void testLockWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.lock("myEntity", tb, LockMode.WRITE); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.lock("myEntity", tb, LockMode.WRITE); + hibernateTemplate.lock("myEntity", tb, LockMode.WRITE); + verify(session).lock("myEntity", tb, LockMode.WRITE); + verify(session).flush(); + verify(session).close(); } + @Test public void testSave() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.save(tb); - sessionControl.setReturnValue(new Integer(0), 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - assertEquals("Correct return value", ht.save(tb), new Integer(0)); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.save(tb)).willReturn(0); + assertEquals("Correct return value", hibernateTemplate.save(tb), 0); + verify(session).flush(); + verify(session).close(); } + @Test public void testSaveWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.save("myEntity", tb); - sessionControl.setReturnValue(new Integer(0), 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - assertEquals("Correct return value", ht.save("myEntity", tb), new Integer(0)); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.save("myEntity", tb)).willReturn(0); + assertEquals("Correct return value", hibernateTemplate.save("myEntity", tb), 0); + verify(session).flush(); + verify(session).close(); } + @Test public void testUpdate() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.update(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.update(tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.update(tb); + verify(session).update(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testUpdateWithLockMode() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.update(tb); - sessionControl.setVoidCallable(1); - session.lock(tb, LockMode.UPGRADE); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.update(tb, LockMode.UPGRADE); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.update(tb, LockMode.UPGRADE); + verify(session).update(tb); + verify(session).lock(tb, LockMode.UPGRADE); + verify(session).flush(); + verify(session).close(); } + @Test public void testUpdateWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.update("myEntity", tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.update("myEntity", tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.update("myEntity", tb); + verify(session).update("myEntity", tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testUpdateWithEntityNameAndLockMode() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.update("myEntity", tb); - sessionControl.setVoidCallable(1); - session.lock(tb, LockMode.UPGRADE); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.update("myEntity", tb, LockMode.UPGRADE); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.update("myEntity", tb, LockMode.UPGRADE); + verify(session).update("myEntity", tb); + verify(session).lock(tb, LockMode.UPGRADE); + verify(session).flush(); + verify(session).close(); } + @Test public void testSaveOrUpdate() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.saveOrUpdate(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.saveOrUpdate(tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.saveOrUpdate(tb); + verify(session).saveOrUpdate(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testSaveOrUpdateWithFlushModeNever() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); try { - ht.saveOrUpdate(tb); + hibernateTemplate.saveOrUpdate(tb); fail("Should have thrown InvalidDataAccessApiUsageException"); } catch (InvalidDataAccessApiUsageException ex) { // expected } + verify(session).close(); } + @Test public void testSaveOrUpdateWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.saveOrUpdate("myEntity", tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - HibernateTemplate ht = new HibernateTemplate(sf); - ht.saveOrUpdate("myEntity", tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.saveOrUpdate("myEntity", tb); + verify(session).saveOrUpdate("myEntity", tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testSaveOrUpdateAll() throws HibernateException { TestBean tb1 = new TestBean(); TestBean tb2 = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.saveOrUpdate(tb1); - sessionControl.setVoidCallable(1); - session.saveOrUpdate(tb2); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); List tbs = new ArrayList(); tbs.add(tb1); tbs.add(tb2); - ht.saveOrUpdateAll(tbs); + hibernateTemplate.saveOrUpdateAll(tbs); + verify(session).saveOrUpdate(same(tb1)); + verify(session).saveOrUpdate(same(tb2)); + verify(session).flush(); + verify(session).close(); } + @Test public void testReplicate() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.replicate(tb, ReplicationMode.LATEST_VERSION); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.replicate(tb, ReplicationMode.LATEST_VERSION); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.replicate(tb, ReplicationMode.LATEST_VERSION); + verify(session).replicate(tb, ReplicationMode.LATEST_VERSION); + verify(session).flush(); + verify(session).close(); } + @Test public void testReplicateWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.replicate("myEntity", tb, ReplicationMode.LATEST_VERSION); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.replicate("myEntity", tb, ReplicationMode.LATEST_VERSION); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.replicate("myEntity", tb, ReplicationMode.LATEST_VERSION); + verify(session).replicate("myEntity", tb, ReplicationMode.LATEST_VERSION); + verify(session).flush(); + verify(session).close(); } + @Test public void testPersist() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.persist(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.persist(tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.persist(tb); + verify(session).persist(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testPersistWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.persist("myEntity", tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.persist("myEntity", tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.persist("myEntity", tb); + verify(session).persist("myEntity", tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testMerge() throws HibernateException { TestBean tb = new TestBean(); TestBean tbMerged = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.merge(tb); - sessionControl.setReturnValue(tbMerged, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - assertSame(tbMerged, ht.merge(tb)); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.merge(tb)).willReturn(tbMerged); + assertSame(tbMerged, hibernateTemplate.merge(tb)); + verify(session).flush(); + verify(session).close(); } + @Test public void testMergeWithEntityName() throws HibernateException { TestBean tb = new TestBean(); TestBean tbMerged = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.merge("myEntity", tb); - sessionControl.setReturnValue(tbMerged, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - assertSame(tbMerged, ht.merge("myEntity", tb)); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.merge("myEntity", tb)).willReturn(tbMerged); + assertSame(tbMerged, hibernateTemplate.merge("myEntity", tb)); + verify(session).flush(); + verify(session).close(); } + @Test public void testDelete() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.delete(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.delete(tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.delete(tb); + verify(session).delete(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testDeleteWithLockMode() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.lock(tb, LockMode.UPGRADE); - sessionControl.setVoidCallable(1); - session.delete(tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.delete(tb, LockMode.UPGRADE); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.delete(tb, LockMode.UPGRADE); + verify(session).lock(tb, LockMode.UPGRADE); + verify(session).delete(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testDeleteWithEntityName() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.delete("myEntity", tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.delete("myEntity", tb); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.delete("myEntity", tb); + verify(session).delete("myEntity", tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testDeleteWithEntityNameAndLockMode() throws HibernateException { TestBean tb = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.lock("myEntity", tb, LockMode.UPGRADE); - sessionControl.setVoidCallable(1); - session.delete("myEntity", tb); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.delete("myEntity", tb, LockMode.UPGRADE); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + hibernateTemplate.delete("myEntity", tb, LockMode.UPGRADE); + verify(session).lock("myEntity", tb, LockMode.UPGRADE); + verify(session).delete("myEntity", tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testDeleteAll() throws HibernateException { TestBean tb1 = new TestBean(); TestBean tb2 = new TestBean(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO); - session.delete(tb1); - sessionControl.setVoidCallable(1); - session.delete(tb2); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); List tbs = new ArrayList(); tbs.add(tb1); tbs.add(tb2); - ht.deleteAll(tbs); + hibernateTemplate.deleteAll(tbs); + verify(session).delete(same(tb1)); + verify(session).delete(same(tb2)); + verify(session).flush(); + verify(session).close(); } + @Test public void testFlush() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setFlushMode(HibernateTemplate.FLUSH_NEVER); - ht.flush(); + hibernateTemplate.setFlushMode(HibernateTemplate.FLUSH_NEVER); + hibernateTemplate.flush(); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).flush(); + verify(session).close(); } + @Test public void testClear() throws HibernateException { - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.clear(); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.clear(); + hibernateTemplate.clear(); + verify(session).clear(); + verify(session).flush(); + verify(session).close(); } + @Test public void testFind() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.find("some query string"); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.find("some query string"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindWithParameter() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue"); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.find("some query string", "myvalue"); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter(0, "myvalue")).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.find("some query string", "myvalue"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter(0, "myvalue"); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindWithParameters() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue1"); - queryControl.setReturnValue(query, 1); - query.setParameter(1, new Integer(2)); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.find("some query string", new Object[] {"myvalue1", new Integer(2)}); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter(0, "myvalue1")).willReturn(query); + given(query.setParameter(1, 2)).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.find("some query string", new Object[] {"myvalue1", 2}); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter(0, "myvalue1"); + verify(query).setParameter(1, 2); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindWithNamedParameter() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter("myparam", "myvalue"); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedParam("some query string", "myparam", "myvalue"); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter("myparam", "myvalue")).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedParam("some query string", "myparam", "myvalue"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter("myparam", "myvalue"); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindWithNamedParameters() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter("myparam1", "myvalue1"); - queryControl.setReturnValue(query, 1); - query.setParameter("myparam2", new Integer(2)); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedParam("some query string", + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter("myparam1", "myvalue1")).willReturn(query); + given(query.setParameter("myparam2", 2)).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedParam("some query string", new String[] {"myparam1", "myparam2"}, - new Object[] {"myvalue1", new Integer(2)}); + new Object[] {"myvalue1", 2}); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter("myparam1", "myvalue1"); + verify(query).setParameter("myparam2", 2); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByValueBean() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); TestBean tb = new TestBean(); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setProperties(tb); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByValueBean("some query string", tb); + given(session.createQuery("some query string")).willReturn(query); + given(query.setProperties(tb)).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByValueBean("some query string", tb); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setProperties(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQuery() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedQuery("some query name"); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedQuery("some query name"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryWithParameter() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue"); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedQuery("some query name", "myvalue"); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setParameter(0, "myvalue")).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedQuery("some query name", "myvalue"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter(0, "myvalue"); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryWithParameters() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue1"); - queryControl.setReturnValue(query, 1); - query.setParameter(1, new Integer(2)); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedQuery("some query name", new Object[] {"myvalue1", new Integer(2)}); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setParameter(0, "myvalue1")).willReturn(query); + given(query.setParameter(1, 2)).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedQuery("some query name", new Object[] {"myvalue1", 2}); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter(0, "myvalue1"); + verify(query).setParameter(1, 2); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryWithNamedParameter() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setParameter("myparam", "myvalue"); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedQueryAndNamedParam("some query name", "myparam", "myvalue"); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setParameter("myparam", "myvalue")).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedQueryAndNamedParam("some query name", "myparam", "myvalue"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter("myparam", "myvalue"); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryWithNamedParameters() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setParameter("myparam1", "myvalue1"); - queryControl.setReturnValue(query, 1); - query.setParameter("myparam2", new Integer(2)); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedQueryAndNamedParam("some query name", + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setParameter("myparam1", "myvalue1")).willReturn(query); + given(query.setParameter("myparam2", 2)).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedQueryAndNamedParam("some query name", new String[] {"myparam1", "myparam2"}, - new Object[] {"myvalue1", new Integer(2)}); + new Object[] {"myvalue1", 2}); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setParameter("myparam1", "myvalue1"); + verify(query).setParameter("myparam2", 2); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryAndValueBean() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); TestBean tb = new TestBean(); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setProperties(tb); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - List result = ht.findByNamedQueryAndValueBean("some query name", tb); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setProperties(tb)).willReturn(query); + given(query.list()).willReturn(list); + List result = hibernateTemplate.findByNamedQueryAndValueBean("some query name", tb); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setProperties(tb); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindWithCacheable() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setCacheable(true); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - List result = ht.find("some query string"); + given(session.createQuery("some query string")).willReturn(query); + given(query.setCacheable(true)).willReturn(query); + given(query.list()).willReturn(list); + hibernateTemplate.setCacheQueries(true); + List result = hibernateTemplate.find("some query string"); assertTrue("Correct list", result == list); - sfControl.verify(); + verify(query).setCacheable(true); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindWithCacheableAndCacheRegion() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setCacheable(true); - queryControl.setReturnValue(query, 1); - query.setCacheRegion("myCacheRegion"); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - ht.setQueryCacheRegion("myCacheRegion"); - List result = ht.find("some query string"); + given(session.createQuery("some query string")).willReturn(query); + given(query.setCacheable(true)).willReturn(query); + given(query.setCacheRegion("myCacheRegion")).willReturn(query); + given(query.list()).willReturn(list); + hibernateTemplate.setCacheQueries(true); + hibernateTemplate.setQueryCacheRegion("myCacheRegion"); + List result = hibernateTemplate.find("some query string"); assertTrue("Correct list", result == list); - sfControl.verify(); + verify(query).setCacheable(true); + verify(query).setCacheRegion("myCacheRegion"); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryWithCacheable() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setCacheable(true); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - List result = ht.findByNamedQuery("some query name"); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setCacheable(true)).willReturn(query); + given(query.list()).willReturn(list); + hibernateTemplate.setCacheQueries(true); + List result = hibernateTemplate.findByNamedQuery("some query name"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setCacheable(true); + verify(session).flush(); + verify(session).close(); } + @Test public void testFindByNamedQueryWithCacheableAndCacheRegion() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); List list = new ArrayList(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getNamedQuery("some query name"); - sessionControl.setReturnValue(query, 1); - query.setCacheable(true); - queryControl.setReturnValue(query, 1); - query.setCacheRegion("myCacheRegion"); - queryControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - ht.setCacheQueries(true); - ht.setQueryCacheRegion("myCacheRegion"); - List result = ht.findByNamedQuery("some query name"); + given(session.getNamedQuery("some query name")).willReturn(query); + given(query.setCacheable(true)).willReturn(query); + given(query.setCacheRegion("myCacheRegion")).willReturn(query); + given(query.list()).willReturn(list); + hibernateTemplate.setCacheQueries(true); + hibernateTemplate.setQueryCacheRegion("myCacheRegion"); + List result = hibernateTemplate.findByNamedQuery("some query name"); assertTrue("Correct list", result == list); - queryControl.verify(); + verify(query).setCacheable(true); + verify(query).setCacheRegion("myCacheRegion"); + verify(session).flush(); + verify(session).close(); } + @Test public void testIterate() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); Iterator it = Collections.EMPTY_LIST.iterator(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.iterate(); - queryControl.setReturnValue(it, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Iterator result = ht.iterate("some query string"); + given(session.createQuery("some query string")).willReturn(query); + given(query.iterate()).willReturn(it); + Iterator result = hibernateTemplate.iterate("some query string"); assertTrue("Correct list", result == it); - queryControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testIterateWithParameter() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); Iterator it = Collections.EMPTY_LIST.iterator(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue"); - queryControl.setReturnValue(query, 1); - query.iterate(); - queryControl.setReturnValue(it, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Iterator result = ht.iterate("some query string", "myvalue"); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter(0, "myvalue")).willReturn(query); + given(query.iterate()).willReturn(it); + Iterator result = hibernateTemplate.iterate("some query string", "myvalue"); assertTrue("Correct list", result == it); - queryControl.verify(); + verify(query).setParameter(0, "myvalue"); + verify(session).flush(); + verify(session).close(); } + @Test public void testIterateWithParameters() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - + Query query = mock(Query.class); Iterator it = Collections.EMPTY_LIST.iterator(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue1"); - queryControl.setReturnValue(query, 1); - query.setParameter(1, new Integer(2)); - queryControl.setReturnValue(query, 1); - query.iterate(); - queryControl.setReturnValue(it, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - Iterator result = ht.iterate("some query string", - new Object[] {"myvalue1", new Integer(2)}); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter(0, "myvalue1")).willReturn(query); + given(query.setParameter(1, 2)).willReturn(query); + given(query.iterate()).willReturn(it); + Iterator result = hibernateTemplate.iterate("some query string", + new Object[] {"myvalue1", 2}); assertTrue("Correct list", result == it); - sfControl.verify(); + verify(query).setParameter(0, "myvalue1"); + verify(query).setParameter(1, 2); + verify(session).flush(); + verify(session).close(); } + @Test public void testBulkUpdate() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.executeUpdate(); - queryControl.setReturnValue(5, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - int result = ht.bulkUpdate("some query string"); + Query query = mock(Query.class); + given(session.createQuery("some query string")).willReturn(query); + given(query.executeUpdate()).willReturn(5); + int result = hibernateTemplate.bulkUpdate("some query string"); assertTrue("Correct list", result == 5); - queryControl.verify(); + verify(session).flush(); + verify(session).close(); } + @Test public void testBulkUpdateWithParameter() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue"); - queryControl.setReturnValue(query, 1); - query.executeUpdate(); - queryControl.setReturnValue(5, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - int result = ht.bulkUpdate("some query string", "myvalue"); + Query query = mock(Query.class); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter(0, "myvalue")).willReturn(query); + given(query.executeUpdate()).willReturn(5); + int result = hibernateTemplate.bulkUpdate("some query string", "myvalue"); assertTrue("Correct list", result == 5); - queryControl.verify(); + verify(query).setParameter(0, "myvalue"); + verify(session).flush(); + verify(session).close(); } + @Test public void testBulkUpdateWithParameters() throws HibernateException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.setParameter(0, "myvalue1"); - queryControl.setReturnValue(query, 1); - query.setParameter(1, new Integer(2)); - queryControl.setReturnValue(query, 1); - query.executeUpdate(); - queryControl.setReturnValue(5, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - queryControl.replay(); - - HibernateTemplate ht = new HibernateTemplate(sf); - int result = ht.bulkUpdate("some query string", - new Object[] {"myvalue1", new Integer(2)}); + Query query = mock(Query.class); + given(session.createQuery("some query string")).willReturn(query); + given(query.setParameter(0, "myvalue1")).willReturn(query); + given(query.setParameter(1, 2)).willReturn(query); + given(query.executeUpdate()).willReturn(5); + int result = hibernateTemplate.bulkUpdate("some query string", + new Object[] {"myvalue1", 2}); assertTrue("Correct list", result == 5); - queryControl.verify(); + verify(query).setParameter(0, "myvalue1"); + verify(query).setParameter(1, 2); + verify(session).flush(); + verify(session).close(); } + @Test public void testExceptions() throws HibernateException { SQLException sqlEx = new SQLException("argh", "27"); final JDBCConnectionException jcex = new JDBCConnectionException("mymsg", sqlEx); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw jcex; @@ -2305,7 +1326,7 @@ public class HibernateTemplateTests extends TestCase { final SQLGrammarException sgex = new SQLGrammarException("mymsg", sqlEx); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw sgex; @@ -2321,7 +1342,7 @@ public class HibernateTemplateTests extends TestCase { final LockAcquisitionException laex = new LockAcquisitionException("mymsg", sqlEx); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw laex; @@ -2337,7 +1358,7 @@ public class HibernateTemplateTests extends TestCase { final ConstraintViolationException cvex = new ConstraintViolationException("mymsg", sqlEx, "myconstraint"); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw cvex; @@ -2353,7 +1374,7 @@ public class HibernateTemplateTests extends TestCase { final DataException dex = new DataException("mymsg", sqlEx); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw dex; @@ -2369,7 +1390,7 @@ public class HibernateTemplateTests extends TestCase { final JDBCException jdex = new JDBCException("mymsg", sqlEx); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw jdex; @@ -2385,7 +1406,7 @@ public class HibernateTemplateTests extends TestCase { final PropertyValueException pvex = new PropertyValueException("mymsg", "myentity", "myproperty"); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw pvex; @@ -2400,7 +1421,7 @@ public class HibernateTemplateTests extends TestCase { } try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw new PersistentObjectException(""); @@ -2413,7 +1434,7 @@ public class HibernateTemplateTests extends TestCase { } try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw new TransientObjectException(""); @@ -2427,7 +1448,7 @@ public class HibernateTemplateTests extends TestCase { final ObjectDeletedException odex = new ObjectDeletedException("msg", "id", TestBean.class.getName()); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw odex; @@ -2443,7 +1464,7 @@ public class HibernateTemplateTests extends TestCase { final QueryException qex = new QueryException("msg"); qex.setQueryString("query"); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw qex; @@ -2459,7 +1480,7 @@ public class HibernateTemplateTests extends TestCase { final UnresolvableObjectException uoex = new UnresolvableObjectException("id", TestBean.class.getName()); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw uoex; @@ -2476,7 +1497,7 @@ public class HibernateTemplateTests extends TestCase { final ObjectNotFoundException onfe = new ObjectNotFoundException("id", TestBean.class.getName()); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw onfe; @@ -2493,7 +1514,7 @@ public class HibernateTemplateTests extends TestCase { final WrongClassException wcex = new WrongClassException("msg", "id", TestBean.class.getName()); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw wcex; @@ -2510,7 +1531,7 @@ public class HibernateTemplateTests extends TestCase { final NonUniqueResultException nuex = new NonUniqueResultException(2); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw nuex; @@ -2526,7 +1547,7 @@ public class HibernateTemplateTests extends TestCase { final StaleObjectStateException sosex = new StaleObjectStateException(TestBean.class.getName(), "id"); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw sosex; @@ -2543,7 +1564,7 @@ public class HibernateTemplateTests extends TestCase { final StaleStateException ssex = new StaleStateException("msg"); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw ssex; @@ -2560,7 +1581,7 @@ public class HibernateTemplateTests extends TestCase { final HibernateException hex = new HibernateException("msg"); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw hex; @@ -2574,12 +1595,13 @@ public class HibernateTemplateTests extends TestCase { } } + @Test public void testFallbackExceptionTranslation() throws HibernateException { SQLException sqlEx = new SQLException("argh", "27"); final GenericJDBCException gjex = new GenericJDBCException("mymsg", sqlEx); try { - createTemplate().execute(new HibernateCallback() { + hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(org.hibernate.Session session) throws HibernateException { throw gjex; @@ -2593,32 +1615,4 @@ public class HibernateTemplateTests extends TestCase { assertTrue(ex.getMessage().indexOf("mymsg") != -1); } } - - private HibernateTemplate createTemplate() throws HibernateException { - sfControl.reset(); - sessionControl.reset(); - sf.openSession(); - sfControl.setReturnValue(session); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - return new HibernateTemplate(sf); - } - - @Override - protected void tearDown() { - try { - sfControl.verify(); - sessionControl.verify(); - } - catch (IllegalStateException ex) { - // ignore: test method didn't call replay - } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java index 707d17b9fe..534beea656 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,18 @@ package org.springframework.orm.hibernate3; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; @@ -23,10 +35,9 @@ import java.sql.Savepoint; import java.util.ArrayList; import java.util.List; import java.util.Properties; + import javax.sql.DataSource; -import junit.framework.TestCase; -import org.easymock.MockControl; import org.hibernate.FlushMode; import org.hibernate.HibernateException; import org.hibernate.Interceptor; @@ -39,7 +50,9 @@ import org.hibernate.classic.Session; import org.hibernate.dialect.HSQLDialect; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.GenericJDBCException; - +import org.junit.After; +import org.junit.Test; +import org.mockito.InOrder; import org.springframework.beans.factory.BeanFactory; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.datasource.ConnectionHolder; @@ -58,63 +71,38 @@ import org.springframework.transaction.support.TransactionTemplate; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -public class HibernateTransactionManagerTests extends TestCase { +public class HibernateTransactionManagerTests { + @After + public void tearDown() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + } + + @Test public void testTransactionCommit() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - con.getTransactionIsolation(); - conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED); - con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - conControl.setVoidCallable(1); - con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - conControl.setVoidCallable(1); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getTransaction(); - sessionControl.setReturnValue(tx, 1); - tx.setTimeout(10); - txControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - session.connection(); - sessionControl.setReturnValue(con, 3); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED); + given(sf.openSession()).willReturn(session); + given(session.getTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.isConnected()).willReturn(true); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -152,44 +140,27 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + + verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + verify(tx).setTimeout(10); + verify(tx).begin(); + verify(tx).commit(); + verify(session).close(); } + @Test public void testTransactionRollback() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -218,44 +189,23 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testTransactionRollbackOnly() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -279,70 +229,31 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).flush(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testTransactionCommitWithEarlyFlush() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - con.getTransactionIsolation(); - conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED); - con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - conControl.setVoidCallable(1); - con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - conControl.setVoidCallable(1); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getTransaction(); - sessionControl.setReturnValue(tx, 1); - tx.setTimeout(10); - txControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - session.connection(); - sessionControl.setReturnValue(con, 3); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED); + given(sf.openSession()).willReturn(session); + given(session.getTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -381,47 +292,30 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + InOrder ordered = inOrder(con); + ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + verify(tx).setTimeout(10); + verify(tx).begin(); + verify(session).flush(); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(tx).commit(); + verify(session).close(); } + @Test public void testParticipatingTransactionWithCommit() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -457,42 +351,24 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Correct result list", result == l); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).flush(); + verify(session).close(); + verify(tx).commit(); } + @Test public void testParticipatingTransactionWithRollback() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -521,40 +397,22 @@ public class HibernateTransactionManagerTests extends TestCase { // expected } - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testParticipatingTransactionWithRollbackOnly() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -587,61 +445,28 @@ public class HibernateTransactionManagerTests extends TestCase { // expected } - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testParticipatingTransactionWithWithRequiresNew() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(Session.class); - Session session1 = (Session) session1Control.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - Session session2 = (Session) session2Control.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + Session session1 = mock(Session.class); + Session session2 = mock(Session.class); + Connection con = mock(Connection.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - sf.openSession(); - sfControl.setReturnValue(session2, 1); - session1.beginTransaction(); - session1Control.setReturnValue(tx, 1); - session1.isOpen(); - session1Control.setReturnValue(true, 1); - session2.beginTransaction(); - session2Control.setReturnValue(tx, 1); - session2.isOpen(); - session2Control.setReturnValue(true, 1); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); - session2.flush(); - session2Control.setVoidCallable(1); - session1.close(); - session1Control.setReturnValue(null, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(2); - session1.isConnected(); - session1Control.setReturnValue(true, 1); - session1.connection(); - session1Control.setReturnValue(con, 2); - session2.isConnected(); - session2Control.setReturnValue(true, 1); - session2.connection(); - session2Control.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 2); - - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); - conControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session1, session2); + given(session1.beginTransaction()).willReturn(tx); + given(session1.isOpen()).willReturn(true); + given(session2.beginTransaction()).willReturn(tx); + given(session2.isOpen()).willReturn(true); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); + given(session1.isConnected()).willReturn(true); + given(session1.connection()).willReturn(con); + given(session2.isConnected()).willReturn(true); + given(session2.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -680,50 +505,26 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); - conControl.verify(); - txControl.verify(); + verify(session2).flush(); + verify(session1).close(); + verify(session2).close(); + verify(tx, times(2)).commit(); } + @Test public void testParticipatingTransactionWithWithNotSupported() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Connection con = mock(Connection.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 2); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 2); - session.flush(); - sessionControl.setVoidCallable(2); - session.close(); - sessionControl.setReturnValue(null, 2); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - conControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -763,35 +564,19 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session, times(2)).flush(); + verify(session, times(2)).close(); + verify(tx).commit(); } + @Test public void testTransactionWithPropagationSupports() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - session.flush(); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -828,57 +613,29 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy)); - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).flush(); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + ordered.verify(session).close(); } + @Test public void testTransactionWithPropagationSupportsAndInnerTransaction() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(Session.class); - final Session session1 = (Session) session1Control.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session1 = mock(Session.class); + final Session session2 = mock(Session.class); + Connection con = mock(Connection.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - session1.getSessionFactory(); - session1Control.setReturnValue(sf, 1); - session1.getFlushMode(); - session1Control.setReturnValue(FlushMode.AUTO, 2); - session1.flush(); - session1Control.setVoidCallable(2); - session1.disconnect(); - session1Control.setReturnValue(null, 1); - session1.close(); - session1Control.setReturnValue(null, 1); - - sf.openSession(); - sfControl.setReturnValue(session2, 1); - session2.beginTransaction(); - session2Control.setReturnValue(tx, 1); - session2.connection(); - session2Control.setReturnValue(con, 2); - session2.getFlushMode(); - session2Control.setReturnValue(FlushMode.AUTO, 1); - session2.flush(); - session2Control.setVoidCallable(1); - session2.isOpen(); - session2Control.setReturnValue(true, 1); - tx.commit(); - txControl.setVoidCallable(1); - session2.isConnected(); - session2Control.setReturnValue(true, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session1, session2); + given(session1.getSessionFactory()).willReturn(sf); + given(session1.getFlushMode()).willReturn(FlushMode.AUTO); + given(session2.beginTransaction()).willReturn(tx); + given(session2.connection()).willReturn(con); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); + given(session2.isOpen()).willReturn(true); + given(session2.isConnected()).willReturn(true); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -936,46 +693,27 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); - txControl.verify(); + verify(session1, times(2)).flush(); + verify(session1).disconnect(); + verify(session1).close(); + verify(session2).flush(); + verify(session2).close(); + verify(tx).commit(); } + @Test public void testTransactionCommitWithEntityInterceptor() throws Exception { - MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); - Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock(); - interceptorControl.replay(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Interceptor entityInterceptor = mock(Interceptor.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(entityInterceptor); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - conControl.replay(); + given(sf.openSession(entityInterceptor)).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(sf); tm.setEntityInterceptor(entityInterceptor); @@ -1003,61 +741,30 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - interceptorControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - conControl.verify(); + + verify(session).close(); + verify(tx).commit(); } + @Test public void testTransactionCommitWithEntityInterceptorBeanName() throws Exception { - MockControl interceptorControl = MockControl.createControl(org.hibernate.Interceptor.class); - Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock(); - interceptorControl.replay(); - MockControl interceptor2Control = MockControl.createControl(org.hibernate.Interceptor.class); - Interceptor entityInterceptor2 = (Interceptor) interceptor2Control.getMock(); - interceptor2Control.replay(); + Interceptor entityInterceptor = mock(Interceptor.class); + Interceptor entityInterceptor2 = mock(Interceptor.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + given(sf.openSession(entityInterceptor)).willReturn(session); + given(sf.openSession(entityInterceptor2)).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); - sf.openSession(entityInterceptor); - sfControl.setReturnValue(session, 1); - sf.openSession(entityInterceptor2); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 2); - session.isOpen(); - sessionControl.setReturnValue(true, 2); - session.close(); - sessionControl.setReturnValue(null, 2); - tx.commit(); - txControl.setVoidCallable(2); - session.isConnected(); - sessionControl.setReturnValue(true, 2); - session.connection(); - sessionControl.setReturnValue(con, 4); - con.isReadOnly(); - conControl.setReturnValue(false, 2); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - conControl.replay(); - - MockControl beanFactoryControl = MockControl.createControl(BeanFactory.class); - BeanFactory beanFactory = (BeanFactory) beanFactoryControl.getMock(); - beanFactory.getBean("entityInterceptor", Interceptor.class); - beanFactoryControl.setReturnValue(entityInterceptor, 1); - beanFactory.getBean("entityInterceptor", Interceptor.class); - beanFactoryControl.setReturnValue(entityInterceptor2, 1); - beanFactoryControl.replay(); + BeanFactory beanFactory = mock(BeanFactory.class); + given(beanFactory.getBean("entityInterceptor", Interceptor.class)).willReturn( + entityInterceptor, entityInterceptor2); HibernateTransactionManager tm = new HibernateTransactionManager(sf); tm.setEntityInterceptorBeanName("entityInterceptor"); @@ -1086,61 +793,29 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - interceptorControl.verify(); - interceptor2Control.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - conControl.verify(); - beanFactoryControl.verify(); + + verify(session, times(2)).close(); + verify(tx, times(2)).commit(); } + @Test public void testTransactionCommitWithReadOnly() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.setReadOnly(true); - conControl.setVoidCallable(1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - con.isReadOnly(); - conControl.setReturnValue(true, 1); - con.setReadOnly(false); - conControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.isConnected()).willReturn(true); + given(con.isReadOnly()).willReturn(true); HibernateTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -1163,65 +838,46 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(con).setReadOnly(true); + verify(tx).commit(); + verify(con).setReadOnly(false); + verify(session).close(); } + @Test public void testTransactionCommitWithFlushFailure() throws Exception { doTestTransactionCommitWithFlushFailure(false); } + @Test public void testTransactionCommitWithFlushFailureAndFallbackTranslation() throws Exception { doTestTransactionCommitWithFlushFailure(true); } private void doTestTransactionCommitWithFlushFailure(boolean fallbackTranslation) throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - tx.commit(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); SQLException sqlEx = new SQLException("argh", "27"); Exception rootCause = null; if (fallbackTranslation) { GenericJDBCException jdbcEx = new GenericJDBCException("mymsg", sqlEx); - txControl.setThrowable(jdbcEx, 1); rootCause = sqlEx; + willThrow(jdbcEx).given(tx).commit(); } else { ConstraintViolationException jdbcEx = new ConstraintViolationException("mymsg", sqlEx, null); - txControl.setThrowable(jdbcEx, 1); rootCause = jdbcEx; + willThrow(jdbcEx).given(tx).commit(); } - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - conControl.replay(); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -1254,56 +910,25 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - conControl.verify(); + + verify(session).close(); + verify(tx).rollback(); } + @Test public void testTransactionCommitWithPreBound() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 1); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.connection(); - sessionControl.setReturnValue(con, 3); - con.getTransactionIsolation(); - conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED); - con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - conControl.setVoidCallable(1); - con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - conControl.setVoidCallable(1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - session.disconnect(); - sessionControl.setReturnValue(null, 1); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); + given(session.connection()).willReturn(con); + given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED); + given(session.isConnected()).willReturn(true); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setSessionFactory(sf); @@ -1344,61 +969,29 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + InOrder ordered = inOrder(session, con); + ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + verify(tx).commit(); + verify(session).disconnect(); } + @Test public void testTransactionRollbackWithPreBound() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl tx1Control = MockControl.createControl(Transaction.class); - final Transaction tx1 = (Transaction) tx1Control.getMock(); - MockControl tx2Control = MockControl.createControl(Transaction.class); - final Transaction tx2 = (Transaction) tx2Control.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + final Transaction tx1 = mock(Transaction.class); + final Transaction tx2 = mock(Transaction.class); - session.beginTransaction(); - sessionControl.setReturnValue(tx1, 1); - tx1.rollback(); - tx1Control.setVoidCallable(1); - session.clear(); - sessionControl.setVoidCallable(1); - session.beginTransaction(); - sessionControl.setReturnValue(tx2, 1); - tx2.commit(); - tx2Control.setVoidCallable(1); - - session.isOpen(); - sessionControl.setReturnValue(true, 2); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 2); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(2); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(2); - session.isConnected(); - sessionControl.setReturnValue(true, 2); - session.connection(); - sessionControl.setReturnValue(con, 6); - con.isReadOnly(); - conControl.setReturnValue(false, 2); - session.disconnect(); - sessionControl.setReturnValue(null, 2); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - tx1Control.replay(); - tx2Control.replay(); + given(session.beginTransaction()).willReturn(tx1, tx2); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setSessionFactory(sf); @@ -1470,56 +1063,27 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - tx1Control.verify(); - tx2Control.verify(); + verify(tx1).rollback(); + verify(tx2).commit(); + InOrder ordered = inOrder(session); + ordered.verify(session).clear(); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + ordered.verify(session).disconnect(); } + @Test public void testTransactionRollbackWithHibernateManagedSession() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl tx1Control = MockControl.createControl(Transaction.class); - final Transaction tx1 = (Transaction) tx1Control.getMock(); - MockControl tx2Control = MockControl.createControl(Transaction.class); - final Transaction tx2 = (Transaction) tx2Control.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + final Transaction tx1 = mock(Transaction.class); + final Transaction tx2 = mock(Transaction.class); - sf.getCurrentSession(); - sfControl.setReturnValue(session, 2); - session.isOpen(); - sessionControl.setReturnValue(true, 2); - session.getTransaction(); - sessionControl.setReturnValue(tx1, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx1, 1); - tx1.isActive(); - tx1Control.setReturnValue(false, 1); - tx1.rollback(); - tx1Control.setVoidCallable(1); - session.getTransaction(); - sessionControl.setReturnValue(tx2, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx2, 1); - tx2.isActive(); - tx2Control.setReturnValue(false, 1); - tx2.commit(); - tx2Control.setVoidCallable(1); - - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.MANUAL, 2); - session.setFlushMode(FlushMode.AUTO); - sessionControl.setVoidCallable(2); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(2); - - sfControl.replay(); - sessionControl.replay(); - tx1Control.replay(); - tx2Control.replay(); + given(sf.getCurrentSession()).willReturn(session); + given(session.isOpen()).willReturn(true); + given(session.getTransaction()).willReturn(tx1, tx2); + given(session.beginTransaction()).willReturn(tx1, tx2); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setSessionFactory(sf); @@ -1577,16 +1141,19 @@ public class HibernateTransactionManagerTests extends TestCase { } }); - sfControl.verify(); - sessionControl.verify(); - tx1Control.verify(); - tx2Control.verify(); + verify(tx1).rollback(); + verify(tx2).commit(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); } + @Test public void testExistingTransactionWithPropagationNestedAndRollback() throws Exception { doTestExistingTransactionWithPropagationNestedAndRollback(false); } + @Test public void testExistingTransactionWithManualSavepointAndRollback() throws Exception { doTestExistingTransactionWithPropagationNestedAndRollback(true); } @@ -1594,62 +1161,27 @@ public class HibernateTransactionManagerTests extends TestCase { private void doTestExistingTransactionWithPropagationNestedAndRollback(final boolean manualSavepoint) throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl mdControl = MockControl.createControl(DatabaseMetaData.class); - DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock(); - MockControl spControl = MockControl.createControl(Savepoint.class); - Savepoint sp = (Savepoint) spControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + DatabaseMetaData md = mock(DatabaseMetaData.class); + Savepoint sp = mock(Savepoint.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.connection(); - sessionControl.setReturnValue(con, 3); - session.isOpen(); - sessionControl.setReturnValue(true, 1); - md.supportsSavepoints(); - mdControl.setReturnValue(true, 1); - con.getMetaData(); - conControl.setReturnValue(md, 1); - con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1); - conControl.setReturnValue(sp, 1); - con.rollback(sp); - conControl.setVoidCallable(1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(1); - - dsControl.replay(); - conControl.replay(); - mdControl.replay(); - spControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(md.supportsSavepoints()).willReturn(true); + given(con.getMetaData()).willReturn(md); + given(con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1)).willReturn(sp); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.isConnected()).willReturn(true); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setJdbcExceptionTranslator(new SQLStateSQLExceptionTranslator()); @@ -1690,16 +1222,14 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - mdControl.verify(); - spControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + + verify(con).setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1); + verify(con).rollback(sp); + verify(session).close(); + verify(tx).commit(); } + @Test public void testTransactionCommitWithNonExistingDatabase() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean(); @@ -1742,6 +1272,7 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); } + @Test public void testTransactionCommitWithPreBoundSessionAndNonExistingDatabase() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean(); @@ -1792,6 +1323,7 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); } + @Test public void testTransactionCommitWithNonExistingDatabaseAndLazyConnection() throws Exception { DriverManagerDataSource dsTarget = new DriverManagerDataSource(); final LazyConnectionDataSourceProxy ds = new LazyConnectionDataSourceProxy(); @@ -1835,28 +1367,14 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); } + @Test public void testTransactionFlush() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.flush(); - sessionControl.setVoidCallable(1); - tx.commit(); - txControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); HibernateTransactionManager tm = new HibernateTransactionManager(sf); tm.setPrepareConnection(false); @@ -1876,17 +1394,9 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - } - @Override - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + verify(session).flush(); + verify(tx).commit(); + verify(session).close(); } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java index 60d9b82d9b..0b61d59160 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/LocalSessionFactoryBeanTests.java @@ -16,6 +16,13 @@ package org.springframework.orm.hibernate3; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,9 +38,6 @@ import java.util.Set; import javax.transaction.TransactionManager; -import junit.framework.TestCase; - -import org.easymock.MockControl; import org.hibernate.HibernateException; import org.hibernate.Interceptor; import org.hibernate.SessionFactory; @@ -51,6 +55,7 @@ import org.hibernate.engine.FilterDefinition; import org.hibernate.event.MergeEvent; import org.hibernate.event.MergeEventListener; import org.hibernate.mapping.TypeDef; +import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.ClassPathResource; @@ -60,10 +65,12 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -public class LocalSessionFactoryBeanTests extends TestCase { +public class LocalSessionFactoryBeanTests { + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithDataSource() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); @@ -99,6 +106,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals("newSessionFactory", invocations.get(0)); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithCacheRegionFactory() throws Exception { final RegionFactory regionFactory = new NoCachingRegionFactory(null); @@ -134,6 +142,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals("newSessionFactory", invocations.get(0)); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithCacheProvider() throws Exception { final CacheProvider cacheProvider = new NoCacheProvider(); @@ -170,6 +179,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals("newSessionFactory", invocations.get(0)); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithTransactionAwareDataSource() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); @@ -207,11 +217,11 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals("newSessionFactory", invocations.get(0)); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithDataSourceAndMappingResources() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); - MockControl tmControl = MockControl.createControl(TransactionManager.class); - final TransactionManager tm = (TransactionManager) tmControl.getMock(); + final TransactionManager tm = mock(TransactionManager.class); final List invocations = new ArrayList(); LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @Override @@ -254,6 +264,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals("newSessionFactory", invocations.get(2)); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithDataSourceAndMappingJarLocations() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); @@ -289,6 +300,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertTrue(invocations.contains("newSessionFactory")); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithDataSourceAndProperties() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); @@ -333,6 +345,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertTrue(invocations.contains("newSessionFactory")); } + @Test public void testLocalSessionFactoryBeanWithValidProperties() throws Exception { final Set invocations = new HashSet(); LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @@ -354,6 +367,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertTrue(invocations.contains("newSessionFactory")); } + @Test public void testLocalSessionFactoryBeanWithInvalidProperties() throws Exception { LocalSessionFactoryBean sfb = new LocalSessionFactoryBean(); sfb.setMappingResources(new String[0]); @@ -368,6 +382,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { } } + @Test public void testLocalSessionFactoryBeanWithInvalidMappings() throws Exception { LocalSessionFactoryBean sfb = new LocalSessionFactoryBean(); sfb.setMappingResources(new String[]{"mapping.hbm.xml"}); @@ -379,12 +394,9 @@ public class LocalSessionFactoryBeanTests extends TestCase { } } + @Test public void testLocalSessionFactoryBeanWithCustomSessionFactory() throws Exception { - MockControl factoryControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sessionFactory = (SessionFactory) factoryControl.getMock(); - sessionFactory.close(); - factoryControl.setVoidCallable(1); - factoryControl.replay(); + final SessionFactory sessionFactory = mock(SessionFactory.class); LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @Override protected SessionFactory newSessionFactory(Configuration config) { @@ -397,9 +409,10 @@ public class LocalSessionFactoryBeanTests extends TestCase { sfb.afterPropertiesSet(); assertTrue(sessionFactory == sfb.getObject()); sfb.destroy(); - factoryControl.verify(); + verify(sessionFactory).close(); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithEntityInterceptor() throws Exception { LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @@ -415,9 +428,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { }; sfb.setMappingResources(new String[0]); sfb.setDataSource(new DriverManagerDataSource()); - MockControl interceptorControl = MockControl.createControl(Interceptor.class); - Interceptor entityInterceptor = (Interceptor) interceptorControl.getMock(); - interceptorControl.replay(); + Interceptor entityInterceptor = mock(Interceptor.class); sfb.setEntityInterceptor(entityInterceptor); try { sfb.afterPropertiesSet(); @@ -429,6 +440,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { } } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithNamingStrategy() throws Exception { LocalSessionFactoryBean sfb = new LocalSessionFactoryBean() { @@ -455,6 +467,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { } } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithCacheStrategies() throws Exception { final Properties registeredClassCache = new Properties(); @@ -495,6 +508,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals(collectionCache, registeredCollectionCache); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithCacheStrategiesAndRegions() throws Exception { final Properties registeredClassCache = new Properties(); @@ -534,6 +548,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals(collectionCache, registeredCollectionCache); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithEventListeners() throws Exception { final Map registeredListeners = new HashMap(); @@ -562,6 +577,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { assertEquals(listeners, registeredListeners); } + @Test @SuppressWarnings("serial") public void testLocalSessionFactoryBeanWithEventListenerSet() throws Exception { final Map registeredListeners = new HashMap(); @@ -594,6 +610,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { } /* + @Test public void testLocalSessionFactoryBeanWithFilterDefinitions() throws Exception { XmlBeanFactory xbf = new XmlBeanFactory(new ClassPathResource("filterDefinitions.xml", getClass())); FilterTestLocalSessionFactoryBean sf = (FilterTestLocalSessionFactoryBean) xbf.getBean("&sessionFactory"); @@ -613,6 +630,7 @@ public class LocalSessionFactoryBeanTests extends TestCase { } */ + @Test public void testLocalSessionFactoryBeanWithTypeDefinitions() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new ClassPathResource("typeDefinitions.xml", getClass())); diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java index 2f264aa25f..8aa465e0e8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/HibernateDaoSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,25 +16,26 @@ package org.springframework.orm.hibernate3.support; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; import org.hibernate.SessionFactory; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.orm.hibernate3.HibernateTemplate; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -public class HibernateDaoSupportTests extends TestCase { +public class HibernateDaoSupportTests { + @Test public void testHibernateDaoSupportWithSessionFactory() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - sfControl.replay(); + SessionFactory sf = mock(SessionFactory.class); final List test = new ArrayList(); HibernateDaoSupport dao = new HibernateDaoSupport() { @Override @@ -47,9 +48,9 @@ public class HibernateDaoSupportTests extends TestCase { assertEquals("Correct SessionFactory", sf, dao.getSessionFactory()); assertEquals("Correct HibernateTemplate", sf, dao.getHibernateTemplate().getSessionFactory()); assertEquals("initDao called", test.size(), 1); - sfControl.verify(); } + @Test public void testHibernateDaoSupportWithHibernateTemplate() throws Exception { HibernateTemplate template = new HibernateTemplate(); final List test = new ArrayList(); diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java index aefb017e98..ab82cbcf63 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/LobTypeTests.java @@ -16,6 +16,11 @@ package org.springframework.orm.hibernate3.support; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; @@ -31,12 +36,11 @@ import javax.transaction.Status; import javax.transaction.Synchronization; import javax.transaction.TransactionManager; -import junit.framework.TestCase; -import org.easymock.MockControl; -import org.easymock.internal.ArrayMatcher; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; import org.springframework.orm.hibernate3.SessionFactoryUtils; @@ -46,39 +50,31 @@ import org.springframework.transaction.support.TransactionSynchronizationManager /** * @author Juergen Hoeller + * @author Phillip Webb * @since 05.03.2005 */ -public class LobTypeTests extends TestCase { +public class LobTypeTests { - private MockControl rsControl = MockControl.createControl(ResultSet.class); - private ResultSet rs = (ResultSet) rsControl.getMock(); - private MockControl psControl = MockControl.createControl(PreparedStatement.class); - private PreparedStatement ps = (PreparedStatement) psControl.getMock(); + private ResultSet rs = mock(ResultSet.class); + private PreparedStatement ps = mock(PreparedStatement.class); + private LobHandler lobHandler = mock(LobHandler.class); + private LobCreator lobCreator = mock(LobCreator.class); - private MockControl lobHandlerControl = MockControl.createControl(LobHandler.class); - private LobHandler lobHandler = (LobHandler) lobHandlerControl.getMock(); - private MockControl lobCreatorControl = MockControl.createControl(LobCreator.class); - private LobCreator lobCreator = (LobCreator) lobCreatorControl.getMock(); - - @Override - protected void setUp() throws SQLException { - lobHandler.getLobCreator(); - lobHandlerControl.setReturnValue(lobCreator); - lobCreator.close(); - lobCreatorControl.setVoidCallable(1); - - rsControl.replay(); - psControl.replay(); + @Before + public void setUp() throws SQLException { + given(lobHandler.getLobCreator()).willReturn(lobCreator); } - public void testClobStringType() throws Exception { - lobHandler.getClobAsString(rs, "column"); - lobHandlerControl.setReturnValue("content"); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); + @After + public void tearDown() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + verify(lobCreator).close(); + } - lobHandlerControl.replay(); - lobCreatorControl.replay(); + @Test + public void testClobStringType() throws Exception { + given(lobHandler.getClobAsString(rs, "column")).willReturn("content"); ClobStringType type = new ClobStringType(lobHandler, null); assertEquals(1, type.sqlTypes().length); @@ -101,29 +97,16 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testClobStringTypeWithSynchronizedSession() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getSessionFactory(); - sessionControl.setReturnValue(sf, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); - - lobHandler.getClobAsString(rs, "column"); - lobHandlerControl.setReturnValue("content"); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(lobHandler.getClobAsString(rs, "column")).willReturn("content"); ClobStringType type = new ClobStringType(lobHandler, null); assertEquals(1, type.sqlTypes().length); @@ -150,18 +133,13 @@ public class LobTypeTests extends TestCase { TransactionSynchronizationManager.clearSynchronization(); } - sfControl.verify(); - sessionControl.verify(); + verify(session).close(); + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testClobStringTypeWithFlushOnCommit() throws Exception { - lobHandler.getClobAsString(rs, "column"); - lobHandlerControl.setReturnValue("content"); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getClobAsString(rs, "column")).willReturn("content"); ClobStringType type = new ClobStringType(lobHandler, null); assertEquals(1, type.sqlTypes().length); @@ -182,73 +160,51 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testClobStringTypeWithJtaSynchronization() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); - lobHandler.getClobAsString(rs, "column"); - lobHandlerControl.setReturnValue("content"); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getClobAsString(rs, "column")).willReturn("content"); ClobStringType type = new ClobStringType(lobHandler, tm); assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, "content", 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.beforeCompletion(); synch.afterCompletion(Status.STATUS_COMMITTED); - tmControl.verify(); + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testClobStringTypeWithJtaSynchronizationAndRollback() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); - - lobHandler.getClobAsString(rs, "column"); - lobHandlerControl.setReturnValue("content"); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); + given(lobHandler.getClobAsString(rs, "column")).willReturn("content"); ClobStringType type = new ClobStringType(lobHandler, tm); assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, "content", 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.afterCompletion(Status.STATUS_ROLLEDBACK); - tmControl.verify(); + + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testBlobStringType() throws Exception { String content = "content"; byte[] contentBytes = content.getBytes(); - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(contentBytes); - lobCreator.setBlobAsBytes(ps, 1, contentBytes); - lobCreatorControl.setMatcher(new ArrayMatcher()); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes); BlobStringType type = new BlobStringType(lobHandler, null); assertEquals(1, type.sqlTypes().length); @@ -270,15 +226,12 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes); } + @Test public void testBlobStringTypeWithNull() throws Exception { - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(null); - lobCreator.setBlobAsBytes(ps, 1, null); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(null); BlobStringType type = new BlobStringType(lobHandler, null); assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null)); @@ -292,76 +245,56 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + + verify(lobCreator).setBlobAsBytes(ps, 1, null); } + @Test public void testBlobStringTypeWithJtaSynchronization() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); String content = "content"; byte[] contentBytes = content.getBytes(); - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(contentBytes); - lobCreator.setBlobAsBytes(ps, 1, contentBytes); - lobCreatorControl.setMatcher(new ArrayMatcher()); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes); BlobStringType type = new BlobStringType(lobHandler, tm); assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, content, 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.beforeCompletion(); synch.afterCompletion(Status.STATUS_COMMITTED); - tmControl.verify(); + + verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes); } + @Test public void testBlobStringTypeWithJtaSynchronizationAndRollback() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); String content = "content"; byte[] contentBytes = content.getBytes(); - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(contentBytes); - lobCreator.setBlobAsBytes(ps, 1, contentBytes); - lobCreatorControl.setMatcher(new ArrayMatcher()); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(contentBytes); BlobStringType type = new BlobStringType(lobHandler, tm); assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, content, 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.afterCompletion(Status.STATUS_ROLLEDBACK); - tmControl.verify(); + verify(lobCreator).setBlobAsBytes(ps, 1, contentBytes); } + @Test public void testBlobByteArrayType() throws Exception { byte[] content = "content".getBytes(); - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(content); - lobCreator.setBlobAsBytes(ps, 1, content); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content); BlobByteArrayType type = new BlobByteArrayType(lobHandler, null); assertEquals(1, type.sqlTypes().length); @@ -383,78 +316,56 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, content); } + @Test public void testBlobByteArrayTypeWithJtaSynchronization() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); byte[] content = "content".getBytes(); - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(content); - lobCreator.setBlobAsBytes(ps, 1, content); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content); BlobByteArrayType type = new BlobByteArrayType(lobHandler, tm); assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, content, 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.beforeCompletion(); synch.afterCompletion(Status.STATUS_COMMITTED); - tmControl.verify(); + verify(lobCreator).setBlobAsBytes(ps, 1, content); } + @Test public void testBlobByteArrayTypeWithJtaSynchronizationAndRollback() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); byte[] content = "content".getBytes(); - lobHandler.getBlobAsBytes(rs, "column"); - lobHandlerControl.setReturnValue(content); - lobCreator.setBlobAsBytes(ps, 1, content); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, "column")).willReturn(content); BlobByteArrayType type = new BlobByteArrayType(lobHandler, tm); assertEquals(content, type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, content, 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.afterCompletion(Status.STATUS_ROLLEDBACK); - tmControl.verify(); + verify(lobCreator).setBlobAsBytes(ps, 1, content); } + @Test public void testBlobSerializableType() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject("content"); oos.close(); - lobHandler.getBlobAsBinaryStream(rs, "column"); - lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray())); - lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray()); - lobCreatorControl.setMatcher(new ArrayMatcher()); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(new ByteArrayInputStream(baos.toByteArray())); BlobSerializableType type = new BlobSerializableType(lobHandler, null); assertEquals(1, type.sqlTypes().length); @@ -474,15 +385,12 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray()); } + @Test public void testBlobSerializableTypeWithNull() throws Exception { - lobHandler.getBlobAsBinaryStream(rs, "column"); - lobHandlerControl.setReturnValue(null); - lobCreator.setBlobAsBytes(ps, 1, null); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn(null); BlobSerializableType type = new BlobSerializableType(lobHandler, null); assertEquals(null, type.nullSafeGet(rs, new String[] {"column"}, null)); @@ -496,29 +404,23 @@ public class LobTypeTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, null); } + @Test public void testBlobSerializableTypeWithJtaSynchronization() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject("content"); oos.close(); - lobHandler.getBlobAsBinaryStream(rs, "column"); - lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray())); - lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray()); - lobCreatorControl.setMatcher(new ArrayMatcher()); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn( + new ByteArrayInputStream(baos.toByteArray())); BlobSerializableType type = new BlobSerializableType(lobHandler, tm); assertEquals(1, type.sqlTypes().length); @@ -527,36 +429,28 @@ public class LobTypeTests extends TestCase { assertTrue(type.isMutable()); assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, "content", 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.beforeCompletion(); synch.afterCompletion(Status.STATUS_COMMITTED); - tmControl.verify(); + verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray()); } + @Test public void testBlobSerializableTypeWithJtaSynchronizationAndRollback() throws Exception { - MockControl tmControl = MockControl.createControl(TransactionManager.class); - TransactionManager tm = (TransactionManager) tmControl.getMock(); + TransactionManager tm = mock(TransactionManager.class); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.getStatus(); - tmControl.setReturnValue(Status.STATUS_ACTIVE, 1); - tm.getTransaction(); - tmControl.setReturnValue(transaction, 1); + given(tm.getStatus()).willReturn(Status.STATUS_ACTIVE); + given(tm.getTransaction()).willReturn(transaction); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject("content"); oos.close(); - lobHandler.getBlobAsBinaryStream(rs, "column"); - lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray())); - lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray()); - lobCreatorControl.setMatcher(new ArrayMatcher()); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBinaryStream(rs, "column")).willReturn( + new ByteArrayInputStream(baos.toByteArray())); BlobSerializableType type = new BlobSerializableType(lobHandler, tm); assertEquals(1, type.sqlTypes().length); @@ -565,20 +459,15 @@ public class LobTypeTests extends TestCase { assertTrue(type.isMutable()); assertEquals("content", type.nullSafeGet(rs, new String[] {"column"}, null)); - tmControl.replay(); type.nullSafeSet(ps, "content", 1); Synchronization synch = transaction.getSynchronization(); assertNotNull(synch); synch.afterCompletion(Status.STATUS_ROLLEDBACK); - tmControl.verify(); + verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray()); } + @Test public void testHbm2JavaStyleInitialization() throws Exception { - rsControl.reset(); - psControl.reset(); - lobHandlerControl.reset(); - lobCreatorControl.reset(); - ClobStringType cst = null; BlobByteArrayType bbat = null; BlobSerializableType bst = null; @@ -612,21 +501,6 @@ public class LobTypeTests extends TestCase { catch (IllegalStateException ex) { // expected } + lobCreator.close(); } - - @Override - protected void tearDown() { - try { - rsControl.verify(); - psControl.verify(); - lobHandlerControl.verify(); - lobCreatorControl.verify(); - } - catch (IllegalStateException ex) { - // ignore: test method didn't call replay - } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java index 41058bb7c4..a51fc633e9 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/support/OpenSessionInViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,15 @@ package org.springframework.orm.hibernate3.support; -import static org.easymock.EasyMock.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.io.IOException; import java.sql.Connection; @@ -33,9 +37,7 @@ import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.transaction.TransactionManager; -import org.easymock.EasyMock; import org.hibernate.FlushMode; -import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.classic.Session; @@ -66,6 +68,7 @@ import org.springframework.web.context.support.StaticWebApplicationContext; /** * @author Juergen Hoeller * @author Rossen Stoyanchev + * @author Phillip Webb * @since 05.03.2005 */ public class OpenSessionInViewTests { @@ -90,19 +93,16 @@ public class OpenSessionInViewTests { @Test public void testOpenSessionInViewInterceptorWithSingleSession() throws Exception { - SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); interceptor.setSessionFactory(sf); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - session.setFlushMode(FlushMode.MANUAL); - expect(session.getSessionFactory()).andReturn(sf); - expect(session.isOpen()).andReturn(true); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.getSessionFactory()).willReturn(sf); + given(session.isOpen()).willReturn(true); interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(sf)); @@ -122,29 +122,14 @@ public class OpenSessionInViewTests { interceptor.postHandle(this.webRequest, null); interceptor.afterCompletion(this.webRequest, null); - verify(sf); - verify(session); - reset(sf); - reset(session); - replay(sf); - replay(session); - interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); - reset(sf); - reset(session); - expect(session.close()).andReturn(null); - replay(sf); - replay(session); - interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).close(); } @Test @@ -152,30 +137,19 @@ public class OpenSessionInViewTests { // Initial request thread - final SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); interceptor.setSessionFactory(sf); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - session.setFlushMode(FlushMode.MANUAL); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); - - AsyncWebRequest asyncWebRequest = createStrictMock(AsyncWebRequest.class); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.addTimeoutHandler((Runnable) anyObject()); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.startAsync(); - replay(asyncWebRequest); + AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); @@ -188,8 +162,6 @@ public class OpenSessionInViewTests { } }); - verify(asyncWebRequest); - interceptor.afterConcurrentHandlingStarted(this.webRequest); assertFalse(TransactionSynchronizationManager.hasResource(sf)); @@ -198,56 +170,34 @@ public class OpenSessionInViewTests { interceptor.preHandle(this.webRequest); assertTrue("Session not bound to async thread", TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - reset(sf); - replay(sf); - - verify(session); - reset(session); - replay(session); - interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - reset(sf); - - verify(session); - reset(session); - - expect(session.close()).andReturn(null); - - replay(sf); - replay(session); - interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); + verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); + verify(asyncWebRequest).startAsync(); } @Test public void testOpenSessionInViewInterceptorWithSingleSessionAndJtaTm() throws Exception { - final SessionFactoryImplementor sf = createStrictMock(SessionFactoryImplementor.class); - Session session = createStrictMock(Session.class); + final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class); + Session session = mock(Session.class); - TransactionManager tm = createStrictMock(TransactionManager.class); - expect(tm.getTransaction()).andReturn(null); - expect(tm.getTransaction()).andReturn(null); - replay(tm); + TransactionManager tm = mock(TransactionManager.class); + given(tm.getTransaction()).willReturn(null); + given(tm.getTransaction()).willReturn(null); OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); interceptor.setSessionFactory(sf); - expect(sf.openSession()).andReturn(session); - expect(sf.getTransactionManager()).andReturn(tm); - session.setFlushMode(FlushMode.MANUAL); - expect(sf.getTransactionManager()).andReturn(tm); - expect(session.isOpen()).andReturn(true); - - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(sf.getTransactionManager()).willReturn(tm); + given(sf.getTransactionManager()).willReturn(tm); + given(session.isOpen()).willReturn(true); interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(sf)); @@ -268,86 +218,50 @@ public class OpenSessionInViewTests { interceptor.postHandle(this.webRequest, null); interceptor.afterCompletion(this.webRequest, null); - verify(sf); - verify(session); - - reset(sf); - reset(session); - replay(sf); - replay(session); - interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); - - reset(sf); - reset(session); - expect(session.close()).andReturn(null); - replay(sf); - replay(session); - interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).close(); } @Test public void testOpenSessionInViewInterceptorWithSingleSessionAndFlush() throws Exception { - SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); interceptor.setSessionFactory(sf); interceptor.setFlushMode(HibernateAccessor.FLUSH_AUTO); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); interceptor.preHandle(this.webRequest); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); - reset(sf); - reset(session); - session.flush(); - replay(sf); - replay(session); interceptor.postHandle(this.webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); - reset(sf); - reset(session); - expect(session.close()).andReturn(null); - replay(sf); - replay(session); interceptor.afterCompletion(this.webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(sf)); - verify(sf); - verify(session); + verify(session).flush(); + verify(session).close(); } @Test public void testOpenSessionInViewInterceptorAndDeferredClose() throws Exception { - SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); OpenSessionInViewInterceptor interceptor = new OpenSessionInViewInterceptor(); interceptor.setSessionFactory(sf); interceptor.setSingleSession(false); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - session.setFlushMode(FlushMode.MANUAL); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); interceptor.preHandle(this.webRequest); org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true); @@ -367,43 +281,28 @@ public class OpenSessionInViewTests { interceptor.postHandle(this.webRequest, null); interceptor.afterCompletion(this.webRequest, null); - verify(sf); - verify(session); - - reset(sf); - reset(session); - expect(session.close()).andReturn(null); - replay(sf); - replay(session); - interceptor.postHandle(this.webRequest, null); interceptor.afterCompletion(this.webRequest, null); - verify(sf); - verify(session); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).close(); } @Test public void testOpenSessionInViewFilterWithSingleSession() throws Exception { - final SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - session.setFlushMode(FlushMode.MANUAL); - expect(session.close()).andReturn(null); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.close()).willReturn(null); - final SessionFactory sf2 = createStrictMock(SessionFactory.class); - Session session2 = createStrictMock(Session.class); + final SessionFactory sf2 = mock(SessionFactory.class); + Session session2 = mock(Session.class); - expect(sf2.openSession()).andReturn(session2); - expect(session2.getSessionFactory()).andReturn(sf2); - session2.setFlushMode(FlushMode.AUTO); - expect(session2.close()).andReturn(null); - replay(sf2); - replay(session2); + given(sf2.openSession()).willReturn(session2); + given(session2.getSessionFactory()).willReturn(sf2); + given(session2.close()).willReturn(null); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); @@ -448,26 +347,20 @@ public class OpenSessionInViewTests { assertFalse(TransactionSynchronizationManager.hasResource(sf2)); assertNotNull(this.request.getAttribute("invoked")); - verify(sf); - verify(session); - verify(sf2); - verify(session2); - + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session2).setFlushMode(FlushMode.AUTO); wac.close(); } @Test public void testOpenSessionInViewFilterAsyncScenario() throws Exception { - final SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); // Initial request during which concurrent handling starts.. - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - session.setFlushMode(FlushMode.MANUAL); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); @@ -490,13 +383,8 @@ public class OpenSessionInViewTests { } }; - AsyncWebRequest asyncWebRequest = createMock(AsyncWebRequest.class); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.addTimeoutHandler(EasyMock.anyObject()); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.startAsync(); - expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes(); - replay(asyncWebRequest); + AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); + given(asyncWebRequest.isAsyncStarted()).willReturn(true); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); @@ -513,46 +401,29 @@ public class OpenSessionInViewTests { assertFalse(TransactionSynchronizationManager.hasResource(sf)); assertEquals(1, count.get()); - verify(sf); - verify(session); - verify(asyncWebRequest); - - reset(sf); - reset(session); - reset(asyncWebRequest); // Async dispatch after concurrent handling produces result ... - expect(session.close()).andReturn(null); - expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes(); - - replay(sf); - replay(session); - replay(asyncWebRequest); - assertFalse(TransactionSynchronizationManager.hasResource(sf)); filter.doFilter(this.request, this.response, filterChain); assertFalse(TransactionSynchronizationManager.hasResource(sf)); assertEquals(2, count.get()); - verify(sf); - verify(session); - verify(asyncWebRequest); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); + verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); + verify(asyncWebRequest).startAsync(); wac.close(); } @Test public void testOpenSessionInViewFilterWithSingleSessionAndPreBoundSession() throws Exception { - final SessionFactory sf = createStrictMock(SessionFactory.class); - Session session = createStrictMock(Session.class); + final SessionFactory sf = mock(SessionFactory.class); + Session session = mock(Session.class); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - session.setFlushMode(FlushMode.MANUAL); - expect(session.close()).andReturn(null); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); @@ -588,43 +459,32 @@ public class OpenSessionInViewTests { interceptor.postHandle(this.webRequest, null); interceptor.afterCompletion(this.webRequest, null); - verify(sf); - verify(session); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).close(); wac.close(); } @Test public void testOpenSessionInViewFilterWithDeferredClose() throws Exception { - final SessionFactory sf = createStrictMock(SessionFactory.class); - final Session session = createStrictMock(Session.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - expect(session.getFlushMode()).andReturn(FlushMode.MANUAL); - session.setFlushMode(FlushMode.MANUAL); - replay(sf); - replay(session); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); - final SessionFactory sf2 = createStrictMock(SessionFactory.class); - final Session session2 = createStrictMock(Session.class); + final SessionFactory sf2 = mock(SessionFactory.class); + final Session session2 = mock(Session.class); - Transaction tx = createStrictMock(Transaction.class); - Connection con = createStrictMock(Connection.class); + Transaction tx = mock(Transaction.class); + Connection con = mock(Connection.class); - expect(sf2.openSession()).andReturn(session2); - expect(session2.connection()).andReturn(con); - expect(session2.beginTransaction()).andReturn(tx); - expect(session2.isConnected()).andReturn(true); - expect(session2.connection()).andReturn(con); - tx.commit(); - expect(con.isReadOnly()).andReturn(false); - session2.setFlushMode(FlushMode.MANUAL); - - replay(sf2); - replay(session2); - replay(tx); - replay(con); + given(sf2.openSession()).willReturn(session2); + given(session2.connection()).willReturn(con); + given(session2.beginTransaction()).willReturn(tx); + given(session2.isConnected()).willReturn(true); + given(session2.connection()).willReturn(con); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); @@ -653,13 +513,6 @@ public class OpenSessionInViewTests { org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true); SessionFactoryUtils.releaseSession(sess, sf); tm.commit(ts); - - verify(session); - reset(session); - - expect(session.close()).andReturn(null); - replay(session); - servletRequest.setAttribute("invoked", Boolean.TRUE); } }; @@ -668,17 +521,9 @@ public class OpenSessionInViewTests { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { - HibernateTransactionManager tm = new HibernateTransactionManager(sf2); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); tm.commit(ts); - - verify(session2); - reset(session2); - - expect(session2.close()).andReturn(null); - replay(session2); - filter.doFilter(servletRequest, servletResponse, filterChain); } }; @@ -688,39 +533,23 @@ public class OpenSessionInViewTests { filter2.doFilter(this.request, this.response, filterChain3); assertNotNull(this.request.getAttribute("invoked")); - verify(sf); - verify(session); - - verify(sf2); - verify(session2); - verify(tx); - verify(con); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(tx).commit(); + verify(session2).setFlushMode(FlushMode.MANUAL); + verify(session).close(); + verify(session2).close(); wac.close(); } @Test public void testOpenSessionInViewFilterWithDeferredCloseAndAlreadyActiveDeferredClose() throws Exception { - final SessionFactory sf = createStrictMock(SessionFactory.class); - final Session session = createStrictMock(Session.class); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); - expect(sf.openSession()).andReturn(session); - expect(session.getSessionFactory()).andReturn(sf); - expect(session.getFlushMode()).andReturn(FlushMode.MANUAL); - session.setFlushMode(FlushMode.MANUAL); - replay(sf); - replay(session); - -// sf.openSession(); -// sfControl.setReturnValue(session, 1); -// session.getSessionFactory(); -// sessionControl.setReturnValue(sf); -// session.getFlushMode(); -// sessionControl.setReturnValue(FlushMode.MANUAL, 1); -// session.setFlushMode(FlushMode.MANUAL); -// sessionControl.setVoidCallable(1); -// sfControl.replay(); -// sessionControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); @@ -754,16 +583,6 @@ public class OpenSessionInViewTests { org.hibernate.Session sess = SessionFactoryUtils.getSession(sf, true); SessionFactoryUtils.releaseSession(sess, sf); tm.commit(ts); - - verify(session); - reset(session); - try { - expect(session.close()).andReturn(null); - } - catch (HibernateException ex) { - } - replay(session); - servletRequest.setAttribute("invoked", Boolean.TRUE); } }; @@ -782,8 +601,8 @@ public class OpenSessionInViewTests { interceptor.postHandle(webRequest, null); interceptor.afterCompletion(webRequest, null); - verify(sf); - verify(session); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(session).close(); wac.close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java b/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java index 43a44e3498..91a7277e78 100644 --- a/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/ibatis/SqlMapClientTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,13 @@ package org.springframework.orm.ibatis; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; @@ -25,24 +32,25 @@ import java.util.Map; import javax.sql.DataSource; -import com.ibatis.sqlmap.client.SqlMapClient; -import com.ibatis.sqlmap.client.SqlMapExecutor; -import com.ibatis.sqlmap.client.SqlMapSession; -import com.ibatis.sqlmap.client.event.RowHandler; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.dao.DataAccessException; import org.springframework.jdbc.JdbcUpdateAffectedIncorrectNumberOfRowsException; import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport; +import com.ibatis.sqlmap.client.SqlMapClient; +import com.ibatis.sqlmap.client.SqlMapExecutor; +import com.ibatis.sqlmap.client.SqlMapSession; +import com.ibatis.sqlmap.client.event.RowHandler; + /** * @author Juergen Hoeller * @author Alef Arendsen + * @author Phillip Webb * @since 09.10.2004 */ -public class SqlMapClientTests extends TestCase { +public class SqlMapClientTests { + @Test public void testSqlMapClientFactoryBeanWithoutConfig() throws Exception { SqlMapClientFactoryBean factory = new SqlMapClientFactoryBean(); // explicitly set to null, don't know why ;-) @@ -56,32 +64,15 @@ public class SqlMapClientTests extends TestCase { } } + @Test public void testSqlMapClientTemplate() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - ds.getConnection(); - dsControl.setReturnValue(con, 1); - con.close(); - conControl.setVoidCallable(1); - dsControl.replay(); - conControl.replay(); + DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SqlMapSession session = mock(SqlMapSession.class); + SqlMapClient client = mock(SqlMapClient.class); - MockControl sessionControl = MockControl.createControl(SqlMapSession.class); - final SqlMapSession session = (SqlMapSession) sessionControl.getMock(); - MockControl clientControl = MockControl.createControl(SqlMapClient.class); - SqlMapClient client = (SqlMapClient) clientControl.getMock(); - client.openSession(); - clientControl.setReturnValue(session, 1); - session.getCurrentConnection(); - sessionControl.setReturnValue(null, 1); - session.setUserConnection(con); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - sessionControl.replay(); - clientControl.replay(); + given(ds.getConnection()).willReturn(con); + given(client.openSession()).willReturn(session); SqlMapClientTemplate template = new SqlMapClientTemplate(); template.setDataSource(ds); @@ -95,30 +86,21 @@ public class SqlMapClientTests extends TestCase { } }); assertEquals("done", result); - dsControl.verify(); - conControl.verify(); - sessionControl.verify(); - clientControl.verify(); + + verify(con).close(); + verify(session).setUserConnection(con); + verify(session).close(); } + @Test public void testSqlMapClientTemplateWithNestedSqlMapSession() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - final Connection con = (Connection) conControl.getMock(); - dsControl.replay(); - conControl.replay(); + DataSource ds = mock(DataSource.class); + final Connection con = mock(Connection.class); + final SqlMapSession session = mock(SqlMapSession.class); + SqlMapClient client = mock(SqlMapClient.class); - MockControl sessionControl = MockControl.createControl(SqlMapSession.class); - final SqlMapSession session = (SqlMapSession) sessionControl.getMock(); - MockControl clientControl = MockControl.createControl(SqlMapClient.class); - SqlMapClient client = (SqlMapClient) clientControl.getMock(); - client.openSession(); - clientControl.setReturnValue(session, 1); - session.getCurrentConnection(); - sessionControl.setReturnValue(con, 1); - sessionControl.replay(); - clientControl.replay(); + given(client.openSession()).willReturn(session); + given(session.getCurrentConnection()).willReturn(con); SqlMapClientTemplate template = new SqlMapClientTemplate(); template.setDataSource(ds); @@ -132,210 +114,157 @@ public class SqlMapClientTests extends TestCase { } }); assertEquals("done", result); - dsControl.verify(); - conControl.verify(); - sessionControl.verify(); - clientControl.verify(); } + @Test public void testQueryForObjectOnSqlMapSession() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl clientControl = MockControl.createControl(SqlMapClient.class); - SqlMapClient client = (SqlMapClient) clientControl.getMock(); - MockControl sessionControl = MockControl.createControl(SqlMapSession.class); - SqlMapSession session = (SqlMapSession) sessionControl.getMock(); + DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + SqlMapClient client = mock(SqlMapClient.class); + SqlMapSession session = mock(SqlMapSession.class); - ds.getConnection(); - dsControl.setReturnValue(con, 1); - con.close(); - conControl.setVoidCallable(1); - client.getDataSource(); - clientControl.setReturnValue(ds, 2); - client.openSession(); - clientControl.setReturnValue(session, 1); - session.getCurrentConnection(); - sessionControl.setReturnValue(null, 1); - session.setUserConnection(con); - sessionControl.setVoidCallable(1); - session.queryForObject("myStatement", "myParameter"); - sessionControl.setReturnValue("myResult", 1); - session.close(); - sessionControl.setVoidCallable(1); - - dsControl.replay(); - conControl.replay(); - clientControl.replay(); - sessionControl.replay(); + given(ds.getConnection()).willReturn(con); + given(client.getDataSource()).willReturn(ds); + given(client.openSession()).willReturn(session); + given(session.queryForObject("myStatement", "myParameter")).willReturn("myResult"); SqlMapClientTemplate template = new SqlMapClientTemplate(); template.setSqlMapClient(client); template.afterPropertiesSet(); assertEquals("myResult", template.queryForObject("myStatement", "myParameter")); - dsControl.verify(); - clientControl.verify(); + verify(con).close(); + verify(session).setUserConnection(con); + verify(session).close(); } + @Test public void testQueryForObject() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForObject("myStatement", null); - template.executorControl.setReturnValue("myResult", 1); - template.executorControl.replay(); + given(template.executor.queryForObject("myStatement", null)).willReturn("myResult"); assertEquals("myResult", template.queryForObject("myStatement")); - template.executorControl.verify(); } + @Test public void testQueryForObjectWithParameter() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForObject("myStatement", "myParameter"); - template.executorControl.setReturnValue("myResult", 1); - template.executorControl.replay(); + given(template.executor.queryForObject("myStatement", "myParameter")).willReturn("myResult"); assertEquals("myResult", template.queryForObject("myStatement", "myParameter")); - template.executorControl.verify(); } + @Test public void testQueryForObjectWithParameterAndResultObject() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForObject("myStatement", "myParameter", "myResult"); - template.executorControl.setReturnValue("myResult", 1); - template.executorControl.replay(); + given(template.executor.queryForObject("myStatement", "myParameter", + "myResult")).willReturn("myResult"); assertEquals("myResult", template.queryForObject("myStatement", "myParameter", "myResult")); - template.executorControl.verify(); } + @Test public void testQueryForList() throws SQLException { List result = new ArrayList(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForList("myStatement", null); - template.executorControl.setReturnValue(result, 1); - template.executorControl.replay(); + given(template.executor.queryForList("myStatement", null)).willReturn(result); assertEquals(result, template.queryForList("myStatement")); - template.executorControl.verify(); } + @Test public void testQueryForListWithParameter() throws SQLException { List result = new ArrayList(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForList("myStatement", "myParameter"); - template.executorControl.setReturnValue(result, 1); - template.executorControl.replay(); + given(template.executor.queryForList("myStatement", "myParameter")).willReturn(result); assertEquals(result, template.queryForList("myStatement", "myParameter")); - template.executorControl.verify(); } + @Test public void testQueryForListWithResultSize() throws SQLException { List result = new ArrayList(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForList("myStatement", null, 10, 20); - template.executorControl.setReturnValue(result, 1); - template.executorControl.replay(); + given(template.executor.queryForList("myStatement", null, 10, 20)).willReturn(result); assertEquals(result, template.queryForList("myStatement", 10, 20)); - template.executorControl.verify(); } + @Test public void testQueryForListParameterAndWithResultSize() throws SQLException { List result = new ArrayList(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForList("myStatement", "myParameter", 10, 20); - template.executorControl.setReturnValue(result, 1); - template.executorControl.replay(); + given(template.executor.queryForList("myStatement", "myParameter", 10, 20)).willReturn(result); assertEquals(result, template.queryForList("myStatement", "myParameter", 10, 20)); - template.executorControl.verify(); } + @Test public void testQueryWithRowHandler() throws SQLException { RowHandler rowHandler = new TestRowHandler(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryWithRowHandler("myStatement", null, rowHandler); - template.executorControl.setVoidCallable(1); - template.executorControl.replay(); template.queryWithRowHandler("myStatement", rowHandler); - template.executorControl.verify(); + verify(template.executor).queryWithRowHandler("myStatement", null, rowHandler); } + @Test public void testQueryWithRowHandlerWithParameter() throws SQLException { RowHandler rowHandler = new TestRowHandler(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryWithRowHandler("myStatement", "myParameter", rowHandler); - template.executorControl.setVoidCallable(1); - template.executorControl.replay(); template.queryWithRowHandler("myStatement", "myParameter", rowHandler); - template.executorControl.verify(); + verify(template.executor).queryWithRowHandler("myStatement", "myParameter", rowHandler); } + @Test public void testQueryForMap() throws SQLException { Map result = new HashMap(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForMap("myStatement", "myParameter", "myKey"); - template.executorControl.setReturnValue(result, 1); - template.executorControl.replay(); + given(template.executor.queryForMap("myStatement", "myParameter", "myKey")).willReturn(result); assertEquals(result, template.queryForMap("myStatement", "myParameter", "myKey")); - template.executorControl.verify(); } + @Test public void testQueryForMapWithValueProperty() throws SQLException { Map result = new HashMap(); TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.queryForMap("myStatement", "myParameter", "myKey", "myValue"); - template.executorControl.setReturnValue(result, 1); - template.executorControl.replay(); + given(template.executor.queryForMap("myStatement", "myParameter", "myKey", + "myValue")).willReturn(result); assertEquals(result, template.queryForMap("myStatement", "myParameter", "myKey", "myValue")); - template.executorControl.verify(); } + @Test public void testInsert() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.insert("myStatement", null); - template.executorControl.setReturnValue("myResult", 1); - template.executorControl.replay(); + given(template.executor.insert("myStatement", null)).willReturn("myResult"); assertEquals("myResult", template.insert("myStatement")); - template.executorControl.verify(); } + @Test public void testInsertWithParameter() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.insert("myStatement", "myParameter"); - template.executorControl.setReturnValue("myResult", 1); - template.executorControl.replay(); + given(template.executor.insert("myStatement", "myParameter")).willReturn("myResult"); assertEquals("myResult", template.insert("myStatement", "myParameter")); - template.executorControl.verify(); } + @Test public void testUpdate() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.update("myStatement", null); - template.executorControl.setReturnValue(10, 1); - template.executorControl.replay(); + given(template.executor.update("myStatement", null)).willReturn(10); assertEquals(10, template.update("myStatement")); - template.executorControl.verify(); } + @Test public void testUpdateWithParameter() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.update("myStatement", "myParameter"); - template.executorControl.setReturnValue(10, 1); - template.executorControl.replay(); + given(template.executor.update("myStatement", "myParameter")).willReturn(10); assertEquals(10, template.update("myStatement", "myParameter")); - template.executorControl.verify(); } + @Test public void testUpdateWithRequiredRowsAffected() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.update("myStatement", "myParameter"); - template.executorControl.setReturnValue(10, 1); - template.executorControl.replay(); + given(template.executor.update("myStatement", "myParameter")).willReturn(10); template.update("myStatement", "myParameter", 10); - template.executorControl.verify(); + verify(template.executor).update("myStatement", "myParameter"); } + @Test public void testUpdateWithRequiredRowsAffectedAndInvalidRowCount() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.update("myStatement", "myParameter"); - template.executorControl.setReturnValue(20, 1); - template.executorControl.replay(); + given(template.executor.update("myStatement", "myParameter")).willReturn(20); try { template.update("myStatement", "myParameter", 10); fail("Should have thrown JdbcUpdateAffectedIncorrectNumberOfRowsException"); @@ -345,41 +274,34 @@ public class SqlMapClientTests extends TestCase { assertEquals(10, ex.getExpectedRowsAffected()); assertEquals(20, ex.getActualRowsAffected()); } - template.executorControl.verify(); } + @Test public void testDelete() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.delete("myStatement", null); - template.executorControl.setReturnValue(10, 1); - template.executorControl.replay(); + given(template.executor.delete("myStatement", null)).willReturn(10); assertEquals(10, template.delete("myStatement")); - template.executorControl.verify(); } + @Test public void testDeleteWithParameter() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.delete("myStatement", "myParameter"); - template.executorControl.setReturnValue(10, 1); - template.executorControl.replay(); + given(template.executor.delete("myStatement", "myParameter")).willReturn(10); assertEquals(10, template.delete("myStatement", "myParameter")); - template.executorControl.verify(); } + @Test public void testDeleteWithRequiredRowsAffected() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.delete("myStatement", "myParameter"); - template.executorControl.setReturnValue(10, 1); - template.executorControl.replay(); + given(template.executor.delete("myStatement", "myParameter")).willReturn(10); template.delete("myStatement", "myParameter", 10); - template.executorControl.verify(); + verify(template.executor).delete("myStatement", "myParameter"); } + @Test public void testDeleteWithRequiredRowsAffectedAndInvalidRowCount() throws SQLException { TestSqlMapClientTemplate template = new TestSqlMapClientTemplate(); - template.executor.delete("myStatement", "myParameter"); - template.executorControl.setReturnValue(20, 1); - template.executorControl.replay(); + given(template.executor.delete("myStatement", "myParameter")).willReturn(20); try { template.delete("myStatement", "myParameter", 10); fail("Should have thrown JdbcUpdateAffectedIncorrectNumberOfRowsException"); @@ -389,20 +311,17 @@ public class SqlMapClientTests extends TestCase { assertEquals(10, ex.getExpectedRowsAffected()); assertEquals(20, ex.getActualRowsAffected()); } - template.executorControl.verify(); } + @Test public void testSqlMapClientDaoSupport() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - DataSource ds = (DataSource) dsControl.getMock(); + DataSource ds = mock(DataSource.class); SqlMapClientDaoSupport testDao = new SqlMapClientDaoSupport() { }; testDao.setDataSource(ds); assertEquals(ds, testDao.getDataSource()); - MockControl clientControl = MockControl.createControl(SqlMapClient.class); - SqlMapClient client = (SqlMapClient) clientControl.getMock(); - clientControl.replay(); + SqlMapClient client = mock(SqlMapClient.class); testDao.setSqlMapClient(client); assertEquals(client, testDao.getSqlMapClient()); @@ -419,8 +338,7 @@ public class SqlMapClientTests extends TestCase { private static class TestSqlMapClientTemplate extends SqlMapClientTemplate { - public MockControl executorControl = MockControl.createControl(SqlMapExecutor.class); - public SqlMapExecutor executor = (SqlMapExecutor) executorControl.getMock(); + public SqlMapExecutor executor = mock(SqlMapExecutor.class); @Override public Object execute(SqlMapClientCallback action) throws DataAccessException { diff --git a/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java b/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java index d92b60d3f4..948c4e7ec2 100644 --- a/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/ibatis/support/LobTypeHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,29 @@ package org.springframework.orm.ibatis.support; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.InputStream; import java.io.ObjectOutputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.SQLException; import java.util.Arrays; import java.util.List; import javax.sql.DataSource; -import junit.framework.TestCase; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jdbc.datasource.DataSourceUtils; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy; @@ -41,42 +49,33 @@ import org.springframework.transaction.support.TransactionSynchronizationManager /** * @author Juergen Hoeller + * @author Phillip Webb * @since 27.02.2005 */ -public class LobTypeHandlerTests extends TestCase { +public class LobTypeHandlerTests { - private MockControl rsControl = MockControl.createControl(ResultSet.class); - private ResultSet rs = (ResultSet) rsControl.getMock(); - private MockControl psControl = MockControl.createControl(PreparedStatement.class); - private PreparedStatement ps = (PreparedStatement) psControl.getMock(); + private ResultSet rs = mock(ResultSet.class); + private PreparedStatement ps = mock(PreparedStatement.class); - private MockControl lobHandlerControl = MockControl.createControl(LobHandler.class); - private LobHandler lobHandler = (LobHandler) lobHandlerControl.getMock(); - private MockControl lobCreatorControl = MockControl.createControl(LobCreator.class); - private LobCreator lobCreator = (LobCreator) lobCreatorControl.getMock(); + private LobHandler lobHandler = mock(LobHandler.class); + private LobCreator lobCreator = mock(LobCreator.class); - @Override - protected void setUp() throws SQLException { - rs.findColumn("column"); - rsControl.setReturnValue(1); - - lobHandler.getLobCreator(); - lobHandlerControl.setReturnValue(lobCreator); - lobCreator.close(); - lobCreatorControl.setVoidCallable(1); - - rsControl.replay(); - psControl.replay(); + @Before + public void setUp() throws Exception { + given(rs.findColumn("column")).willReturn(1); + given(lobHandler.getLobCreator()).willReturn(lobCreator); } - public void testClobStringTypeHandler() throws Exception { - lobHandler.getClobAsString(rs, 1); - lobHandlerControl.setReturnValue("content", 2); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); + @After + public void tearDown() throws Exception { + verify(lobCreator).close(); + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + } - lobHandlerControl.replay(); - lobCreatorControl.replay(); + @Test + public void testClobStringTypeHandler() throws Exception { + given(lobHandler.getClobAsString(rs, 1)).willReturn("content"); ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler); assertEquals("content", type.valueOf("content")); @@ -95,19 +94,15 @@ public class LobTypeHandlerTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testClobStringTypeWithSynchronizedConnection() throws Exception { DataSource dsTarget = new DriverManagerDataSource(); DataSource ds = new LazyConnectionDataSourceProxy(dsTarget); - lobHandler.getClobAsString(rs, 1); - lobHandlerControl.setReturnValue("content", 2); - lobCreator.setClobAsString(ps, 1, "content"); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getClobAsString(rs, 1)).willReturn("content"); ClobStringTypeHandler type = new ClobStringTypeHandler(lobHandler); assertEquals("content", type.valueOf("content")); @@ -129,17 +124,13 @@ public class LobTypeHandlerTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setClobAsString(ps, 1, "content"); } + @Test public void testBlobByteArrayType() throws Exception { byte[] content = "content".getBytes(); - lobHandler.getBlobAsBytes(rs, 1); - lobHandlerControl.setReturnValue(content, 2); - lobCreator.setBlobAsBytes(ps, 1, content); - lobCreatorControl.setVoidCallable(1); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBytes(rs, 1)).willReturn(content); BlobByteArrayTypeHandler type = new BlobByteArrayTypeHandler(lobHandler); assertTrue(Arrays.equals(content, (byte[]) type.valueOf("content"))); @@ -157,33 +148,24 @@ public class LobTypeHandlerTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, content); } + @Test public void testBlobSerializableType() throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject("content"); oos.close(); - lobHandler.getBlobAsBinaryStream(rs, 1); - lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()), 1); - lobHandler.getBlobAsBinaryStream(rs, 1); - lobHandlerControl.setReturnValue(new ByteArrayInputStream(baos.toByteArray()), 1); - lobCreator.setBlobAsBytes(ps, 1, baos.toByteArray()); - lobCreatorControl.setMatcher(new ArgumentsMatcher() { + given(lobHandler.getBlobAsBinaryStream(rs, 1)).willAnswer(new Answer() { @Override - public boolean matches(Object[] o1, Object[] o2) { - return Arrays.equals((byte[]) o1[2], (byte[]) o2[2]); - } - @Override - public String toString(Object[] objects) { - return null; + public InputStream answer(InvocationOnMock invocation) + throws Throwable { + return new ByteArrayInputStream(baos.toByteArray()); } }); - lobHandlerControl.replay(); - lobCreatorControl.replay(); - BlobSerializableTypeHandler type = new BlobSerializableTypeHandler(lobHandler); assertEquals("content", type.valueOf("content")); assertEquals("content", type.getResult(rs, "column")); @@ -200,15 +182,12 @@ public class LobTypeHandlerTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, baos.toByteArray()); } + @Test public void testBlobSerializableTypeWithNull() throws Exception { - lobHandler.getBlobAsBinaryStream(rs, 1); - lobHandlerControl.setReturnValue(null, 2); - lobCreator.setBlobAsBytes(ps, 1, null); - - lobHandlerControl.replay(); - lobCreatorControl.replay(); + given(lobHandler.getBlobAsBinaryStream(rs, 1)).willReturn(null); BlobSerializableTypeHandler type = new BlobSerializableTypeHandler(lobHandler); assertEquals(null, type.valueOf(null)); @@ -225,21 +204,6 @@ public class LobTypeHandlerTests extends TestCase { finally { TransactionSynchronizationManager.clearSynchronization(); } + verify(lobCreator).setBlobAsBytes(ps, 1, null); } - - @Override - protected void tearDown() { - try { - rsControl.verify(); - psControl.verify(); - lobHandlerControl.verify(); - lobCreatorControl.verify(); - } - catch (IllegalStateException ex) { - // ignore: test method didn't call replay - } - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java index 21fa381178..c88e58cd07 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,36 +16,34 @@ package org.springframework.orm.jdo; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; -import junit.framework.TestCase; - import org.aopalliance.intercept.Interceptor; import org.aopalliance.intercept.Invocation; import org.aopalliance.intercept.MethodInvocation; -import org.easymock.MockControl; +import org.junit.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * @author Juergen Hoeller + * @author Phillip Webb */ -public class JdoInterceptorTests extends TestCase { +public class JdoInterceptorTests { + @Test public void testInterceptor() { - MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); - MockControl pmControl = MockControl.createControl(PersistenceManager.class); - PersistenceManager pm = (PersistenceManager) pmControl.getMock(); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); + PersistenceManager pm = mock(PersistenceManager.class); + given(pmf.getPersistenceManager()).willReturn(pm); JdoInterceptor interceptor = new JdoInterceptor(); interceptor.setPersistenceManagerFactory(pmf); @@ -56,17 +54,13 @@ public class JdoInterceptorTests extends TestCase { fail("Should not have thrown Throwable: " + t.getMessage()); } - pmfControl.verify(); - pmControl.verify(); + verify(pm).close(); } + @Test public void testInterceptorWithPrebound() { - MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); - MockControl pmControl = MockControl.createControl(PersistenceManager.class); - PersistenceManager pm = (PersistenceManager) pmControl.getMock(); - pmfControl.replay(); - pmControl.replay(); + PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); + PersistenceManager pm = mock(PersistenceManager.class); TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm)); JdoInterceptor interceptor = new JdoInterceptor(); @@ -80,9 +74,6 @@ public class JdoInterceptorTests extends TestCase { finally { TransactionSynchronizationManager.unbindResource(pmf); } - - pmfControl.verify(); - pmControl.verify(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java index 2baf4d205a..29c882b2b6 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,20 @@ package org.springframework.orm.jdo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; + import javax.jdo.JDODataStoreException; import javax.jdo.JDOException; import javax.jdo.JDOFatalDataStoreException; @@ -33,44 +41,29 @@ import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 03.06.2003 */ -public class JdoTemplateTests extends TestCase { +public class JdoTemplateTests { - private MockControl pmfControl; private PersistenceManagerFactory pmf; - private MockControl pmControl; private PersistenceManager pm; - @Override - protected void setUp() { - pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - pmf = (PersistenceManagerFactory) pmfControl.getMock(); - pmControl = MockControl.createControl(PersistenceManager.class); - pm = (PersistenceManager) pmControl.getMock(); - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); - } - - @Override - protected void tearDown() { - try { - pmfControl.verify(); - pmControl.verify(); - } - catch (IllegalStateException ex) { - // ignore: test method didn't call replay - } + @Before + public void setUp() { + pmf = mock(PersistenceManagerFactory.class); + pm = mock(PersistenceManager.class); } + @Test public void testTemplateExecuteWithNotAllowCreate() { JdoTemplate jt = new JdoTemplate(); jt.setPersistenceManagerFactory(pmf); @@ -89,10 +82,8 @@ public class JdoTemplateTests extends TestCase { } } + @Test public void testTemplateExecuteWithNotAllowCreateAndThreadBound() { - pmfControl.replay(); - pmControl.replay(); - JdoTemplate jt = new JdoTemplate(pmf); jt.setAllowCreate(false); TransactionSynchronizationManager.bindResource(pmf, new PersistenceManagerHolder(pm)); @@ -108,13 +99,9 @@ public class JdoTemplateTests extends TestCase { TransactionSynchronizationManager.unbindResource(pmf); } + @Test public void testTemplateExecuteWithNewPersistenceManager() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); final List l = new ArrayList(); @@ -126,14 +113,11 @@ public class JdoTemplateTests extends TestCase { } }); assertTrue("Correct result list", result == l); + verify(pm).close(); } + @Test public void testTemplateExecuteWithThreadBoundAndFlushEager() { - pm.flush(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - JdoTemplate jt = new JdoTemplate(pmf); jt.setFlushEager(true); jt.setAllowCreate(false); @@ -148,481 +132,291 @@ public class JdoTemplateTests extends TestCase { }); assertTrue("Correct result list", result == l); TransactionSynchronizationManager.unbindResource(pmf); + verify(pm).flush(); } + @Test public void testGetObjectById() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.getObjectById("0", true); - pmControl.setReturnValue("A"); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.getObjectById("0", true)).willReturn("A"); JdoTemplate jt = new JdoTemplate(pmf); assertEquals("A", jt.getObjectById("0")); + verify(pm).close(); } + @Test public void testGetObjectByIdWithClassAndValue() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.getObjectById(String.class, "0"); - pmControl.setReturnValue("A"); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.getObjectById(String.class, "0")).willReturn("A"); JdoTemplate jt = new JdoTemplate(pmf); assertEquals("A", jt.getObjectById(String.class, "0")); + verify(pm).close(); } + @Test public void testEvict() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.evict("0"); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.evict("0"); + verify(pm).evict("0"); + verify(pm).close(); } + @Test public void testEvictAllWithCollection() { Collection coll = new HashSet(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.evictAll(coll); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.evictAll(coll); + verify(pm).evictAll(coll); + verify(pm).close(); } + @Test public void testEvictAll() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.evictAll(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.evictAll(); + verify(pm).evictAll(); + verify(pm).close(); } + @Test public void testRefresh() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.refresh("0"); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.refresh("0"); + verify(pm).refresh("0"); + verify(pm).close(); } + @Test public void testRefreshAllWithCollection() { Collection coll = new HashSet(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.refreshAll(coll); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.refreshAll(coll); + verify(pm).refreshAll(coll); + verify(pm).close(); } + @Test public void testRefreshAll() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.refreshAll(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.refreshAll(); + verify(pm).refreshAll(); + verify(pm).close(); } + @Test public void testMakePersistent() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.makePersistent("0"); - pmControl.setReturnValue(null, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.makePersistent("0"); + verify(pm).makePersistent("0"); + verify(pm).close(); } + @Test public void testMakePersistentAll() { Collection coll = new HashSet(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.makePersistentAll(coll); - pmControl.setReturnValue(null, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.makePersistentAll(coll); + verify(pm).makePersistentAll(coll); + verify(pm).close(); } + @Test public void testDeletePersistent() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.deletePersistent("0"); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.deletePersistent("0"); + verify(pm).deletePersistent("0"); + verify(pm).close(); } + @Test public void testDeletePersistentAll() { Collection coll = new HashSet(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.deletePersistentAll(coll); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.deletePersistentAll(coll); + verify(pm).deletePersistentAll(coll); + verify(pm).close(); } + @Test public void testDetachCopy() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.detachCopy("0"); - pmControl.setReturnValue("0x", 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.detachCopy("0")).willReturn("0x"); JdoTemplate jt = new JdoTemplate(pmf); assertEquals("0x", jt.detachCopy("0")); + verify(pm).close(); } + @Test public void testDetachCopyAll() { Collection attached = new HashSet(); Collection detached = new HashSet(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.detachCopyAll(attached); - pmControl.setReturnValue(detached, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.detachCopyAll(attached)).willReturn(detached); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(detached, jt.detachCopyAll(attached)); + verify(pm).close(); } + @Test public void testFlush() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.flush(); + verify(pm).flush(); + verify(pm).close(); } + @Test public void testFlushWithDialect() { - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - + given(pmf.getPersistenceManager()).willReturn(pm); JdoTemplate jt = new JdoTemplate(pmf); jt.flush(); + verify(pm).flush(); + verify(pm).close(); } + @Test public void testFind() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class); - pmControl.setReturnValue(query); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class)).willReturn(query); Collection coll = new HashSet(); - query.execute(); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.execute()).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class)); - queryControl.verify(); + verify(pm).close(); } + @Test public void testFindWithFilter() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class, "a == b"); - pmControl.setReturnValue(query); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class, "a == b")).willReturn(query); Collection coll = new HashSet(); - query.execute(); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.execute()).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class, "a == b")); - queryControl.verify(); + verify(pm).close(); } + @Test public void testFindWithFilterAndOrdering() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class, "a == b"); - pmControl.setReturnValue(query); - query.setOrdering("c asc"); - queryControl.setVoidCallable(1); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class, "a == b")).willReturn(query); Collection coll = new HashSet(); - query.execute(); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.execute()).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class, "a == b", "c asc")); - queryControl.verify(); + verify(query).setOrdering("c asc"); + verify(pm).close(); } + @Test public void testFindWithParameterArray() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class, "a == b"); - pmControl.setReturnValue(query); - query.declareParameters("params"); - queryControl.setVoidCallable(1); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class, "a == b")).willReturn(query); Object[] values = new Object[0]; Collection coll = new HashSet(); - query.executeWithArray(values); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.executeWithArray(values)).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class, "a == b", "params", values)); - queryControl.verify(); + verify(query).declareParameters("params"); + verify(pm).close(); } + @Test public void testFindWithParameterArrayAndOrdering() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class, "a == b"); - pmControl.setReturnValue(query); - query.declareParameters("params"); - queryControl.setVoidCallable(1); - query.setOrdering("c asc"); - queryControl.setVoidCallable(1); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class, "a == b")).willReturn(query); Object[] values = new Object[0]; Collection coll = new HashSet(); - query.executeWithArray(values); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.executeWithArray(values)).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class, "a == b", "params", values, "c asc")); - queryControl.verify(); + verify(query).declareParameters("params"); + verify(query).setOrdering("c asc"); + verify(pm).close(); } + @Test public void testFindWithParameterMap() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class, "a == b"); - pmControl.setReturnValue(query); - query.declareParameters("params"); - queryControl.setVoidCallable(1); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class, "a == b")).willReturn(query); Map values = new HashMap(); Collection coll = new HashSet(); - query.executeWithMap(values); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.executeWithMap(values)).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class, "a == b", "params", values)); - queryControl.verify(); + verify(query).declareParameters("params"); + verify(pm).close(); } + @Test public void testFindWithParameterMapAndOrdering() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(String.class, "a == b"); - pmControl.setReturnValue(query); - query.declareParameters("params"); - queryControl.setVoidCallable(1); - query.setOrdering("c asc"); - queryControl.setVoidCallable(1); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(String.class, "a == b")).willReturn(query); Map values = new HashMap(); Collection coll = new HashSet(); - query.executeWithMap(values); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.executeWithMap(values)).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(String.class, "a == b", "params", values, "c asc")); - queryControl.verify(); + verify(query).declareParameters("params"); + verify(query).setOrdering("c asc"); + verify(pm).close(); } + @Test public void testFindWithLanguageAndQueryObject() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery(Query.SQL, "some SQL"); - pmControl.setReturnValue(query); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery(Query.SQL, "some SQL")).willReturn(query); Collection coll = new HashSet(); - query.execute(); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.execute()).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find(Query.SQL, "some SQL")); - queryControl.verify(); + verify(pm).close(); } + @Test public void testFindWithQueryString() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newQuery("single string query"); - pmControl.setReturnValue(query); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newQuery("single string query")).willReturn(query); Collection coll = new HashSet(); - query.execute(); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.execute()).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.find("single string query")); - queryControl.verify(); + verify(pm).close(); } + @Test public void testFindByNamedQuery() { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm); - pm.newNamedQuery(String.class, "some query name"); - pmControl.setReturnValue(query); + Query query = mock(Query.class); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.newNamedQuery(String.class, "some query name")).willReturn(query); Collection coll = new HashSet(); - query.execute(); - queryControl.setReturnValue(coll); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - queryControl.replay(); - + given(query.execute()).willReturn(coll); JdoTemplate jt = new JdoTemplate(pmf); assertEquals(coll, jt.findByNamedQuery(String.class, "some query name")); - queryControl.verify(); + verify(pm).close(); } + @Test public void testTemplateExceptions() { try { createTemplate().execute(new JdoCallback() { @@ -716,13 +510,11 @@ public class JdoTemplateTests extends TestCase { } } + @Test public void testTranslateException() { - MockControl dialectControl = MockControl.createControl(JdoDialect.class); - JdoDialect dialect = (JdoDialect) dialectControl.getMock(); + JdoDialect dialect = mock(JdoDialect.class); final JDOException ex = new JDOException(); - dialect.translateException(ex); - dialectControl.setReturnValue(new DataIntegrityViolationException("test", ex)); - dialectControl.replay(); + given(dialect.translateException(ex)).willReturn(new DataIntegrityViolationException("test", ex)); try { JdoTemplate template = createTemplate(); template.setJdoDialect(dialect); @@ -737,20 +529,10 @@ public class JdoTemplateTests extends TestCase { catch (DataIntegrityViolationException dive) { // expected } - dialectControl.verify(); } private JdoTemplate createTemplate() { - pmfControl.reset(); - pmControl.reset(); - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); return new JdoTemplate(pmf); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java index b4e6791628..538ce2572b 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java @@ -16,6 +16,17 @@ package org.springframework.orm.jdo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -23,6 +34,7 @@ import java.sql.SQLException; import java.sql.Savepoint; import java.util.ArrayList; import java.util.List; + import javax.jdo.JDOFatalDataStoreException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; @@ -33,16 +45,16 @@ import javax.transaction.Status; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; -import junit.framework.TestCase; -import org.easymock.MockControl; - -import org.springframework.tests.sample.beans.TestBean; -import org.springframework.tests.transaction.MockJtaTransaction; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.jdbc.datasource.ConnectionHandle; import org.springframework.jdbc.datasource.ConnectionHolder; import org.springframework.jdbc.datasource.SimpleConnectionHandle; import org.springframework.orm.jdo.support.SpringPersistenceManagerProxyBean; import org.springframework.orm.jdo.support.StandardPersistenceManagerProxyBean; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.tests.transaction.MockJtaTransaction; import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -55,10 +67,9 @@ import org.springframework.transaction.support.TransactionTemplate; /** * @author Juergen Hoeller + * @author Phillip Webb */ -public class JdoTransactionManagerTests extends TestCase { - - private MockControl pmfControl, pmControl, txControl; +public class JdoTransactionManagerTests { private PersistenceManagerFactory pmf; @@ -67,55 +78,26 @@ public class JdoTransactionManagerTests extends TestCase { private Transaction tx; - @Override - protected void setUp() { - pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - pmf = (PersistenceManagerFactory) pmfControl.getMock(); - pmControl = MockControl.createControl(PersistenceManager.class); - pm = (PersistenceManager) pmControl.getMock(); - txControl = MockControl.createControl(Transaction.class); - tx = (Transaction) txControl.getMock(); - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); + @Before + public void setUp() { + pmf = mock(PersistenceManagerFactory.class); + pm = mock(PersistenceManager.class); + tx = mock(Transaction.class); } - @Override - protected void tearDown() { - try { - pmfControl.verify(); - pmControl.verify(); - } - catch (IllegalStateException ex) { - // ignore: test method didn't call replay - } + @After + public void tearDown() { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); } + @Test public void testTransactionCommit() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 3); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pmf.getPersistenceManagerProxy(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.flush(); - pmControl.setVoidCallable(4); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pmf.getPersistenceManagerProxy()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -164,26 +146,18 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(pm, times(4)).flush(); + verify(pm).close(); + verify(tx).begin(); + verify(tx).commit(); } + @Test public void testTransactionRollback() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 2); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - tx.isActive(); - txControl.setReturnValue(true, 1); - tx.rollback(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -212,24 +186,16 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(pm).close(); + verify(tx).begin(); + verify(tx).rollback(); } + @Test public void testTransactionRollbackWithAlreadyRolledBack() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 2); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - tx.isActive(); - txControl.setReturnValue(false, 1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -258,28 +224,16 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(pm).close(); + verify(tx).begin(); } + @Test public void testTransactionRollbackOnly() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 2); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - tx.isActive(); - txControl.setReturnValue(true, 1); - tx.rollback(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -303,24 +257,18 @@ public class JdoTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); + + verify(pm).flush(); + verify(pm).close(); + verify(tx).begin(); + verify(tx).rollback(); } + @Test public void testParticipatingTransactionWithCommit() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); PlatformTransactionManager tm = new JdoTransactionManager(pmf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -330,14 +278,6 @@ public class JdoTransactionManagerTests extends TestCase { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.reset(); - tx.isActive(); - txControl.setReturnValue(true, 1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - txControl.replay(); return tt.execute(new TransactionCallback() { @Override @@ -355,24 +295,17 @@ public class JdoTransactionManagerTests extends TestCase { } }); assertTrue("Correct result list", result == l); + + verify(pm).flush(); + verify(pm).close(); + verify(tx).begin(); } + @Test public void testParticipatingTransactionWithRollback() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.close(); - pmControl.setVoidCallable(1); - tx.isActive(); - txControl.setReturnValue(false, 1); - tx.begin(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); PlatformTransactionManager tm = new JdoTransactionManager(pmf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -380,15 +313,6 @@ public class JdoTransactionManagerTests extends TestCase { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.reset(); - tx.isActive(); - txControl.setReturnValue(true, 3); - tx.setRollbackOnly(); - txControl.setVoidCallable(1); - tx.rollback(); - txControl.setVoidCallable(1); - txControl.replay(); - return tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -408,24 +332,19 @@ public class JdoTransactionManagerTests extends TestCase { catch (RuntimeException ex) { // expected } + verify(pm).close(); + verify(tx).begin(); + verify(tx).setRollbackOnly(); + verify(tx).rollback(); } + @Test public void testParticipatingTransactionWithRollbackOnly() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 5); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); + given(tx.getRollbackOnly()).willReturn(true); + willThrow(new JDOFatalDataStoreException()).given(tx).commit(); PlatformTransactionManager tm = new JdoTransactionManager(pmf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -436,19 +355,6 @@ public class JdoTransactionManagerTests extends TestCase { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.reset(); - tx.isActive(); - txControl.setReturnValue(true, 1); - tx.setRollbackOnly(); - txControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(true, 1); - tx.commit(); - txControl.setThrowable(new JDOFatalDataStoreException(), 1); - tx.isActive(); - txControl.setReturnValue(false, 1); - txControl.replay(); - return tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -471,24 +377,17 @@ public class JdoTransactionManagerTests extends TestCase { catch (JdoResourceFailureException ex) { // expected } + verify(pm).flush(); + verify(pm).close(); + verify(tx).begin(); + verify(tx).setRollbackOnly(); } + @Test public void testParticipatingTransactionWithWithRequiresNew() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 2); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 6); - tx.begin(); - txControl.setVoidCallable(1); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(2); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); PlatformTransactionManager tm = new JdoTransactionManager(pmf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -499,18 +398,6 @@ public class JdoTransactionManagerTests extends TestCase { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.verify(); - txControl.reset(); - tx.isActive(); - txControl.setReturnValue(true, 1); - tx.begin(); - txControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 2); - tx.commit(); - txControl.setVoidCallable(2); - txControl.replay(); - return tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { @@ -527,24 +414,17 @@ public class JdoTransactionManagerTests extends TestCase { } }); assertTrue("Correct result list", result == l); + verify(tx, times(2)).begin(); + verify(tx, times(2)).commit(); + verify(pm).flush(); + verify(pm, times(2)).close(); } + @Test public void testParticipatingTransactionWithWithRequiresNewAndPrebound() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 3); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 6); - tx.begin(); - txControl.setVoidCallable(1); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); PlatformTransactionManager tm = new JdoTransactionManager(pmf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -558,18 +438,6 @@ public class JdoTransactionManagerTests extends TestCase { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.verify(); - txControl.reset(); - tx.isActive(); - txControl.setReturnValue(true, 1); - tx.begin(); - txControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 2); - tx.commit(); - txControl.setVoidCallable(2); - txControl.replay(); - JdoTemplate jt = new JdoTemplate(pmf); jt.execute(new JdoCallback() { @Override @@ -598,29 +466,18 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf)); TransactionSynchronizationManager.unbindResource(pmf); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(tx, times(2)).begin(); + verify(tx, times(2)).commit(); + verify(pm).flush(); + verify(pm).close(); } + @Test public void testJtaTransactionCommit() throws Exception { - MockControl utControl = MockControl.createControl(UserTransaction.class); - UserTransaction ut = (UserTransaction) utControl.getMock(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 2); - ut.commit(); - utControl.setVoidCallable(1); - utControl.replay(); - - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.flush(); - pmControl.setVoidCallable(2); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + UserTransaction ut = mock(UserTransaction.class); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE); + given(pmf.getPersistenceManager()).willReturn(pm); JtaTransactionManager ptm = new JtaTransactionManager(ut); TransactionTemplate tt = new TransactionTemplate(ptm); @@ -660,31 +517,22 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); + + verify(ut).begin(); + verify(ut).commit(); + verify(pm, times(2)).flush(); + verify(pm, times(2)).close(); } + @Test public void testParticipatingJtaTransactionWithWithRequiresNewAndPrebound() throws Exception { - final MockControl utControl = MockControl.createControl(UserTransaction.class); - final UserTransaction ut = (UserTransaction) utControl.getMock(); - final MockControl tmControl = MockControl.createControl(TransactionManager.class); - final TransactionManager tm = (TransactionManager) tmControl.getMock(); + final UserTransaction ut = mock(UserTransaction.class); + final TransactionManager tm = mock(TransactionManager.class); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_NO_TRANSACTION, 1); - ut.begin(); - utControl.setVoidCallable(1); - utControl.replay(); - - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, + Status.STATUS_ACTIVE, Status.STATUS_ACTIVE); + given(pmf.getPersistenceManager()).willReturn(pm); JtaTransactionManager ptm = new JtaTransactionManager(ut, tm); final TransactionTemplate tt = new TransactionTemplate(ptm); @@ -699,23 +547,8 @@ public class JdoTransactionManagerTests extends TestCase { @Override public Object doInTransaction(TransactionStatus status) { try { - utControl.verify(); - utControl.reset(); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 1); MockJtaTransaction transaction = new MockJtaTransaction(); - tm.suspend(); - tmControl.setReturnValue(transaction, 1); - ut.begin(); - utControl.setVoidCallable(1); - ut.getStatus(); - utControl.setReturnValue(Status.STATUS_ACTIVE, 4); - ut.commit(); - utControl.setVoidCallable(2); - tm.resume(transaction); - tmControl.setVoidCallable(1); - utControl.replay(); - tmControl.replay(); + given(tm.suspend()).willReturn(transaction); } catch (Exception ex) { } @@ -748,19 +581,15 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf)); TransactionSynchronizationManager.unbindResource(pmf); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - utControl.verify(); + + verify(ut, times(2)).begin(); + verify(pm).flush(); + verify(pm, times(2)).close(); } - + @Test public void testTransactionCommitWithPropagationSupports() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -786,19 +615,14 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Correct result list", result == l); assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); + + verify(pm, times(2)).close(); } + @Test public void testInvalidIsolation() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(null, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -814,24 +638,12 @@ public class JdoTransactionManagerTests extends TestCase { catch (InvalidIsolationLevelException ex) { // expected } + verify(pm).close(); } + @Test public void testTransactionCommitWithPrebound() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - tx.isActive(); - txControl.setReturnValue(false, 1); - tx.begin(); - txControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -859,42 +671,22 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Has thread pm", TransactionSynchronizationManager.hasResource(pmf)); TransactionSynchronizationManager.unbindResource(pmf); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(tx).begin(); + verify(tx).commit(); } + @Test public void testTransactionCommitWithDataSource() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl dialectControl = MockControl.createControl(JdoDialect.class); - JdoDialect dialect = (JdoDialect) dialectControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - final Connection con = (Connection) conControl.getMock(); + final DataSource ds = mock(DataSource.class); + JdoDialect dialect = mock(JdoDialect.class); + final Connection con = mock(Connection.class); ConnectionHandle conHandle = new SimpleConnectionHandle(con); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.close(); - pmControl.setVoidCallable(1); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); TransactionTemplate tt = new TransactionTemplate(); - dialect.beginTransaction(tx, tt); - dialectControl.setReturnValue(null, 1); - dialect.getJdbcConnection(pm, false); - dialectControl.setReturnValue(conHandle, 1); - dialect.releaseJdbcConnection(conHandle, pm); - dialectControl.setVoidCallable(1); - dialect.cleanupTransaction(null); - dialectControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - dsControl.replay(); - dialectControl.replay(); - pmControl.replay(); - txControl.replay(); - conControl.replay(); + given(dialect.getJdbcConnection(pm, false)).willReturn(conHandle); JdoTransactionManager tm = new JdoTransactionManager(); tm.setPersistenceManagerFactory(pmf); @@ -923,50 +715,26 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds)); - dsControl.verify(); - dialectControl.verify(); - conControl.verify(); + + verify(pm).close(); + verify(dialect).beginTransaction(tx, tt); + verify(dialect).releaseJdbcConnection(conHandle, pm); + verify(dialect).cleanupTransaction(null); + verify(tx).commit(); } + @Test public void testTransactionCommitWithAutoDetectedDataSource() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl dialectControl = MockControl.createControl(JdoDialect.class); - JdoDialect dialect = (JdoDialect) dialectControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - final Connection con = (Connection) conControl.getMock(); + final DataSource ds = mock(DataSource.class); + JdoDialect dialect = mock(JdoDialect.class); + final Connection con = mock(Connection.class); ConnectionHandle conHandle = new SimpleConnectionHandle(con); - pmfControl.reset(); - pmf.getConnectionFactory(); - pmfControl.setReturnValue(ds, 2); - con.getMetaData(); - conControl.setReturnValue(null, 1); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.close(); - pmControl.setVoidCallable(1); + given(pmf.getConnectionFactory()).willReturn(ds); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); TransactionTemplate tt = new TransactionTemplate(); - dialect.beginTransaction(tx, tt); - dialectControl.setReturnValue(null, 1); - dialect.getJdbcConnection(pm, false); - dialectControl.setReturnValue(conHandle, 1); - dialect.releaseJdbcConnection(conHandle, pm); - dialectControl.setVoidCallable(1); - dialect.cleanupTransaction(null); - dialectControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - dsControl.replay(); - dialectControl.replay(); - pmControl.replay(); - txControl.replay(); - conControl.replay(); + given(dialect.getJdbcConnection(pm, false)).willReturn(conHandle); JdoTransactionManager tm = new JdoTransactionManager(); tm.setPersistenceManagerFactory(pmf); @@ -995,46 +763,24 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds)); - dsControl.verify(); - dialectControl.verify(); - conControl.verify(); + + verify(pm).close(); + verify(dialect).beginTransaction(tx, tt); + verify(dialect).releaseJdbcConnection(conHandle, pm); + verify(dialect).cleanupTransaction(null); + verify(tx).commit(); } + @Test public void testTransactionCommitWithAutoDetectedDataSourceAndNoConnection() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl dialectControl = MockControl.createControl(JdoDialect.class); - final JdoDialect dialect = (JdoDialect) dialectControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); + final DataSource ds = mock(DataSource.class); + final JdoDialect dialect = mock(JdoDialect.class); - pmfControl.reset(); - pmf.getConnectionFactory(); - pmfControl.setReturnValue(ds, 1); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); + given(pmf.getConnectionFactory()).willReturn(ds); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); TransactionTemplate tt = new TransactionTemplate(); - dialect.beginTransaction(tx, tt); - dialectControl.setReturnValue(null, 1); - dialect.getJdbcConnection(pm, false); - dialectControl.setReturnValue(null, 1); - dialect.cleanupTransaction(null); - dialectControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - dsControl.replay(); - dialectControl.replay(); - pmControl.replay(); - txControl.replay(); - conControl.replay(); + given(dialect.getJdbcConnection(pm, false)).willReturn(null); JdoTransactionManager tm = new JdoTransactionManager(); tm.setPersistenceManagerFactory(pmf); @@ -1066,15 +812,20 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds)); - dsControl.verify(); - dialectControl.verify(); - conControl.verify(); + + verify(pm).flush(); + verify(pm).close(); + verify(dialect).beginTransaction(tx, tt); + verify(dialect).cleanupTransaction(null); + verify(tx).commit(); } + @Test public void testExistingTransactionWithPropagationNestedAndRollback() throws SQLException { doTestExistingTransactionWithPropagationNestedAndRollback(false); } + @Test public void testExistingTransactionWithManualSavepointAndRollback() throws SQLException { doTestExistingTransactionWithPropagationNestedAndRollback(true); } @@ -1082,60 +833,22 @@ public class JdoTransactionManagerTests extends TestCase { private void doTestExistingTransactionWithPropagationNestedAndRollback(final boolean manualSavepoint) throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl dialectControl = MockControl.createControl(JdoDialect.class); - JdoDialect dialect = (JdoDialect) dialectControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - final Connection con = (Connection) conControl.getMock(); - MockControl mdControl = MockControl.createControl(DatabaseMetaData.class); - DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock(); - MockControl spControl = MockControl.createControl(Savepoint.class); - Savepoint sp = (Savepoint) spControl.getMock(); + final DataSource ds = mock(DataSource.class); + JdoDialect dialect = mock(JdoDialect.class); + final Connection con = mock(Connection.class); + DatabaseMetaData md = mock(DatabaseMetaData.class); + Savepoint sp = mock(Savepoint.class); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - md.supportsSavepoints(); - mdControl.setReturnValue(true, 1); - con.getMetaData(); - conControl.setReturnValue(md, 1); - con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1); - conControl.setReturnValue(sp, 1); - con.rollback(sp); - conControl.setVoidCallable(1); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); + given(md.supportsSavepoints()).willReturn(true); + given(con.getMetaData()).willReturn(md); + given(con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1)).willReturn(sp); final TransactionTemplate tt = new TransactionTemplate(); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); - dialect.beginTransaction(tx, tt); - dialectControl.setReturnValue(null, 1); ConnectionHandle conHandle = new SimpleConnectionHandle(con); - dialect.getJdbcConnection(pm, false); - dialectControl.setReturnValue(conHandle, 1); - dialect.releaseJdbcConnection(conHandle, pm); - dialectControl.setVoidCallable(1); - dialect.cleanupTransaction(null); - dialectControl.setVoidCallable(1); - if (!manualSavepoint) { - tx.isActive(); - txControl.setReturnValue(true, 1); - } - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - dsControl.replay(); - dialectControl.replay(); - pmControl.replay(); - txControl.replay(); - conControl.replay(); - mdControl.replay(); - spControl.replay(); + given(dialect.getJdbcConnection(pm, false)).willReturn(conHandle); + given(tx.isActive()).willReturn(!manualSavepoint); JdoTransactionManager tm = new JdoTransactionManager(); tm.setNestedTransactionAllowed(true); @@ -1180,56 +893,38 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("Hasn't thread con", !TransactionSynchronizationManager.hasResource(ds)); - dsControl.verify(); - dialectControl.verify(); - conControl.verify(); - mdControl.verify(); - spControl.verify(); + verify(pm).flush(); + verify(pm).close(); + verify(con).setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1); + verify(con).rollback(sp); + verify(dialect).beginTransaction(tx, tt); + verify(dialect).releaseJdbcConnection(conHandle, pm); + verify(dialect).cleanupTransaction(null); + verify(tx).commit(); } + @Test public void testTransactionTimeoutWithJdoDialect() throws SQLException { doTestTransactionTimeoutWithJdoDialect(true); } + @Test public void testTransactionTimeoutWithJdoDialectAndPmProxy() throws SQLException { doTestTransactionTimeoutWithJdoDialect(false); } private void doTestTransactionTimeoutWithJdoDialect(final boolean exposeNativePm) throws SQLException { - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); - MockControl dialectControl = MockControl.createControl(JdoDialect.class); - final JdoDialect dialect = (JdoDialect) dialectControl.getMock(); + Query query = mock(Query.class); + final JdoDialect dialect = mock(JdoDialect.class); TransactionTemplate tt = new TransactionTemplate(); - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 2); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - dialect.beginTransaction(tx, tt); - dialectControl.setReturnValue(null, 1); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); if (!exposeNativePm) { dialect.applyQueryTimeout(query, 10); } - dialect.cleanupTransaction(null); - dialectControl.setVoidCallable(1); - pm.newQuery(TestBean.class); - pmControl.setReturnValue(query, 1); - pm.close(); - pmControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); - queryControl.replay(); - dialectControl.replay(); + given(pm.newQuery(TestBean.class)).willReturn(query); JdoTransactionManager tm = new JdoTransactionManager(pmf); tm.setJdoDialect(dialect); @@ -1267,30 +962,17 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dialectControl.verify(); - queryControl.verify(); + verify(dialect).beginTransaction(tx, tt); + verify(dialect).cleanupTransaction(null); + verify(pm).close(); + verify(tx).getRollbackOnly(); + verify(tx).commit(); } + @Test public void testTransactionFlush() { - pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.currentTransaction(); - pmControl.setReturnValue(tx, 3); - pm.flush(); - pmControl.setVoidCallable(1); - pm.close(); - pmControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - tx.getRollbackOnly(); - txControl.setReturnValue(false, 1); - tx.commit(); - txControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); - txControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -1307,6 +989,10 @@ public class JdoTransactionManagerTests extends TestCase { assertTrue("Hasn't thread pm", !TransactionSynchronizationManager.hasResource(pmf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + verify(pm).flush(); + verify(pm).close(); + verify(tx).begin(); + verify(tx).commit(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java index 1bf0d91fbb..4b16a589ca 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/LocalPersistenceManagerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,11 @@ package org.springframework.orm.jdo; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; + import java.io.IOException; import java.util.Map; import java.util.Properties; @@ -23,19 +28,18 @@ import java.util.Properties; import javax.jdo.JDOFatalUserException; import javax.jdo.PersistenceManagerFactory; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.core.io.ClassPathResource; /** * @author Juergen Hoeller + * @author Phillip Webb */ -public class LocalPersistenceManagerFactoryTests extends TestCase { +public class LocalPersistenceManagerFactoryTests { + @Test public void testLocalPersistenceManagerFactoryBean() throws IOException { - MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); + final PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() { @Override protected PersistenceManagerFactory newPersistenceManagerFactory(Map props) { @@ -47,6 +51,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase { assertSame(pmf, pmfb.getObject()); } + @Test public void testLocalPersistenceManagerFactoryBeanWithInvalidSettings() throws IOException { LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean(); try { @@ -58,6 +63,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase { } } + @Test public void testLocalPersistenceManagerFactoryBeanWithIncompleteProperties() throws IOException { LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean(); Properties props = new Properties(); @@ -72,6 +78,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase { } } + @Test public void testLocalPersistenceManagerFactoryBeanWithInvalidProperty() throws IOException { LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() { @Override @@ -92,6 +99,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase { } } + @Test public void testLocalPersistenceManagerFactoryBeanWithFile() throws IOException { LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() { @Override @@ -110,6 +118,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase { } } + @Test public void testLocalPersistenceManagerFactoryBeanWithName() throws IOException { LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() { @Override @@ -128,6 +137,7 @@ public class LocalPersistenceManagerFactoryTests extends TestCase { } } + @Test public void testLocalPersistenceManagerFactoryBeanWithNameAndProperties() throws IOException { LocalPersistenceManagerFactoryBean pmfb = new LocalPersistenceManagerFactoryBean() { @Override diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java index 20bc73dbfe..529bdcabf1 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/support/JdoDaoSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,28 +16,28 @@ package org.springframework.orm.jdo.support; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + import java.util.ArrayList; import java.util.List; import javax.jdo.PersistenceManagerFactory; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.orm.jdo.JdoTemplate; /** * @author Juergen Hoeller + * @author Phillip Webb * @since 30.07.2003 */ -public class JdoDaoSupportTests extends TestCase { +public class JdoDaoSupportTests { + @Test public void testJdoDaoSupportWithPersistenceManagerFactory() throws Exception { - MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); + PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); pmf.getConnectionFactory(); - pmfControl.setReturnValue(null, 1); - pmfControl.replay(); final List test = new ArrayList(); JdoDaoSupport dao = new JdoDaoSupport() { @Override @@ -50,9 +50,9 @@ public class JdoDaoSupportTests extends TestCase { assertEquals("Correct PersistenceManagerFactory", pmf, dao.getPersistenceManagerFactory()); assertEquals("Correct JdoTemplate", pmf, dao.getJdoTemplate().getPersistenceManagerFactory()); assertEquals("initDao called", test.size(), 1); - pmfControl.verify(); } + @Test public void testJdoDaoSupportWithJdoTemplate() throws Exception { JdoTemplate template = new JdoTemplate(); final List test = new ArrayList(); diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java index 7a5784ac93..2736e3b6da 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/support/OpenPersistenceManagerInViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,15 @@ package org.springframework.orm.jdo.support; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.io.IOException; + import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.servlet.FilterChain; @@ -24,9 +32,7 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.mock.web.test.MockFilterConfig; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; @@ -40,15 +46,15 @@ import org.springframework.web.context.support.StaticWebApplicationContext; /** * @author Juergen Hoeller * @author Chris Beams + * @author Phillip Webb * @since 15.06.2004 */ -public class OpenPersistenceManagerInViewTests extends TestCase { +public class OpenPersistenceManagerInViewTests { + @Test public void testOpenPersistenceManagerInViewInterceptor() throws Exception { - MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); - MockControl pmControl = MockControl.createControl(PersistenceManager.class); - PersistenceManager pm = (PersistenceManager) pmControl.getMock(); + PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); + PersistenceManager pm = mock(PersistenceManager.class); OpenPersistenceManagerInViewInterceptor interceptor = new OpenPersistenceManagerInViewInterceptor(); interceptor.setPersistenceManagerFactory(pmf); @@ -56,10 +62,7 @@ public class OpenPersistenceManagerInViewTests extends TestCase { MockServletContext sc = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(sc); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pmfControl.replay(); - pmControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); interceptor.preHandle(new ServletWebRequest(request)); assertTrue(TransactionSynchronizationManager.hasResource(pmf)); @@ -77,54 +80,23 @@ public class OpenPersistenceManagerInViewTests extends TestCase { interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); - pmfControl.verify(); - pmControl.verify(); - - pmfControl.reset(); - pmControl.reset(); - pmfControl.replay(); - pmControl.replay(); interceptor.postHandle(new ServletWebRequest(request), null); assertTrue(TransactionSynchronizationManager.hasResource(pmf)); - pmfControl.verify(); - pmControl.verify(); - pmfControl.reset(); - pmControl.reset(); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); interceptor.afterCompletion(new ServletWebRequest(request), null); assertFalse(TransactionSynchronizationManager.hasResource(pmf)); - pmfControl.verify(); - pmControl.verify(); } + @Test public void testOpenPersistenceManagerInViewFilter() throws Exception { - MockControl pmfControl = MockControl.createControl(PersistenceManagerFactory.class); - final PersistenceManagerFactory pmf = (PersistenceManagerFactory) pmfControl.getMock(); - MockControl pmControl = MockControl.createControl(PersistenceManager.class); - PersistenceManager pm = (PersistenceManager) pmControl.getMock(); + final PersistenceManagerFactory pmf = mock(PersistenceManagerFactory.class); + PersistenceManager pm = mock(PersistenceManager.class); - pmf.getPersistenceManager(); - pmfControl.setReturnValue(pm, 1); - pm.close(); - pmControl.setVoidCallable(1); - pmfControl.replay(); - pmControl.replay(); + given(pmf.getPersistenceManager()).willReturn(pm); + final PersistenceManagerFactory pmf2 = mock(PersistenceManagerFactory.class); + PersistenceManager pm2 = mock(PersistenceManager.class); - MockControl pmf2Control = MockControl.createControl(PersistenceManagerFactory.class); - final PersistenceManagerFactory pmf2 = (PersistenceManagerFactory) pmf2Control.getMock(); - MockControl pm2Control = MockControl.createControl(PersistenceManager.class); - PersistenceManager pm2 = (PersistenceManager) pm2Control.getMock(); - - pmf2.getPersistenceManager(); - pmf2Control.setReturnValue(pm2, 1); - pm2.close(); - pm2Control.setVoidCallable(1); - pmf2Control.replay(); - pm2Control.replay(); + given(pmf2.getPersistenceManager()).willReturn(pm2); MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); @@ -171,10 +143,8 @@ public class OpenPersistenceManagerInViewTests extends TestCase { assertFalse(TransactionSynchronizationManager.hasResource(pmf2)); assertNotNull(request.getAttribute("invoked")); - pmfControl.verify(); - pmControl.verify(); - pmf2Control.verify(); - pm2Control.verify(); + verify(pm).close(); + verify(pm2).close(); wac.close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java index 80912a3479..cefae3bdf2 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/AbstractEntityManagerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,17 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; import javax.persistence.spi.PersistenceUnitInfo; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; import org.springframework.transaction.support.TransactionSynchronizationManager; /** @@ -31,18 +35,23 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * * @author Rod Johnson * @author Juergen Hoeller + * @author Phillip Webb */ -public abstract class AbstractEntityManagerFactoryBeanTests extends TestCase { - - protected static MockControl emfMc; +public abstract class AbstractEntityManagerFactoryBeanTests { protected static EntityManagerFactory mockEmf; + @Before + public void setUp() throws Exception { + mockEmf = mock(EntityManagerFactory.class); + } - @Override - protected void setUp() throws Exception { - emfMc = MockControl.createControl(EntityManagerFactory.class); - mockEmf = (EntityManagerFactory) emfMc.getMock(); + @After + public void tearDown() throws Exception { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); } protected void checkInvariants(AbstractEntityManagerFactoryBean demf) { @@ -56,14 +65,6 @@ public abstract class AbstractEntityManagerFactoryBeanTests extends TestCase { assertSame(emfi.getNativeEntityManagerFactory(), mockEmf); } - @Override - protected void tearDown() throws Exception { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - } - protected static class DummyEntityManagerFactoryBean extends AbstractEntityManagerFactoryBean { diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java index 0f7efcafe7..9102cd8645 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/DefaultJpaDialectTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,35 +16,29 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.OptimisticLockException; -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Test; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.support.DefaultTransactionDefinition; /** - * * @author Costin Leau - * + * @author Phillip Webb */ -public class DefaultJpaDialectTests extends TestCase { - JpaDialect dialect; +public class DefaultJpaDialectTests { - @Override - protected void setUp() throws Exception { - dialect = new DefaultJpaDialect(); - } - - @Override - protected void tearDown() throws Exception { - dialect = null; - } + private JpaDialect dialect = new DefaultJpaDialect(); + @Test public void testDefaultTransactionDefinition() throws Exception { DefaultTransactionDefinition definition = new DefaultTransactionDefinition(); definition.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); @@ -58,26 +52,18 @@ public class DefaultJpaDialectTests extends TestCase { } } + @Test public void testDefaultBeginTransaction() throws Exception { TransactionDefinition definition = new DefaultTransactionDefinition(); - MockControl entityControl = MockControl.createControl(EntityManager.class); - EntityManager entityManager = (EntityManager) entityControl.getMock(); + EntityManager entityManager = mock(EntityManager.class); + EntityTransaction entityTx = mock(EntityTransaction.class); - MockControl txControl = MockControl.createControl(EntityTransaction.class); - EntityTransaction entityTx = (EntityTransaction) txControl.getMock(); - - entityControl.expectAndReturn(entityManager.getTransaction(), entityTx); - entityTx.begin(); - - entityControl.replay(); - txControl.replay(); + given(entityManager.getTransaction()).willReturn(entityTx); dialect.beginTransaction(entityManager, definition); - - entityControl.verify(); - txControl.verify(); } + @Test public void testTranslateException() { OptimisticLockException ex = new OptimisticLockException(); assertEquals( diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java index 1d4578b372..0f21f02ea8 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryBeanSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,19 +16,17 @@ package org.springframework.orm.jpa; +import static org.mockito.Mockito.verify; + +import org.junit.Test; + /** * @author Rod Johnson + * @author Phillip Webb */ public class EntityManagerFactoryBeanSupportTests extends AbstractEntityManagerFactoryBeanTests { - @Override - protected void setUp() throws Exception { - super.setUp(); - mockEmf.close(); - emfMc.setVoidCallable(); - emfMc.replay(); - } - + @Test public void testHookIsCalled() throws Exception { DummyEntityManagerFactoryBean demf = new DummyEntityManagerFactoryBean(mockEmf); @@ -39,7 +37,7 @@ public class EntityManagerFactoryBeanSupportTests extends AbstractEntityManagerF // Should trigger close method expected by EntityManagerFactory mock demf.destroy(); - emfMc.verify(); + verify(mockEmf).close(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java index 137912e5b2..4377136663 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/EntityManagerFactoryUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,13 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.persistence.EntityExistsException; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -26,9 +33,7 @@ import javax.persistence.OptimisticLockException; import javax.persistence.PersistenceException; import javax.persistence.TransactionRequiredException; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.EmptyResultDataAccessException; @@ -40,13 +45,15 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * @author Costin Leau * @author Rod Johnson * @author Juergen Hoeller + * @author Phillip Webb */ -public class EntityManagerFactoryUtilsTests extends TestCase { +public class EntityManagerFactoryUtilsTests { /* * Test method for * 'org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetEntityManager(EntityManagerFactory)' */ + @Test public void testDoGetEntityManager() { // test null assertion try { @@ -56,34 +63,25 @@ public class EntityManagerFactoryUtilsTests extends TestCase { catch (IllegalArgumentException ex) { // it's okay } - MockControl mockControl = MockControl.createControl(EntityManagerFactory.class); - EntityManagerFactory factory = (EntityManagerFactory) mockControl.getMock(); + EntityManagerFactory factory = mock(EntityManagerFactory.class); - mockControl.replay(); // no tx active assertNull(EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null)); - mockControl.verify(); - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); } + @Test public void testDoGetEntityManagerWithTx() throws Exception { try { - MockControl mockControl = MockControl.createControl(EntityManagerFactory.class); - EntityManagerFactory factory = (EntityManagerFactory) mockControl.getMock(); - - MockControl managerControl = MockControl.createControl(EntityManager.class); - EntityManager manager = (EntityManager) managerControl.getMock(); + EntityManagerFactory factory = mock(EntityManagerFactory.class); + EntityManager manager = mock(EntityManager.class); TransactionSynchronizationManager.initSynchronization(); - mockControl.expectAndReturn(factory.createEntityManager(), manager); + given(factory.createEntityManager()).willReturn(manager); - mockControl.replay(); // no tx active assertSame(manager, EntityManagerFactoryUtils.doGetTransactionalEntityManager(factory, null)); assertSame(manager, ((EntityManagerHolder)TransactionSynchronizationManager.unbindResource(factory)).getEntityManager()); - - mockControl.verify(); } finally { TransactionSynchronizationManager.clearSynchronization(); @@ -92,6 +90,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); } + @Test public void testTranslatesIllegalStateException() { IllegalStateException ise = new IllegalStateException(); DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(ise); @@ -99,6 +98,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase { assertTrue(dex instanceof InvalidDataAccessApiUsageException); } + @Test public void testTranslatesIllegalArgumentException() { IllegalArgumentException iae = new IllegalArgumentException(); DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(iae); @@ -109,6 +109,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase { /** * We do not convert unknown exceptions. They may result from user code. */ + @Test public void testDoesNotTranslateUnfamiliarException() { UnsupportedOperationException userRuntimeException = new UnsupportedOperationException(); assertNull( @@ -120,6 +121,7 @@ public class EntityManagerFactoryUtilsTests extends TestCase { * Test method for * 'org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessException(PersistenceException)' */ + @Test @SuppressWarnings("serial") public void testConvertJpaPersistenceException() { EntityNotFoundException entityNotFound = new EntityNotFoundException(); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java index 5f2c0d0aa9..acc8f3b555 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,59 +16,57 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.lang.reflect.AccessibleObject; import java.lang.reflect.Method; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; -import junit.framework.TestCase; import org.aopalliance.intercept.Interceptor; import org.aopalliance.intercept.Invocation; import org.aopalliance.intercept.MethodInvocation; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * @author Costin Leau + * @author Phillip Webb */ -public class JpaInterceptorTests extends TestCase { - - private MockControl factoryControl, managerControl; +public class JpaInterceptorTests { private EntityManagerFactory factory; private EntityManager entityManager; - @Override - protected void setUp() throws Exception { - factoryControl = MockControl.createControl(EntityManagerFactory.class); - factory = (EntityManagerFactory) factoryControl.getMock(); - managerControl = MockControl.createControl(EntityManager.class); - entityManager = (EntityManager) managerControl.getMock(); + @Before + public void setUp() throws Exception { + factory = mock(EntityManagerFactory.class); + entityManager = mock(EntityManager.class); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - - factoryControl = null; - factory = null; - managerControl = null; - entityManager = null; - } + @Test public void testInterceptorWithNewEntityManager() throws PersistenceException { - factoryControl.expectAndReturn(factory.createEntityManager(), entityManager); - managerControl.expectAndReturn(entityManager.isOpen(), true); - entityManager.close(); - - factoryControl.replay(); - managerControl.replay(); + given(factory.createEntityManager()).willReturn(entityManager); + given(entityManager.isOpen()).willReturn(true); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setEntityManagerFactory(factory); @@ -79,17 +77,13 @@ public class JpaInterceptorTests extends TestCase { fail("Should not have thrown Throwable: " + t.getMessage()); } - factoryControl.verify(); - managerControl.verify(); + verify(entityManager).close(); } + @Test public void testInterceptorWithNewEntityManagerAndLazyFlush() throws PersistenceException { - factoryControl.expectAndReturn(factory.createEntityManager(), entityManager); - managerControl.expectAndReturn(entityManager.isOpen(), true); - entityManager.close(); - - factoryControl.replay(); - managerControl.replay(); + given(factory.createEntityManager()).willReturn(entityManager); + given(entityManager.isOpen()).willReturn(true); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setFlushEager(false); @@ -101,14 +95,11 @@ public class JpaInterceptorTests extends TestCase { fail("Should not have thrown Throwable: " + t.getMessage()); } - factoryControl.verify(); - managerControl.verify(); + verify(entityManager).close(); } + @Test public void testInterceptorWithThreadBound() { - factoryControl.replay(); - managerControl.replay(); - TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager)); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setEntityManagerFactory(factory); @@ -121,18 +112,10 @@ public class JpaInterceptorTests extends TestCase { finally { TransactionSynchronizationManager.unbindResource(factory); } - - factoryControl.verify(); - managerControl.verify(); } + @Test public void testInterceptorWithThreadBoundAndFlushEager() throws PersistenceException { - //entityManager.setFlushMode(FlushModeType.AUTO); - entityManager.flush(); - - factoryControl.replay(); - managerControl.replay(); - TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager)); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setFlushEager(true); @@ -147,17 +130,11 @@ public class JpaInterceptorTests extends TestCase { TransactionSynchronizationManager.unbindResource(factory); } - factoryControl.verify(); - managerControl.verify(); + verify(entityManager).flush(); } + @Test public void testInterceptorWithThreadBoundAndFlushCommit() { - //entityManager.setFlushMode(FlushModeType.COMMIT); - //entityManager.flush(); - - factoryControl.replay(); - managerControl.replay(); - TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(entityManager)); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setFlushEager(false); @@ -171,22 +148,15 @@ public class JpaInterceptorTests extends TestCase { finally { TransactionSynchronizationManager.unbindResource(factory); } - - factoryControl.verify(); - managerControl.verify(); } + @Test public void testInterceptorWithFlushFailure() throws Throwable { - factoryControl.expectAndReturn(factory.createEntityManager(), entityManager); - entityManager.flush(); + given(factory.createEntityManager()).willReturn(entityManager); PersistenceException exception = new PersistenceException(); - managerControl.setThrowable(exception, 1); - managerControl.expectAndReturn(entityManager.isOpen(), true); - entityManager.close(); - - factoryControl.replay(); - managerControl.replay(); + willThrow(exception).given(entityManager).flush(); + given(entityManager.isOpen()).willReturn(true); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setFlushEager(true); @@ -200,21 +170,16 @@ public class JpaInterceptorTests extends TestCase { assertEquals(exception, ex.getCause()); } - factoryControl.verify(); - managerControl.verify(); + verify(entityManager).close(); } + @Test public void testInterceptorWithFlushFailureWithoutConversion() throws Throwable { - factoryControl.expectAndReturn(factory.createEntityManager(), entityManager); - entityManager.flush(); + given(factory.createEntityManager()).willReturn(entityManager); PersistenceException exception = new PersistenceException(); - managerControl.setThrowable(exception, 1); - managerControl.expectAndReturn(entityManager.isOpen(), true); - entityManager.close(); - - factoryControl.replay(); - managerControl.replay(); + willThrow(exception).given(entityManager).flush(); + given(entityManager.isOpen()).willReturn(true); JpaInterceptor interceptor = new JpaInterceptor(); interceptor.setFlushEager(true); @@ -229,8 +194,7 @@ public class JpaInterceptorTests extends TestCase { assertEquals(exception, ex); } - factoryControl.verify(); - managerControl.verify(); + verify(entityManager).close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java index 4d25da3659..64828a4319 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,61 +16,58 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceException; import javax.persistence.Query; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Before; +import org.junit.Test; import org.springframework.dao.DataAccessException; import org.springframework.transaction.support.TransactionSynchronizationManager; /** * @author Costin Leau + * @author Phillip Webb */ -public class JpaTemplateTests extends TestCase { +public class JpaTemplateTests { private JpaTemplate template; - private MockControl factoryControl, managerControl; - private EntityManager manager; private EntityManagerFactory factory; - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { template = new JpaTemplate(); - factoryControl = MockControl.createControl(EntityManagerFactory.class); - factory = (EntityManagerFactory) factoryControl.getMock(); - managerControl = MockControl.createControl(EntityManager.class); - manager = (EntityManager) managerControl.getMock(); + factory = mock(EntityManagerFactory.class); + manager = mock(EntityManager.class); template.setEntityManager(manager); template.afterPropertiesSet(); } - @Override - protected void tearDown() throws Exception { - template = null; - factoryControl = null; - managerControl = null; - manager = null; - factory = null; - } - /* * Test method for * 'org.springframework.orm.jpa.JpaTemplate.JpaTemplate(EntityManagerFactory)' */ + @Test public void testJpaTemplateEntityManagerFactory() { } @@ -79,6 +76,7 @@ public class JpaTemplateTests extends TestCase { * Test method for * 'org.springframework.orm.jpa.JpaTemplate.JpaTemplate(EntityManager)' */ + @Test public void testJpaTemplateEntityManager() { } @@ -87,14 +85,12 @@ public class JpaTemplateTests extends TestCase { * Test method for * 'org.springframework.orm.jpa.JpaTemplate.execute(JpaCallback)' */ + @Test public void testExecuteJpaCallback() { template.setExposeNativeEntityManager(true); template.setEntityManager(manager); template.afterPropertiesSet(); - managerControl.replay(); - factoryControl.replay(); - template.execute(new JpaCallback() { @Override @@ -113,22 +109,18 @@ public class JpaTemplateTests extends TestCase { return null; } }); - managerControl.verify(); - factoryControl.verify(); } /* * Test method for * 'org.springframework.orm.jpa.JpaTemplate.executeFind(JpaCallback)' */ + @Test public void testExecuteFind() { template.setEntityManager(manager); template.setExposeNativeEntityManager(true); template.afterPropertiesSet(); - managerControl.replay(); - factoryControl.replay(); - try { template.executeFind(new JpaCallback() { @@ -143,28 +135,23 @@ public class JpaTemplateTests extends TestCase { catch (DataAccessException e) { // expected } - - managerControl.verify(); - factoryControl.verify(); } /* * Test method for * 'org.springframework.orm.jpa.JpaTemplate.execute(JpaCallback, boolean)' */ + @Test public void testExecuteJpaCallbackBoolean() { template = new JpaTemplate(); template.setExposeNativeEntityManager(false); template.setEntityManagerFactory(factory); template.afterPropertiesSet(); - factoryControl.expectAndReturn(factory.createEntityManager(), manager); - managerControl.expectAndReturn(manager.isOpen(), true); + given(factory.createEntityManager()).willReturn(manager); + given(manager.isOpen()).willReturn(true); manager.close(); - managerControl.replay(); - factoryControl.replay(); - template.execute(new JpaCallback() { @Override public Object doInJpa(EntityManager em) throws PersistenceException { @@ -172,19 +159,15 @@ public class JpaTemplateTests extends TestCase { return null; } }, true); - - managerControl.verify(); - factoryControl.verify(); } + @Test public void testExecuteJpaCallbackBooleanWithPrebound() { template.setExposeNativeEntityManager(false); template.setEntityManagerFactory(factory); template.afterPropertiesSet(); TransactionSynchronizationManager.bindResource(factory, new EntityManagerHolder(manager)); - managerControl.replay(); - factoryControl.replay(); try { template.execute(new JpaCallback() { @@ -195,9 +178,6 @@ public class JpaTemplateTests extends TestCase { return null; } }, true); - - managerControl.verify(); - factoryControl.verify(); } finally { TransactionSynchronizationManager.unbindResource(factory); @@ -208,9 +188,8 @@ public class JpaTemplateTests extends TestCase { * Test method for * 'org.springframework.orm.jpa.JpaTemplate.createSharedEntityManager(EntityManager)' */ + @Test public void testCreateEntityManagerProxy() { - manager.clear(); - managerControl.replay(); EntityManager proxy = template.createEntityManagerProxy(manager); assertNotSame(manager, proxy); @@ -220,24 +199,20 @@ public class JpaTemplateTests extends TestCase { proxy.close(); proxy.clear(); - managerControl.verify(); + verify(manager).clear(); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.find(Class, * Object) ' */ + @Test public void testFindClassOfTObject() { Integer result = new Integer(1); Object id = new Object(); - managerControl.expectAndReturn(manager.find(Number.class, id), result); - managerControl.replay(); - factoryControl.replay(); + given(manager.find(Number.class, id)).willReturn(result); assertSame(result, template.find(Number.class, id)); - - managerControl.verify(); - factoryControl.verify(); } /* @@ -245,172 +220,122 @@ public class JpaTemplateTests extends TestCase { * 'org.springframework.orm.jpa.JpaTemplate.getReference(Class, Object) * ' */ + @Test public void testGetReference() { Integer reference = new Integer(1); Object id = new Object(); - managerControl.expectAndReturn(manager.getReference(Number.class, id), reference); - managerControl.replay(); - factoryControl.replay(); + given(manager.getReference(Number.class, id)).willReturn(reference); assertSame(reference, template.getReference(Number.class, id)); - - managerControl.verify(); - factoryControl.verify(); } /* * Test method for * 'org.springframework.orm.jpa.JpaTemplate.contains(Object)' */ + @Test public void testContains() { boolean result = true; Object entity = new Object(); - managerControl.expectAndReturn(manager.contains(entity), result); - managerControl.replay(); - factoryControl.replay(); + given(manager.contains(entity)).willReturn(result); assertSame(result, template.contains(entity)); - - managerControl.verify(); - factoryControl.verify(); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.refresh(Object)' */ + @Test public void testRefresh() { Object entity = new Object(); - manager.refresh(entity); - managerControl.replay(); - factoryControl.replay(); - template.refresh(entity); - - managerControl.verify(); - factoryControl.verify(); + verify(manager).refresh(entity); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.persist(Object)' */ + @Test public void testPersist() { Object entity = new Object(); - manager.persist(entity); - managerControl.replay(); - factoryControl.replay(); - template.persist(entity); - - managerControl.verify(); - factoryControl.verify(); + verify(manager).persist(entity); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.merge(T) ' */ + @Test public void testMerge() { Object result = new Object(); Object entity = new Object(); - managerControl.expectAndReturn(manager.merge(entity), result); - managerControl.replay(); - factoryControl.replay(); - + given(manager.merge(entity)).willReturn(result); assertSame(result, template.merge(entity)); - - managerControl.verify(); - factoryControl.verify(); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.remove(Object)' */ + @Test public void testRemove() { Object entity = new Object(); - manager.remove(entity); - managerControl.replay(); - factoryControl.replay(); - template.remove(entity); - - managerControl.verify(); - factoryControl.verify(); + verify(manager).remove(entity); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.flush()' */ + @Test public void testFlush() { - manager.flush(); - managerControl.replay(); - factoryControl.replay(); - template.flush(); - - managerControl.verify(); - factoryControl.verify(); + verify(manager).flush(); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String)' */ + @Test public void testFindString() { String queryString = "some query"; - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Query query = mock(Query.class); List result = new ArrayList(); - managerControl.expectAndReturn(manager.createQuery(queryString), query); - queryControl.expectAndReturn(query.getResultList(), result); - - managerControl.replay(); - factoryControl.replay(); - queryControl.replay(); - + given(manager.createQuery(queryString)).willReturn(query); + given(query.getResultList()).willReturn(result); assertSame(result, template.find(queryString)); - - managerControl.verify(); - factoryControl.verify(); - queryControl.verify(); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String, * Object...)' */ + @Test public void testFindStringObjectArray() { String queryString = "some query"; - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Query query = mock(Query.class); List result = new ArrayList(); Object param1 = new Object(); Object param2 = new Object(); Object[] params = new Object[] { param1, param2 }; - managerControl.expectAndReturn(manager.createQuery(queryString), query); - queryControl.expectAndReturn(query.setParameter(1, param1), null); - queryControl.expectAndReturn(query.setParameter(2, param2), null); - - queryControl.expectAndReturn(query.getResultList(), result); - - managerControl.replay(); - factoryControl.replay(); - queryControl.replay(); + given(manager.createQuery(queryString)).willReturn(query); + given(query.getResultList()).willReturn(result); assertSame(result, template.find(queryString, params)); - managerControl.verify(); - factoryControl.verify(); - queryControl.verify(); + verify(query).setParameter(1, param1); + verify(query).setParameter(2, param2); } /* * Test method for 'org.springframework.orm.jpa.JpaTemplate.find(String, Map)' */ + @Test public void testFindStringMapOfStringObject() { String queryString = "some query"; - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Query query = mock(Query.class); List result = new ArrayList(); Object param1 = new Object(); Object param2 = new Object(); @@ -418,46 +343,29 @@ public class JpaTemplateTests extends TestCase { params.put("param1", param1); params.put("param2", param2); - managerControl.expectAndReturn(manager.createQuery(queryString), query); - queryControl.expectAndReturn(query.setParameter("param1", param1), null); - queryControl.expectAndReturn(query.setParameter("param2", param2), null); - - queryControl.expectAndReturn(query.getResultList(), result); - - managerControl.replay(); - factoryControl.replay(); - queryControl.replay(); + given(manager.createQuery(queryString)).willReturn(query); + given(query.getResultList()).willReturn(result); assertSame(result, template.findByNamedParams(queryString, params)); - managerControl.verify(); - factoryControl.verify(); - queryControl.verify(); + verify(query).setParameter("param1", param1); + verify(query).setParameter("param2", param2); } /* * Test method for * 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String)' */ + @Test public void testFindByNamedQueryString() { String queryName = "some query name"; - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Query query = mock(Query.class); List result = new ArrayList(); - managerControl.expectAndReturn(manager.createNamedQuery(queryName), query); - - queryControl.expectAndReturn(query.getResultList(), result); - - managerControl.replay(); - factoryControl.replay(); - queryControl.replay(); + given(manager.createNamedQuery(queryName)).willReturn(query); + given(query.getResultList()).willReturn(result); assertSame(result, template.findByNamedQuery(queryName)); - - managerControl.verify(); - factoryControl.verify(); - queryControl.verify(); } /* @@ -465,30 +373,22 @@ public class JpaTemplateTests extends TestCase { * 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String, * Object...)' */ + @Test public void testFindByNamedQueryStringObjectArray() { String queryName = "some query name"; - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Query query = mock(Query.class); List result = new ArrayList(); Object param1 = new Object(); Object param2 = new Object(); Object[] params = new Object[] { param1, param2 }; - managerControl.expectAndReturn(manager.createNamedQuery(queryName), query); - queryControl.expectAndReturn(query.setParameter(1, param1), null); - queryControl.expectAndReturn(query.setParameter(2, param2), null); - - queryControl.expectAndReturn(query.getResultList(), result); - - managerControl.replay(); - factoryControl.replay(); - queryControl.replay(); + given(manager.createNamedQuery(queryName)).willReturn(query); + given(query.getResultList()).willReturn(result); assertSame(result, template.findByNamedQuery(queryName, params)); - managerControl.verify(); - factoryControl.verify(); - queryControl.verify(); + verify(query).setParameter(1, param1); + verify(query).setParameter(2, param2); } /* @@ -496,10 +396,10 @@ public class JpaTemplateTests extends TestCase { * 'org.springframework.orm.jpa.JpaTemplate.findByNamedQuery(String, Map)' */ + @Test public void testFindByNamedQueryStringMapOfStringObject() { String queryName = "some query name"; - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Query query = mock(Query.class); List result = new ArrayList(); Object param1 = new Object(); Object param2 = new Object(); @@ -507,21 +407,11 @@ public class JpaTemplateTests extends TestCase { params.put("param1", param1); params.put("param2", param2); - managerControl.expectAndReturn(manager.createNamedQuery(queryName), query); - queryControl.expectAndReturn(query.setParameter("param1", param1), null); - queryControl.expectAndReturn(query.setParameter("param2", param2), null); - - queryControl.expectAndReturn(query.getResultList(), result); - - managerControl.replay(); - factoryControl.replay(); - queryControl.replay(); + given(manager.createNamedQuery(queryName)).willReturn(query); + given(query.getResultList()).willReturn(result); assertSame(result, template.findByNamedQueryAndNamedParams(queryName, params)); - - managerControl.verify(); - factoryControl.verify(); - queryControl.verify(); + verify(query).setParameter("param1", param1); + verify(query).setParameter("param2", param2); } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java index a1a7db067b..a343d21537 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,21 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import java.sql.SQLException; import java.util.ArrayList; import java.util.List; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; @@ -26,9 +38,9 @@ import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import javax.sql.DataSource; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -42,10 +54,9 @@ import org.springframework.transaction.support.TransactionTemplate; /** * @author Costin Leau * @author Juergen Hoeller + * @author Phillip Webb */ -public class JpaTransactionManagerTests extends TestCase { - - private MockControl factoryControl, managerControl, txControl; +public class JpaTransactionManagerTests { private EntityManager manager; @@ -60,46 +71,33 @@ public class JpaTransactionManagerTests extends TestCase { private TransactionTemplate tt; - @Override - protected void setUp() throws Exception { - factoryControl = MockControl.createControl(EntityManagerFactory.class); - factory = (EntityManagerFactory) factoryControl.getMock(); - managerControl = MockControl.createControl(EntityManager.class); - manager = (EntityManager) managerControl.getMock(); - txControl = MockControl.createControl(EntityTransaction.class); - tx = (EntityTransaction) txControl.getMock(); + @Before + public void setUp() throws Exception { + factory = mock(EntityManagerFactory.class); + manager = mock(EntityManager.class); + tx = mock(EntityTransaction.class); transactionManager = new JpaTransactionManager(factory); template = new JpaTemplate(factory); template.afterPropertiesSet(); tt = new TransactionTemplate(transactionManager); - factoryControl.expectAndReturn(factory.createEntityManager(), manager); - managerControl.expectAndReturn(manager.getTransaction(), tx); - tx.begin(); - managerControl.expectAndReturn(manager.isOpen(), true); - manager.close(); + given(factory.createEntityManager()).willReturn(manager); + given(manager.getTransaction()).willReturn(tx); + given(manager.isOpen()).willReturn(true); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); } - + @Test public void testTransactionCommit() { - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - managerControl.expectAndReturn(manager.getTransaction(), tx); - tx.commit(); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -125,22 +123,16 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).commit(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testTransactionCommitWithRollbackException() { - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.getRollbackOnly(), true); - managerControl.expectAndReturn(manager.getTransaction(), tx); - tx.commit(); - txControl.setThrowable(new RollbackException()); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); + given(tx.getRollbackOnly()).willReturn(true); + willThrow(new RollbackException()).given(tx).commit(); final List l = new ArrayList(); l.add("test"); @@ -172,19 +164,14 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testTransactionRollback() { - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.isActive(), true); - tx.rollback(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); final List l = new ArrayList(); l.add("test"); @@ -215,19 +202,13 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).rollback(); + verify(manager).close(); } + @Test public void testTransactionRollbackWithAlreadyRolledBack() { - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.isActive(), false); - // tx.rollback(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -257,20 +238,13 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).close(); } + @Test public void testTransactionRollbackOnly() { - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.isActive(), true); - manager.flush(); - tx.rollback(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); final List l = new ArrayList(); l.add("test"); @@ -299,18 +273,14 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(tx).rollback(); + verify(manager).close(); } + @Test public void testParticipatingTransactionWithCommit() { - managerControl.expectAndReturn(manager.getTransaction(), tx, 2); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -321,11 +291,6 @@ public class JpaTransactionManagerTests extends TestCase { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.reset(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - txControl.replay(); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); return tt.execute(new TransactionCallback() { @@ -347,16 +312,15 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(tx).commit(); + verify(manager).close(); } + @Test public void testParticipatingTransactionWithRollback() { - managerControl.expectAndReturn(manager.getTransaction(), tx, 2); - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); final List l = new ArrayList(); l.add("test"); @@ -368,12 +332,6 @@ public class JpaTransactionManagerTests extends TestCase { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.reset(); - txControl.expectAndReturn(tx.isActive(), true, 2); - tx.setRollbackOnly(); - tx.rollback(); - txControl.replay(); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); return tt.execute(new TransactionCallback() { @Override @@ -397,18 +355,17 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).setRollbackOnly(); + verify(tx).rollback(); + verify(manager).close(); } + @Test public void testParticipatingTransactionWithRollbackOnly() { - managerControl.expectAndReturn(manager.getTransaction(), tx, 3); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); + given(tx.getRollbackOnly()).willReturn(true); + willThrow(new RollbackException()).given(tx).commit(); final List l = new ArrayList(); l.add("test"); @@ -420,14 +377,6 @@ public class JpaTransactionManagerTests extends TestCase { tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.reset(); - txControl.expectAndReturn(tx.isActive(), true); - tx.setRollbackOnly(); - txControl.expectAndReturn(tx.getRollbackOnly(), true); - tx.commit(); - txControl.setThrowable(new RollbackException()); - txControl.replay(); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); return tt.execute(new TransactionCallback() { @@ -458,23 +407,18 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(tx).setRollbackOnly(); + verify(manager).close(); } + @Test public void testParticipatingTransactionWithRequiresNew() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - factoryControl.expectAndReturn(factory.createEntityManager(), manager); - managerControl.expectAndReturn(manager.getTransaction(), tx, 5); - manager.flush(); - managerControl.expectAndReturn(manager.isOpen(), true); - manager.close(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(factory.createEntityManager()).willReturn(manager); + given(manager.getTransaction()).willReturn(tx); + given(manager.isOpen()).willReturn(true); final List l = new ArrayList(); l.add("test"); @@ -485,17 +429,6 @@ public class JpaTransactionManagerTests extends TestCase { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.verify(); - txControl.reset(); - - tx.begin(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - - txControl.replay(); - assertTrue(TransactionSynchronizationManager.hasResource(factory)); return tt.execute(new TransactionCallback() { @Override @@ -516,20 +449,16 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(manager, times(2)).close(); + verify(tx, times(2)).begin(); } + @Test public void testParticipatingTransactionWithRequiresNewAndPrebound() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - managerControl.expectAndReturn(manager.getTransaction(), tx, 5); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -543,17 +472,6 @@ public class JpaTransactionManagerTests extends TestCase { Object result = tt.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - txControl.verify(); - txControl.reset(); - - tx.begin(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - - txControl.replay(); - JpaTemplate template2 = new JpaTemplate(factory); template2.execute(new JpaCallback() { @Override @@ -586,22 +504,17 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx, times(2)).begin(); + verify(tx, times(2)).commit(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testPropagationSupportsAndRequiresNew() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - manager.flush(); - managerControl.expectAndReturn(manager.getTransaction(), tx, 2); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -634,25 +547,18 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).commit(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testPropagationSupportsAndRequiresNewAndEarlyAccess() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); - factoryControl.expectAndReturn(factory.createEntityManager(), manager); - managerControl.expectAndReturn(manager.getTransaction(), tx, 2); - manager.flush(); - managerControl.expectAndReturn(manager.isOpen(), true); - manager.close(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(factory.createEntityManager()).willReturn(manager); + given(manager.getTransaction()).willReturn(tx); + given(manager.isOpen()).willReturn(true); final List l = new ArrayList(); l.add("test"); @@ -693,37 +599,22 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).commit(); + verify(manager).flush(); + verify(manager, times(2)).close(); } + @Test public void testTransactionWithRequiresNewInAfterCompletion() { tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - MockControl managerControl2 = MockControl.createControl(EntityManager.class); - EntityManager manager2 = (EntityManager) managerControl2.getMock(); - MockControl txControl2 = MockControl.createControl(EntityTransaction.class); - EntityTransaction tx2 = (EntityTransaction) txControl2.getMock(); + EntityManager manager2 = mock(EntityManager.class); + EntityTransaction tx2 = mock(EntityTransaction.class); - managerControl.expectAndReturn(manager.getTransaction(), tx, 2); - factoryControl.expectAndReturn(factory.createEntityManager(), manager2); - managerControl2.expectAndReturn(manager2.getTransaction(), tx2, 3); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - txControl2.expectAndReturn(tx2.getRollbackOnly(), false); - manager.flush(); - tx.commit(); - tx2.begin(); - tx2.commit(); - manager2.flush(); - managerControl2.expectAndReturn(manager2.isOpen(), true); - manager2.close(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); - managerControl2.replay(); - txControl2.replay(); + given(manager.getTransaction()).willReturn(tx); + given(factory.createEntityManager()).willReturn(manager, manager2); + given(manager2.getTransaction()).willReturn(tx2); + given(manager2.isOpen()).willReturn(true); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -762,24 +653,18 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); - managerControl2.verify(); - txControl2.verify(); + verify(tx).commit(); + verify(tx2).begin(); + verify(tx2).commit(); + verify(manager).flush(); + verify(manager).close(); + verify(manager2).flush(); + verify(manager2).close(); } + @Test public void testTransactionCommitWithPropagationSupports() { - managerControl.reset(); - txControl.reset(); - - manager.flush(); - managerControl.expectAndReturn(manager.isOpen(), true); - manager.close(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.isOpen()).willReturn(true); final List l = new ArrayList(); l.add("test"); @@ -809,22 +694,13 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testTransactionRollbackWithPropagationSupports() { - managerControl.reset(); - txControl.reset(); - - manager.flush(); - managerControl.expectAndReturn(manager.isOpen(), true); - manager.close(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.isOpen()).willReturn(true); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); @@ -852,24 +728,13 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testTransactionCommitWithPrebound() { - factoryControl.reset(); - managerControl.reset(); - txControl.reset(); - - managerControl.expectAndReturn(manager.getTransaction(), tx, 3); - tx.begin(); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -901,25 +766,15 @@ public class JpaTransactionManagerTests extends TestCase { TransactionSynchronizationManager.unbindResource(factory); } - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).begin(); + verify(tx).commit(); } + @Test public void testTransactionRollbackWithPrebound() { - factoryControl.reset(); - managerControl.reset(); - txControl.reset(); - managerControl.expectAndReturn(manager.getTransaction(), tx, 2); - tx.begin(); - txControl.expectAndReturn(tx.isActive(), true); - tx.rollback(); - manager.clear(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); + given(tx.isActive()).willReturn(true); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -949,22 +804,13 @@ public class JpaTransactionManagerTests extends TestCase { TransactionSynchronizationManager.unbindResource(factory); } - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).begin(); + verify(tx).rollback(); + verify(manager).clear(); } + @Test public void testTransactionCommitWithPreboundAndPropagationSupports() { - factoryControl.reset(); - managerControl.reset(); - txControl.reset(); - - manager.joinTransaction(); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); final List l = new ArrayList(); l.add("test"); @@ -1000,23 +846,12 @@ public class JpaTransactionManagerTests extends TestCase { TransactionSynchronizationManager.unbindResource(factory); } - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).joinTransaction(); + verify(manager).flush(); } + @Test public void testTransactionRollbackWithPreboundAndPropagationSupports() { - factoryControl.reset(); - managerControl.reset(); - txControl.reset(); - - manager.joinTransaction(); - manager.flush(); - manager.clear(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS); @@ -1050,26 +885,17 @@ public class JpaTransactionManagerTests extends TestCase { TransactionSynchronizationManager.unbindResource(factory); } - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).joinTransaction(); + verify(manager).flush(); + verify(manager).clear(); } + @Test public void testTransactionCommitWithDataSource() throws SQLException { - MockControl dsControl = MockControl.createControl(DataSource.class); - DataSource ds = (DataSource) dsControl.getMock(); + DataSource ds = mock(DataSource.class); transactionManager.setDataSource(ds); - managerControl.expectAndReturn(manager.getTransaction(), tx); - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - tx.commit(); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); - dsControl.replay(); + given(manager.getTransaction()).willReturn(tx); final List l = new ArrayList(); l.add("test"); @@ -1097,23 +923,16 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); - dsControl.verify(); + verify(tx).commit(); + verify(manager).flush(); + verify(manager).close(); } + @Test public void testInvalidIsolation() { tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - txControl.reset(); - managerControl.reset(); - managerControl.expectAndReturn(manager.isOpen(), true); - manager.close(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.isOpen()).willReturn(true); try { tt.execute(new TransactionCallbackWithoutResult() { @@ -1127,21 +946,12 @@ public class JpaTransactionManagerTests extends TestCase { // expected } - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(manager).close(); } + @Test public void testTransactionFlush() { - managerControl.expectAndReturn(manager.getTransaction(), tx); - txControl.expectAndReturn(tx.getRollbackOnly(), false); - managerControl.expectAndReturn(manager.getTransaction(), tx); - tx.commit(); - manager.flush(); - - factoryControl.replay(); - managerControl.replay(); - txControl.replay(); + given(manager.getTransaction()).willReturn(tx); assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); @@ -1157,9 +967,9 @@ public class JpaTransactionManagerTests extends TestCase { assertTrue(!TransactionSynchronizationManager.hasResource(factory)); assertTrue(!TransactionSynchronizationManager.isSynchronizationActive()); - factoryControl.verify(); - managerControl.verify(); - txControl.verify(); + verify(tx).commit(); + verify(manager).flush(); + verify(manager).close(); } } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java index 393d316db0..5f20a375d4 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,22 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import java.util.Map; import java.util.Properties; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; @@ -27,8 +41,7 @@ import javax.persistence.spi.PersistenceProvider; import javax.persistence.spi.PersistenceUnitInfo; import javax.persistence.spi.PersistenceUnitTransactionType; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.dao.DataAccessException; import org.springframework.dao.OptimisticLockingFailureException; @@ -41,6 +54,7 @@ import org.springframework.util.SerializationTestUtils; /** * @author Rod Johnson * @author Juergen Hoeller + * @author Phillip Webb */ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityManagerFactoryBeanTests { @@ -51,13 +65,15 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM private static PersistenceUnitInfo actualPui; + @Test public void testValidPersistenceUnit() throws Exception { parseValidPersistenceUnit(); } + @Test public void testExceptionTranslationWithNoDialect() throws Exception { LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); - EntityManagerFactory emf = cefb.getObject(); + cefb.getObject(); assertNull("No dialect set", cefb.getJpaDialect()); RuntimeException in1 = new RuntimeException("in1"); @@ -68,6 +84,7 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM assertSame(in2, dex.getCause()); } + @Test public void testEntityManagerFactoryIsProxied() throws Exception { LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); EntityManagerFactory emf = cefb.getObject(); @@ -84,21 +101,12 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM assertNotNull(SerializationTestUtils.serializeAndDeserialize(emf)); } + @Test public void testApplicationManagedEntityManagerWithoutTransaction() throws Exception { Object testEntity = new Object(); + EntityManager mockEm = mock(EntityManager.class); - MockControl emMc = MockControl.createControl(EntityManager.class); - EntityManager mockEm = (EntityManager) emMc.getMock(); - mockEm.contains(testEntity); - emMc.setReturnValue(false); - emMc.replay(); - - // finish recording mock calls - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm); - mockEmf.close(); - emfMc.setVoidCallable(); - emfMc.replay(); + given(mockEmf.createEntityManager()).willReturn(mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); EntityManagerFactory emf = cefb.getObject(); @@ -110,48 +118,24 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM cefb.destroy(); - emfMc.verify(); - emMc.verify(); + verify(mockEmf).close(); } + @Test public void testApplicationManagedEntityManagerWithTransaction() throws Exception { Object testEntity = new Object(); - MockControl tmMc = MockControl.createControl(EntityTransaction.class); - EntityTransaction mockTx = (EntityTransaction) tmMc.getMock(); - mockTx.isActive(); - tmMc.setReturnValue(false); - mockTx.begin(); - tmMc.setVoidCallable(); - mockTx.commit(); - tmMc.setVoidCallable(); - tmMc.replay(); + EntityTransaction mockTx = mock(EntityTransaction.class); // This one's for the tx (shared) - MockControl sharedEmMc = MockControl.createControl(EntityManager.class); - EntityManager sharedEm = (EntityManager) sharedEmMc.getMock(); - sharedEm.getTransaction(); - sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3); - sharedEm.close(); - sharedEmMc.setVoidCallable(); - sharedEmMc.replay(); - mockEmf.createEntityManager(); - emfMc.setReturnValue(sharedEm); + EntityManager sharedEm = mock(EntityManager.class); + given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one - MockControl emMc = MockControl.createControl(EntityManager.class); - EntityManager mockEm = (EntityManager) emMc.getMock(); - mockEm.getTransaction(); - emMc.setReturnValue(mockTx, 3); - mockEm.contains(testEntity); - emMc.setReturnValue(false); - emMc.replay(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEm.getTransaction()).willReturn(mockTx); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm); - mockEmf.close(); - emfMc.setVoidCallable(); - emfMc.replay(); + given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); @@ -172,49 +156,28 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM cefb.destroy(); - emfMc.verify(); - emMc.verify(); - tmMc.verify(); + verify(mockTx).begin(); + verify(mockTx).commit(); + verify(mockEm).contains(testEntity); + verify(mockEmf).close(); } + @Test public void testApplicationManagedEntityManagerWithTransactionAndCommitException() throws Exception { Object testEntity = new Object(); - MockControl tmMc = MockControl.createControl(EntityTransaction.class); - EntityTransaction mockTx = (EntityTransaction) tmMc.getMock(); - mockTx.isActive(); - tmMc.setReturnValue(false); - mockTx.begin(); - tmMc.setVoidCallable(); - mockTx.commit(); - tmMc.setThrowable(new OptimisticLockException()); - tmMc.replay(); + EntityTransaction mockTx = mock(EntityTransaction.class); + willThrow(new OptimisticLockException()).given(mockTx).commit(); // This one's for the tx (shared) - MockControl sharedEmMc = MockControl.createControl(EntityManager.class); - EntityManager sharedEm = (EntityManager) sharedEmMc.getMock(); - sharedEm.getTransaction(); - sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3); - sharedEm.close(); - sharedEmMc.setVoidCallable(); - sharedEmMc.replay(); - mockEmf.createEntityManager(); - emfMc.setReturnValue(sharedEm); + EntityManager sharedEm = mock(EntityManager.class); + given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one - MockControl emMc = MockControl.createControl(EntityManager.class); - EntityManager mockEm = (EntityManager) emMc.getMock(); - mockEm.getTransaction(); - emMc.setReturnValue(mockTx, 3); - mockEm.contains(testEntity); - emMc.setReturnValue(false); - emMc.replay(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEm.getTransaction()).willReturn(mockTx); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm); - mockEmf.close(); - emfMc.setVoidCallable(); - emfMc.replay(); + given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); @@ -241,39 +204,23 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM cefb.destroy(); - emfMc.verify(); - emMc.verify(); - tmMc.verify(); + verify(mockTx).begin(); + verify(mockEm).contains(testEntity); + verify(mockEmf).close(); } + @Test public void testApplicationManagedEntityManagerWithJtaTransaction() throws Exception { Object testEntity = new Object(); // This one's for the tx (shared) - MockControl sharedEmMc = MockControl.createControl(EntityManager.class); - EntityManager sharedEm = (EntityManager) sharedEmMc.getMock(); - sharedEm.getTransaction(); - sharedEmMc.setReturnValue(new NoOpEntityTransaction(), 3); - sharedEm.close(); - sharedEmMc.setVoidCallable(1); - sharedEmMc.replay(); - mockEmf.createEntityManager(); - emfMc.setReturnValue(sharedEm); + EntityManager sharedEm = mock(EntityManager.class); + given(sharedEm.getTransaction()).willReturn(new NoOpEntityTransaction()); // This is the application-specific one - MockControl emMc = MockControl.createControl(EntityManager.class); - EntityManager mockEm = (EntityManager) emMc.getMock(); - mockEm.joinTransaction(); - emMc.setVoidCallable(1); - mockEm.contains(testEntity); - emMc.setReturnValue(false); - emMc.replay(); + EntityManager mockEm = mock(EntityManager.class); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm); - mockEmf.close(); - emfMc.setVoidCallable(); - emfMc.replay(); + given(mockEmf.createEntityManager()).willReturn(sharedEm, mockEm); LocalContainerEntityManagerFactoryBean cefb = parseValidPersistenceUnit(); MutablePersistenceUnitInfo pui = ((MutablePersistenceUnitInfo) cefb.getPersistenceUnitInfo()); @@ -296,8 +243,9 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM cefb.destroy(); - emfMc.verify(); - emMc.verify(); + verify(mockEm).joinTransaction(); + verify(mockEm).contains(testEntity); + verify(mockEmf).close(); } public LocalContainerEntityManagerFactoryBean parseValidPersistenceUnit() throws Exception { @@ -307,6 +255,7 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM return emfb; } + @Test public void testInvalidPersistenceUnitName() throws Exception { try { createEntityManagerFactoryBean("org/springframework/orm/jpa/domain/persistence.xml", null, "call me Bob"); @@ -347,6 +296,7 @@ public class LocalContainerEntityManagerFactoryBeanTests extends AbstractEntityM //emfMc.verify(); } + @Test public void testRejectsMissingPersistenceUnitInfo() throws Exception { LocalContainerEntityManagerFactoryBean containerEmfb = new LocalContainerEntityManagerFactoryBean(); String entityManagerName = "call me Bob"; diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java index 048eb2d4ae..de6667f543 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/LocalEntityManagerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,10 @@ package org.springframework.orm.jpa; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.verify; + import java.util.Map; import java.util.Properties; @@ -23,8 +27,12 @@ import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceProvider; import javax.persistence.spi.PersistenceUnitInfo; +import org.junit.After; +import org.junit.Test; + /** * @author Rod Johnson + * @author Phillip Webb */ public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFactoryBeanTests { @@ -34,19 +42,17 @@ public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFac private static Map actualProps; - - @Override - protected void setUp() throws Exception { - super.setUp(); - mockEmf.close(); - emfMc.setVoidCallable(); - emfMc.replay(); + @After + public void verifyClosed() throws Exception { + verify(mockEmf).close(); } + @Test public void testValidUsageWithDefaultProperties() throws Exception { testValidUsage(null); } + @Test public void testValidUsageWithExplicitProperties() throws Exception { testValidUsage(new Properties()); } @@ -73,8 +79,6 @@ public class LocalEntityManagerFactoryBeanTests extends AbstractEntityManagerFac checkInvariants(lemfb); lemfb.destroy(); - - emfMc.verify(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java index b2b509f3df..4925258a66 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/JpaDaoSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,29 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.orm.jpa.support; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; + import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Test; import org.springframework.orm.jpa.JpaTemplate; /** * @author Costin Leau - * + * @author Phillip Webb */ -public class JpaDaoSupportTests extends TestCase { +public class JpaDaoSupportTests { + @Test public void testJpaDaoSupportWithEntityManager() throws Exception { - MockControl mockControl = MockControl.createControl(EntityManager.class); - EntityManager entityManager = (EntityManager) mockControl.getMock(); - mockControl.replay(); + EntityManager entityManager = mock(EntityManager.class); final List test = new ArrayList(); JpaDaoSupport dao = new JpaDaoSupport() { @Override @@ -48,13 +51,11 @@ public class JpaDaoSupportTests extends TestCase { assertNotNull("jpa template not created", dao.getJpaTemplate()); assertEquals("incorrect entity manager", entityManager, dao.getJpaTemplate().getEntityManager()); assertEquals("initDao not called", test.size(), 1); - mockControl.verify(); } + @Test public void testJpaDaoSupportWithEntityManagerFactory() throws Exception { - MockControl mockControl = MockControl.createControl(EntityManagerFactory.class); - EntityManagerFactory entityManagerFactory = (EntityManagerFactory) mockControl.getMock(); - mockControl.replay(); + EntityManagerFactory entityManagerFactory = mock(EntityManagerFactory.class); final List test = new ArrayList(); JpaDaoSupport dao = new JpaDaoSupport() { @Override @@ -68,9 +69,9 @@ public class JpaDaoSupportTests extends TestCase { assertEquals("incorrect entity manager factory", entityManagerFactory, dao.getJpaTemplate().getEntityManagerFactory()); assertEquals("initDao not called", test.size(), 1); - mockControl.verify(); } + @Test public void testJpaDaoSupportWithJpaTemplate() throws Exception { JpaTemplate template = new JpaTemplate(); final List test = new ArrayList(); @@ -87,6 +88,7 @@ public class JpaDaoSupportTests extends TestCase { assertEquals("initDao not called", test.size(), 1); } + @Test public void testInvalidJpaTemplate() throws Exception { JpaDaoSupport dao = new JpaDaoSupport() { }; diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java index 3431e4a421..8dd05c32b3 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/OpenEntityManagerInViewTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,16 @@ package org.springframework.orm.jpa.support; -import static org.easymock.EasyMock.anyObject; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.createStrictMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.reset; -import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.io.IOException; import java.util.concurrent.Callable; @@ -35,8 +38,9 @@ import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; -import junit.framework.TestCase; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.mock.web.test.MockFilterConfig; import org.springframework.mock.web.test.MockHttpServletRequest; @@ -56,8 +60,9 @@ import org.springframework.web.context.support.StaticWebApplicationContext; * @author Costin Leau * @author Juergen Hoeller * @author Chris Beams + * @author Phillip Webb */ -public class OpenEntityManagerInViewTests extends TestCase { +public class OpenEntityManagerInViewTests { private EntityManager manager; @@ -66,25 +71,26 @@ public class OpenEntityManagerInViewTests extends TestCase { private JpaTemplate template; - @Override - protected void setUp() throws Exception { - factory = createMock(EntityManagerFactory.class); - manager = createMock(EntityManager.class); + @Before + public void setUp() throws Exception { + factory = mock(EntityManagerFactory.class); + manager = mock(EntityManager.class); template = new JpaTemplate(factory); template.afterPropertiesSet(); - expect(factory.createEntityManager()).andReturn(manager); + given(factory.createEntityManager()).willReturn(manager); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); } + @Test public void testOpenEntityManagerInViewInterceptor() throws Exception { OpenEntityManagerInViewInterceptor interceptor = new OpenEntityManagerInViewInterceptor(); interceptor.setEntityManagerFactory(factory); @@ -92,8 +98,6 @@ public class OpenEntityManagerInViewTests extends TestCase { MockServletContext sc = new MockServletContext(); MockHttpServletRequest request = new MockHttpServletRequest(sc); - replay(manager, factory); - interceptor.preHandle(new ServletWebRequest(request)); assertTrue(TransactionSynchronizationManager.hasResource(factory)); @@ -111,29 +115,18 @@ public class OpenEntityManagerInViewTests extends TestCase { interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); - verify(manager, factory); - - reset(manager, factory); - replay(manager, factory); - interceptor.postHandle(new ServletWebRequest(request), null); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - verify(manager, factory); - - reset(manager, factory); - - expect(manager.isOpen()).andReturn(true); - manager.close(); - - replay(manager, factory); + given(manager.isOpen()).willReturn(true); interceptor.afterCompletion(new ServletWebRequest(request), null); assertFalse(TransactionSynchronizationManager.hasResource(factory)); - verify(manager, factory); + verify(manager).close(); } + @Test public void testOpenEntityManagerInViewInterceptorAsyncScenario() throws Exception { // Initial request thread @@ -145,19 +138,10 @@ public class OpenEntityManagerInViewTests extends TestCase { MockHttpServletRequest request = new MockHttpServletRequest(sc); ServletWebRequest webRequest = new ServletWebRequest(request); - replay(manager, factory); - interceptor.preHandle(webRequest); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - verify(manager, factory); - - AsyncWebRequest asyncWebRequest = createStrictMock(AsyncWebRequest.class); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.addTimeoutHandler((Runnable) anyObject()); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.startAsync(); - replay(asyncWebRequest); + AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(webRequest); asyncManager.setTaskExecutor(new SyncTaskExecutor()); @@ -169,23 +153,19 @@ public class OpenEntityManagerInViewTests extends TestCase { } }); - verify(asyncWebRequest); + verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); + verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); + verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); + verify(asyncWebRequest).startAsync(); interceptor.afterConcurrentHandlingStarted(webRequest); assertFalse(TransactionSynchronizationManager.hasResource(factory)); // Async dispatch thread - reset(manager, factory); - replay(manager, factory); - interceptor.preHandle(webRequest); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - verify(manager, factory); - reset(manager, factory); - replay(manager, factory); - asyncManager.clearConcurrentResult(); // check that further invocations simply participate @@ -202,41 +182,26 @@ public class OpenEntityManagerInViewTests extends TestCase { interceptor.postHandle(new ServletWebRequest(request), null); interceptor.afterCompletion(new ServletWebRequest(request), null); - verify(manager, factory); - reset(manager, factory); - replay(manager, factory); - interceptor.postHandle(webRequest, null); assertTrue(TransactionSynchronizationManager.hasResource(factory)); - verify(manager, factory); - reset(manager, factory); - - expect(manager.isOpen()).andReturn(true); - manager.close(); - - replay(manager, factory); + given(manager.isOpen()).willReturn(true); interceptor.afterCompletion(webRequest, null); assertFalse(TransactionSynchronizationManager.hasResource(factory)); - verify(manager, factory); + verify(manager).close(); } + @Test public void testOpenEntityManagerInViewFilter() throws Exception { - expect(manager.isOpen()).andReturn(true); - manager.close(); + given(manager.isOpen()).willReturn(true); - replay(manager, factory); + final EntityManagerFactory factory2 = mock(EntityManagerFactory.class); + final EntityManager manager2 = mock(EntityManager.class); - final EntityManagerFactory factory2 = createMock(EntityManagerFactory.class); - final EntityManager manager2 = createMock(EntityManager.class); - - expect(factory2.createEntityManager()).andReturn(manager2); - expect(manager2.isOpen()).andReturn(true); - manager2.close(); - - replay(factory2, manager2); + given(factory2.createEntityManager()).willReturn(manager2); + given(manager2.isOpen()).willReturn(true); MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); @@ -283,26 +248,21 @@ public class OpenEntityManagerInViewTests extends TestCase { assertFalse(TransactionSynchronizationManager.hasResource(factory2)); assertNotNull(request.getAttribute("invoked")); - verify(manager, factory); - verify(factory2, manager2); + verify(manager).close(); + verify(manager2).close(); wac.close(); } + @Test public void testOpenEntityManagerInViewFilterAsyncScenario() throws Exception { - expect(manager.isOpen()).andReturn(true); - manager.close(); + given(manager.isOpen()).willReturn(true); - replay(manager, factory); + final EntityManagerFactory factory2 = mock(EntityManagerFactory.class); + final EntityManager manager2 = mock(EntityManager.class); - final EntityManagerFactory factory2 = createMock(EntityManagerFactory.class); - final EntityManager manager2 = createMock(EntityManager.class); - - expect(factory2.createEntityManager()).andReturn(manager2); - expect(manager2.isOpen()).andReturn(true); - manager2.close(); - - replay(factory2, manager2); + given(factory2.createEntityManager()).willReturn(manager2); + given(manager2.isOpen()).willReturn(true); MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); @@ -348,13 +308,8 @@ public class OpenEntityManagerInViewTests extends TestCase { FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2); - AsyncWebRequest asyncWebRequest = createMock(AsyncWebRequest.class); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.addTimeoutHandler((Runnable) anyObject()); - asyncWebRequest.addCompletionHandler((Runnable) anyObject()); - asyncWebRequest.startAsync(); - expect(asyncWebRequest.isAsyncStarted()).andReturn(true).anyTimes(); - replay(asyncWebRequest); + AsyncWebRequest asyncWebRequest = mock(AsyncWebRequest.class); + given(asyncWebRequest.isAsyncStarted()).willReturn(true); WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); asyncManager.setTaskExecutor(new SyncTaskExecutor()); @@ -375,11 +330,15 @@ public class OpenEntityManagerInViewTests extends TestCase { assertEquals(1, count2.get()); assertNotNull(request.getAttribute("invoked")); + verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); + verify(asyncWebRequest).addTimeoutHandler(any(Runnable.class)); + verify(asyncWebRequest, times(2)).addCompletionHandler(any(Runnable.class)); + verify(asyncWebRequest).startAsync(); + // Async dispatch after concurrent handling produces result ... reset(asyncWebRequest); - expect(asyncWebRequest.isAsyncStarted()).andReturn(false).anyTimes(); - replay(asyncWebRequest); + given(asyncWebRequest.isAsyncStarted()).willReturn(false); assertFalse(TransactionSynchronizationManager.hasResource(factory)); assertFalse(TransactionSynchronizationManager.hasResource(factory2)); @@ -389,8 +348,8 @@ public class OpenEntityManagerInViewTests extends TestCase { assertEquals(2, count.get()); assertEquals(2, count2.get()); - verify(manager, factory); - verify(factory2, manager2); + verify(manager).close(); + verify(manager2).close(); wac.close(); } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java index 51a5209477..f7a26112fc 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/PersistenceInjectionTests.java @@ -16,6 +16,15 @@ package org.springframework.orm.jpa.support; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.withSettings; + import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -23,6 +32,7 @@ import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; import java.util.Properties; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceContext; @@ -30,10 +40,9 @@ import javax.persistence.PersistenceContextType; import javax.persistence.PersistenceProperty; import javax.persistence.PersistenceUnit; -import org.easymock.MockControl; import org.hibernate.ejb.HibernateEntityManager; import org.junit.Ignore; - +import org.junit.Test; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; @@ -53,10 +62,13 @@ import org.springframework.util.SerializationTestUtils; * * @author Rod Johnson * @author Juergen Hoeller + * @author Phillip Webb */ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanTests { + @Test public void testPrivatePersistenceContextField() throws Exception { + mockEmf = mock(EntityManagerFactory.class, withSettings().serializable()); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); gac.registerBeanDefinition("annotationProcessor", @@ -78,6 +90,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean2.em)); } + @Test public void testPrivateVendorSpecificPersistenceContextField() { GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -92,11 +105,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertNotNull(bean.em); } + @Test public void testPublicExtendedPersistenceContextSetter() throws Exception { - EntityManager mockEm = MockControl.createControl(EntityManager.class).getMock(); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm, 1); - emfMc.replay(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEmf.createEntityManager()).willReturn(mockEm); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -109,24 +121,13 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceContextSetter bean = (DefaultPublicPersistenceContextSetter) gac.getBean( DefaultPublicPersistenceContextSetter.class.getName()); assertNotNull(bean.em); - emfMc.verify(); } + @Test public void testPublicSpecificExtendedPersistenceContextSetter() throws Exception { - emfMc.replay(); - - MockControl emfMc2 = MockControl.createControl(EntityManagerFactory.class); - EntityManagerFactory mockEmf2 = emfMc2.getMock(); - MockControl emMc2 = MockControl.createControl(EntityManager.class); - EntityManager mockEm2 = emMc2.getMock(); - mockEm2.getTransaction(); - emMc2.setReturnValue(null, 1); - mockEm2.flush(); - emMc2.setVoidCallable(1); - emMc2.replay(); - mockEmf2.createEntityManager(); - emfMc2.setReturnValue(mockEm2, 1); - emfMc2.replay(); + EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class); + EntityManager mockEm2 = mock(EntityManager.class); + given(mockEmf2.createEntityManager()).willReturn(mockEm2); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -141,16 +142,15 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT SpecificPublicPersistenceContextSetter.class.getName()); assertNotNull(bean.getEntityManager()); bean.getEntityManager().flush(); - emfMc.verify(); - emfMc2.verify(); + verify(mockEm2).getTransaction(); + verify(mockEm2).flush(); } + @Test public void testPublicExtendedPersistenceContextSetterWithSerialization() throws Exception { DummyInvocationHandler ih = new DummyInvocationHandler(); Object mockEm = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {EntityManager.class}, ih); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm, 1); - emfMc.replay(); + given(mockEmf.createEntityManager()).willReturn((EntityManager) mockEm); GenericApplicationContext gac = new GenericApplicationContext(); SimpleMapScope myScope = new SimpleMapScope(); @@ -172,27 +172,19 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT serialized.close(); assertTrue(DummyInvocationHandler.closed); DummyInvocationHandler.closed = false; - emfMc.verify(); } + @Test + @SuppressWarnings("unchecked") public void testPublicExtendedPersistenceContextSetterWithEntityManagerInfoAndSerialization() throws Exception { - Object mockEm = Proxy.newProxyInstance( - getClass().getClassLoader(), new Class[] {EntityManager.class}, new DummyInvocationHandler()); - MockControl emfMc = MockControl.createControl(EntityManagerFactoryWithInfo.class); - EntityManagerFactoryWithInfo mockEmf = (EntityManagerFactoryWithInfo) emfMc.getMock(); - mockEmf.getNativeEntityManagerFactory(); - emfMc.setReturnValue(mockEmf); - mockEmf.getPersistenceUnitInfo(); - emfMc.setReturnValue(null); - mockEmf.getJpaDialect(); - emfMc.setReturnValue(new DefaultJpaDialect()); - mockEmf.getEntityManagerInterface(); - emfMc.setReturnValue(EntityManager.class); - mockEmf.getBeanClassLoader(); - emfMc.setReturnValue(getClass().getClassLoader()); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm); - emfMc.replay(); + EntityManager mockEm = mock(EntityManager.class, withSettings().serializable()); + given(mockEm.isOpen()).willReturn(true); + EntityManagerFactoryWithInfo mockEmf = mock(EntityManagerFactoryWithInfo.class); + given(mockEmf.getNativeEntityManagerFactory()).willReturn(mockEmf); + given(mockEmf.getJpaDialect()).willReturn(new DefaultJpaDialect()); + given(mockEmf.getEntityManagerInterface()).willReturn((Class)EntityManager.class); + given(mockEmf.getBeanClassLoader()).willReturn(getClass().getClassLoader()); + given(mockEmf.createEntityManager()).willReturn(mockEm); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -206,11 +198,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT DefaultPublicPersistenceContextSetter.class.getName()); assertNotNull(bean.em); assertNotNull(SerializationTestUtils.serializeAndDeserialize(bean.em)); - emfMc.verify(); } + @Test public void testPublicExtendedPersistenceContextSetterWithOverriding() { - EntityManager mockEm2 = MockControl.createControl(EntityManager.class).getMock(); + EntityManager mockEm2 = mock(EntityManager.class); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -226,6 +218,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEm2, bean.em); } + @Test public void testPrivatePersistenceUnitField() { GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -240,6 +233,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf, bean.emf); } + @Test public void testPublicPersistenceUnitSetter() { GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -254,9 +248,9 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf, bean.emf); } + @Test public void testPublicPersistenceUnitSetterWithOverriding() { - EntityManagerFactory mockEmf2 = - MockControl.createControl(EntityManagerFactory.class).getMock(); + EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -272,9 +266,9 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf2, bean.emf); } + @Test public void testPublicPersistenceUnitSetterWithUnitIdentifiedThroughBeanName() { - EntityManagerFactory mockEmf2 = - MockControl.createControl(EntityManagerFactory.class).getMock(); + EntityManagerFactory mockEmf2 = mock(EntityManagerFactory.class); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -297,12 +291,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf2, bean2.emf); } + @Test public void testPublicPersistenceUnitSetterWithMultipleUnitsIdentifiedThroughUnitName() { - MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class); - EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock(); - mockEmf2.getPersistenceUnitName(); - emf2Mc.setReturnValue("Person", 2); - emf2Mc.replay(); + EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class); + given(mockEmf2.getPersistenceUnitName()).willReturn("Person"); GenericApplicationContext gac = new GenericApplicationContext(); gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf); @@ -322,19 +314,14 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT gac.getBean(DefaultPublicPersistenceUnitSetterNamedPerson.class.getName()); assertSame(mockEmf, bean.emf); assertSame(mockEmf2, bean2.emf); - - emf2Mc.verify(); } @Ignore public void ignoreTestPersistenceUnitsFromJndi() { - mockEmf.createEntityManager(); - Object mockEm = MockControl.createControl(EntityManager.class).getMock(); - emfMc.setReturnValue(mockEm, 1); - emfMc.replay(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEmf.createEntityManager()).willReturn(mockEm); - MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class); - EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock(); + EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class); Map persistenceUnits = new HashMap(); persistenceUnits.put("", "pu1"); @@ -369,13 +356,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf2, bean2.emf); assertNotNull(bean3.em); assertNotNull(bean4.em); - - emfMc.verify(); } + @Test public void testPersistenceUnitsFromJndiWithDefaultUnit() { - MockControl emf2Mc = MockControl.createControl(EntityManagerFactoryWithInfo.class); - EntityManagerFactoryWithInfo mockEmf2 = (EntityManagerFactoryWithInfo) emf2Mc.getMock(); + EntityManagerFactoryWithInfo mockEmf2 = mock(EntityManagerFactoryWithInfo.class); Map persistenceUnits = new HashMap(); persistenceUnits.put("System", "pu1"); @@ -403,6 +388,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf2, bean2.emf); } + @Test public void testSinglePersistenceUnitFromJndi() { Map persistenceUnits = new HashMap(); persistenceUnits.put("Person", "pu1"); @@ -427,10 +413,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEmf, bean2.emf); } + @Test public void testPersistenceContextsFromJndi() { - Object mockEm = MockControl.createControl(EntityManager.class).getMock(); - Object mockEm2 = MockControl.createControl(EntityManager.class).getMock(); - Object mockEm3 = MockControl.createControl(EntityManager.class).getMock(); + EntityManager mockEm = mock(EntityManager.class); + EntityManager mockEm2 = mock(EntityManager.class); + EntityManager mockEm3 = mock(EntityManager.class); Map persistenceContexts = new HashMap(); persistenceContexts.put("", "pc1"); @@ -466,10 +453,11 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEm3, bean3.em); } + @Test public void testPersistenceContextsFromJndiWithDefaultUnit() { - Object mockEm = MockControl.createControl(EntityManager.class).getMock(); - Object mockEm2 = MockControl.createControl(EntityManager.class).getMock(); - Object mockEm3 = MockControl.createControl(EntityManager.class).getMock(); + EntityManager mockEm = mock(EntityManager.class); + EntityManager mockEm2 = mock(EntityManager.class); + EntityManager mockEm3 = mock(EntityManager.class); Map persistenceContexts = new HashMap(); persistenceContexts.put("System", "pc1"); @@ -506,9 +494,10 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEm3, bean3.em); } + @Test public void testSinglePersistenceContextFromJndi() { - Object mockEm = MockControl.createControl(EntityManager.class).getMock(); - Object mockEm2 = MockControl.createControl(EntityManager.class).getMock(); + EntityManager mockEm = mock(EntityManager.class); + EntityManager mockEm2 = mock(EntityManager.class); Map persistenceContexts = new HashMap(); persistenceContexts.put("System", "pc1"); @@ -537,6 +526,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertSame(mockEm2, bean2.em); } + @Test public void testFieldOfWrongTypeAnnotatedWithPersistenceUnit() { PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor(); try { @@ -548,6 +538,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT } } + @Test public void testSetterOfWrongTypeAnnotatedWithPersistenceUnit() { PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor(); try { @@ -559,6 +550,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT } } + @Test public void testSetterWithNoArgs() { PersistenceAnnotationBeanPostProcessor babpp = new PersistenceAnnotationBeanPostProcessor(); try { @@ -572,45 +564,37 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT @Ignore public void ignoreTestNoPropertiesPassedIn() { - mockEmf.createEntityManager(); - emfMc.setReturnValue(MockControl.createControl(EntityManager.class).getMock(), 1); - emfMc.replay(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEmf.createEntityManager()).willReturn(mockEm); PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor(); DefaultPrivatePersistenceContextFieldExtended dppcf = new DefaultPrivatePersistenceContextFieldExtended(); babpp.postProcessAfterInstantiation(dppcf, "bean name does not matter"); assertNotNull(dppcf.em); - emfMc.verify(); } @Ignore public void ignoreTestPropertiesPassedIn() { Properties props = new Properties(); props.put("foo", "bar"); - mockEmf.createEntityManager(props); - emfMc.setReturnValue(MockControl.createControl(EntityManager.class).getMock(), 1); - emfMc.replay(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEmf.createEntityManager(props)).willReturn(mockEm); PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor(); DefaultPrivatePersistenceContextFieldExtendedWithProps dppcf = new DefaultPrivatePersistenceContextFieldExtendedWithProps(); babpp.postProcessAfterInstantiation(dppcf, "bean name does not matter"); assertNotNull(dppcf.em); - emfMc.verify(); } + @Test public void testPropertiesForTransactionalEntityManager() { Properties props = new Properties(); props.put("foo", "bar"); - MockControl emC = MockControl.createControl(EntityManager.class); - EntityManager em = (EntityManager) emC.getMock(); - emfMc.expectAndReturn(mockEmf.createEntityManager(props), em); - emC.expectAndReturn(em.getDelegate(), new Object()); - emC.expectAndReturn(em.isOpen(), true); - em.close(); - - emfMc.replay(); - emC.replay(); + EntityManager em = mock(EntityManager.class); + given(mockEmf.createEntityManager(props)).willReturn(em); + given(em.getDelegate()).willReturn(new Object()); + given(em.isOpen()).willReturn(true); PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor(); DefaultPrivatePersistenceContextFieldWithProperties transactionalField = @@ -620,27 +604,22 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT assertNotNull(transactionalField.em); assertNotNull(transactionalField.em.getDelegate()); - emfMc.verify(); - emC.verify(); + verify(em).close(); } /** * Binds an EMF to the thread and tests if EM with different properties * generate new EMs or not. */ + @Test public void testPropertiesForSharedEntityManager1() { Properties props = new Properties(); props.put("foo", "bar"); - MockControl emC = MockControl.createControl(EntityManager.class); - EntityManager em = (EntityManager) emC.getMock(); + EntityManager em = mock(EntityManager.class); // only one call made - the first EM definition wins (in this case the one w/ the properties) - emfMc.expectAndReturn(mockEmf.createEntityManager(props), em); - emC.expectAndReturn(em.getDelegate(), new Object(), 2); - emC.expectAndReturn(em.isOpen(), true); - em.close(); - - emfMc.replay(); - emC.replay(); + given(mockEmf.createEntityManager(props)).willReturn(em); + given(em.getDelegate()).willReturn(new Object()); + given(em.isOpen()).willReturn(true); PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor(); DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties = @@ -658,27 +637,22 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT try { TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em)); assertNotNull(transactionalField.em.getDelegate()); - emfMc.verify(); - emC.verify(); + verify(em).close(); } finally { TransactionSynchronizationManager.unbindResource(mockEmf); } } + @Test public void testPropertiesForSharedEntityManager2() { Properties props = new Properties(); props.put("foo", "bar"); - MockControl emC = MockControl.createControl(EntityManager.class); - EntityManager em = (EntityManager) emC.getMock(); + EntityManager em = mock(EntityManager.class); // only one call made - the first EM definition wins (in this case the one w/o the properties) - emfMc.expectAndReturn(mockEmf.createEntityManager(), em); - emC.expectAndReturn(em.getDelegate(), new Object(), 2); - emC.expectAndReturn(em.isOpen(), true); - em.close(); - - emfMc.replay(); - emC.replay(); + given(mockEmf.createEntityManager()).willReturn(em); + given(em.getDelegate()).willReturn(new Object(), 2); + given(em.isOpen()).willReturn(true); PersistenceAnnotationBeanPostProcessor babpp = new MockPersistenceAnnotationBeanPostProcessor(); DefaultPrivatePersistenceContextFieldWithProperties transactionalFieldWithProperties = @@ -696,8 +670,7 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT try { TransactionSynchronizationManager.bindResource(mockEmf, new EntityManagerHolder(em)); assertNotNull(transactionalFieldWithProperties.em.getDelegate()); - emfMc.verify(); - emC.verify(); + verify(em).close(); } finally { TransactionSynchronizationManager.unbindResource(mockEmf); @@ -899,5 +872,4 @@ public class PersistenceInjectionTests extends AbstractEntityManagerFactoryBeanT throw new IllegalStateException(); } } - } diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java index 3296f1f258..4a783c7d5d 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/support/SharedEntityManagerFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,18 @@ package org.springframework.orm.jpa.support; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; -import org.easymock.MockControl; -import static org.junit.Assert.*; import org.junit.Test; - import org.springframework.orm.jpa.EntityManagerHolder; import org.springframework.orm.jpa.EntityManagerProxy; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -30,6 +35,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager /** * @author Rod Johnson * @author Juergen Hoeller + * @author Phillip Webb */ public class SharedEntityManagerFactoryTests { @@ -37,22 +43,11 @@ public class SharedEntityManagerFactoryTests { public void testValidUsage() { Object o = new Object(); - MockControl emMc = MockControl.createControl(EntityManager.class); - EntityManager mockEm = (EntityManager) emMc.getMock(); + EntityManager mockEm = mock(EntityManager.class); + given(mockEm.isOpen()).willReturn(true); - mockEm.contains(o); - emMc.setReturnValue(false, 1); - - emMc.expectAndReturn(mockEm.isOpen(), true); - mockEm.close(); - emMc.setVoidCallable(1); - emMc.replay(); - - MockControl emfMc = MockControl.createControl(EntityManagerFactory.class); - EntityManagerFactory mockEmf = (EntityManagerFactory) emfMc.getMock(); - mockEmf.createEntityManager(); - emfMc.setReturnValue(mockEm, 1); - emfMc.replay(); + EntityManagerFactory mockEmf = mock(EntityManagerFactory.class); + given(mockEmf.createEntityManager()).willReturn(mockEm); SharedEntityManagerBean proxyFactoryBean = new SharedEntityManagerBean(); proxyFactoryBean.setEntityManagerFactory(mockEmf); @@ -83,10 +78,9 @@ public class SharedEntityManagerFactoryTests { TransactionSynchronizationManager.unbindResource(mockEmf); } - emfMc.verify(); - emMc.verify(); - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + verify(mockEm).contains(o); + verify(mockEm).close(); } } From 4ae9cf7cf11af1626cb5dd127c020c98507f8e7f Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 10 Jan 2013 16:42:44 +0100 Subject: [PATCH 031/311] Ensure JUnit & TestNG tests run in spring-test Prior to this commit, the Gradle build configuration only executed TestNG-based tests and effectively disabled all JUnit-based tests in the spring-test module. Furthermore, TestNG-based tests were not properly reported in Bamboo CI builds. This commit ensures that both JUnit and TestNG tests are executed in the Gradle build by defining a new testNG task within the spring-test configuration. The test task now depends on the new testNG task. Furthermore, the testNG task makes use of Gradle 1.3's support for generating test reports for TestNG tests alongside reports for JUnit tests. The net effect is that all tests are executed and reportedly properly in Bamboo builds on the CI server. - Enabled both JUnit and TestNG tests for the spring-test module. - Corrected bugs in FailingBeforeAndAfterMethodsTests introduced in commit 3d1b3868fe3b38f5552883f54111c53f6ee75572. - Deleted the now obsolete SPR-9398.txt file. Issue: SPR-9398 --- build.gradle | 16 ++++++++++++++-- .../FailingBeforeAndAfterMethodsTests.java | 8 +++----- .../test/context/testng/SPR-9398.txt | 3 --- 3 files changed, 17 insertions(+), 10 deletions(-) delete mode 100644 spring-test/src/test/java/org/springframework/test/context/testng/SPR-9398.txt diff --git a/build.gradle b/build.gradle index 724927507f..3ddef1b239 100644 --- a/build.gradle +++ b/build.gradle @@ -640,10 +640,22 @@ project("spring-webmvc-portlet") { project("spring-test") { description = "Spring TestContext Framework" - test { - useJUnit() + + task testNG(type: Test) { useTestNG() + // "TestCase" classes are run by other test classes, not the build. + exclude "**/*TestCase.class" + // Generate TestNG reports alongside JUnit reports. + testReport true } + + test { + dependsOn testNG + useJUnit() + // "TestCase" classes are run by other test classes, not the build. + exclude "**/*TestCase.class" + } + dependencies { compile(project(":spring-core")) optional(project(":spring-beans")) diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/FailingBeforeAndAfterMethodsTests.java b/spring-test/src/test/java/org/springframework/test/context/testng/FailingBeforeAndAfterMethodsTests.java index 05ba435f9b..74e8f2513a 100644 --- a/spring-test/src/test/java/org/springframework/test/context/testng/FailingBeforeAndAfterMethodsTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/testng/FailingBeforeAndAfterMethodsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -237,8 +237,7 @@ public class FailingBeforeAndAfterMethodsTests { @BeforeTransaction public void beforeTransaction() { - // See SPR-8116 - //org.testng.Assert.fail("always failing beforeTransaction()"); + org.testng.Assert.fail("always failing beforeTransaction()"); } } @@ -251,8 +250,7 @@ public class FailingBeforeAndAfterMethodsTests { @AfterTransaction public void afterTransaction() { - // See SPR-8116 - //org.testng.Assert.fail("always failing afterTransaction()"); + org.testng.Assert.fail("always failing afterTransaction()"); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/testng/SPR-9398.txt b/spring-test/src/test/java/org/springframework/test/context/testng/SPR-9398.txt deleted file mode 100644 index dfbdc9ad83..0000000000 --- a/spring-test/src/test/java/org/springframework/test/context/testng/SPR-9398.txt +++ /dev/null @@ -1,3 +0,0 @@ -TODO [SPR-9398] re-enable TestNG support for spring-test. - -These TestNG test classes are currently not run at all. From 10dceb182e86fb79f6ad36a92d5f28088a319379 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 21 Dec 2012 21:33:11 +0100 Subject: [PATCH 032/311] Marked LocalCacheProviderProxy as deprecated (following Hibernate 3.3.'s CacheProvider deprecation) --- .../orm/hibernate3/LocalCacheProviderProxy.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java index dcf15059d3..1c7353697a 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/LocalCacheProviderProxy.java @@ -30,7 +30,10 @@ import org.hibernate.cache.CacheProvider; * @author Juergen Hoeller * @since 2.5.1 * @see LocalSessionFactoryBean#setCacheProvider + * @deprecated as of Spring 3.0, following Hibernate 3.3's deprecation + * of the CacheProvider SPI */ +@Deprecated public class LocalCacheProviderProxy implements CacheProvider { private final CacheProvider cacheProvider; From 3a9ca4a6bb8289b8495f22a9e60dc7799c93493b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 3 Jan 2013 16:31:00 +0100 Subject: [PATCH 033/311] MessageSourceResourceBundle overrides JDK 1.6 containsKey method, avoiding NPE in getKeys Issue: SPR-10136 --- .../support/MessageSourceResourceBundle.java | 29 +++++++++++++++---- .../ResourceBundleMessageSourceTests.java | 13 ++++++++- 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/support/MessageSourceResourceBundle.java b/spring-context/src/main/java/org/springframework/context/support/MessageSourceResourceBundle.java index 8dc2c1ffb3..605aa72e87 100644 --- a/spring-context/src/main/java/org/springframework/context/support/MessageSourceResourceBundle.java +++ b/spring-context/src/main/java/org/springframework/context/support/MessageSourceResourceBundle.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -70,9 +70,9 @@ public class MessageSourceResourceBundle extends ResourceBundle { * Returns {@code null} if the message could not be resolved. */ @Override - protected Object handleGetObject(String code) { + protected Object handleGetObject(String key) { try { - return this.messageSource.getMessage(code, null, this.locale); + return this.messageSource.getMessage(key, null, this.locale); } catch (NoSuchMessageException ex) { return null; @@ -80,12 +80,29 @@ public class MessageSourceResourceBundle extends ResourceBundle { } /** - * This implementation returns {@code null}, as a MessageSource does - * not allow for enumerating the defined message codes. + * This implementation checks whether the target MessageSource can resolve + * a message for the given key, translating {@code NoSuchMessageException} + * accordingly. In contrast to ResourceBundle's default implementation in + * JDK 1.6, this does not rely on the capability to enumerate message keys. + */ + @Override + public boolean containsKey(String key) { + try { + this.messageSource.getMessage(key, null, this.locale); + return true; + } + catch (NoSuchMessageException ex) { + return false; + } + } + + /** + * This implementation throws {@code UnsupportedOperationException}, + * as a MessageSource does not allow for enumerating the defined message codes. */ @Override public Enumeration getKeys() { - return null; + throw new UnsupportedOperationException("MessageSourceResourceBundle does not support enumerating its keys"); } /** diff --git a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java index 7e45ce9898..c0121a4a2d 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ResourceBundleMessageSourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -340,6 +340,17 @@ public class ResourceBundleMessageSourceTests extends TestCase { assertEquals(0, filenames.size()); } + public void testMessageSourceResourceBundle() { + ResourceBundleMessageSource ms = new ResourceBundleMessageSource(); + ms.setBasename("org/springframework/context/support/messages"); + MessageSourceResourceBundle rbe = new MessageSourceResourceBundle(ms, Locale.ENGLISH); + assertEquals("message1", rbe.getString("code1")); + assertTrue(rbe.containsKey("code1")); + MessageSourceResourceBundle rbg = new MessageSourceResourceBundle(ms, Locale.GERMAN); + assertEquals("nachricht2", rbg.getString("code2")); + assertTrue(rbg.containsKey("code2")); + } + @Override protected void tearDown() throws Exception { if (JdkVersion.getMajorJavaVersion() >= JdkVersion.JAVA_16) { From 97ae403b53b5ca2402c5d651dfdc6295d6372735 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 4 Jan 2013 12:25:24 +0100 Subject: [PATCH 034/311] AbstractAdvisingBeanPostProcessor caches per bean target class, working for null bean names as well Issue: SPR-10144 --- .../AbstractAdvisingBeanPostProcessor.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java b/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java index 9e6baee932..5d76f6c8a5 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,7 +47,7 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyConfig */ private int order = Ordered.LOWEST_PRECEDENCE; - private final Map eligibleBeans = new ConcurrentHashMap(64); + private final Map eligibleBeans = new ConcurrentHashMap(64); public void setBeanClassLoader(ClassLoader beanClassLoader) { @@ -94,19 +94,21 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyConfig /** * Check whether the given bean is eligible for advising with this * post-processor's {@link Advisor}. - *

Implements caching of {@code canApply} results per bean name. + *

Implements caching of {@code canApply} results per bean target class. + * Can be overridden e.g. to specifically exclude certain beans by name. * @param bean the bean instance * @param beanName the name of the bean + * @see AopUtils#getTargetClass(Object) * @see AopUtils#canApply(Advisor, Class) */ protected boolean isEligible(Object bean, String beanName) { - Boolean eligible = this.eligibleBeans.get(beanName); + Class targetClass = AopUtils.getTargetClass(bean); + Boolean eligible = this.eligibleBeans.get(targetClass); if (eligible != null) { return eligible; } - Class targetClass = AopUtils.getTargetClass(bean); eligible = AopUtils.canApply(this.advisor, targetClass); - this.eligibleBeans.put(beanName, eligible); + this.eligibleBeans.put(targetClass, eligible); return eligible; } From f8a7cf9f515f0d77fa515cec6af22ad1c8f2a58b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 9 Jan 2013 18:10:25 +0100 Subject: [PATCH 035/311] MimeMessageHelper encodes attachment filename if not ASCII compliant Issue: SPR-9258 --- .../mail/javamail/MimeMessageHelper.java | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java b/spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java index 47a115e980..4184b2f3b4 100644 --- a/spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java +++ b/spring-context-support/src/main/java/org/springframework/mail/javamail/MimeMessageHelper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimePart; +import javax.mail.internet.MimeUtility; import org.springframework.core.io.InputStreamSource; import org.springframework.core.io.Resource; @@ -960,7 +961,7 @@ public class MimeMessageHelper { * @see #addInline(String, javax.activation.DataSource) */ public void addInline(String contentId, InputStreamSource inputStreamSource, String contentType) - throws MessagingException { + throws MessagingException { Assert.notNull(inputStreamSource, "InputStreamSource must not be null"); if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) { @@ -989,11 +990,16 @@ public class MimeMessageHelper { public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException { Assert.notNull(attachmentFilename, "Attachment filename must not be null"); Assert.notNull(dataSource, "DataSource must not be null"); - MimeBodyPart mimeBodyPart = new MimeBodyPart(); - mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); - mimeBodyPart.setFileName(attachmentFilename); - mimeBodyPart.setDataHandler(new DataHandler(dataSource)); - getRootMimeMultipart().addBodyPart(mimeBodyPart); + try { + MimeBodyPart mimeBodyPart = new MimeBodyPart(); + mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT); + mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename)); + mimeBodyPart.setDataHandler(new DataHandler(dataSource)); + getRootMimeMultipart().addBodyPart(mimeBodyPart); + } + catch (UnsupportedEncodingException ex) { + throw new MessagingException("Failed to encode attachment filename", ex); + } } /** @@ -1035,7 +1041,7 @@ public class MimeMessageHelper { * @see org.springframework.core.io.Resource */ public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource) - throws MessagingException { + throws MessagingException { String contentType = getFileTypeMap().getContentType(attachmentFilename); addAttachment(attachmentFilename, inputStreamSource, contentType); @@ -1059,7 +1065,7 @@ public class MimeMessageHelper { */ public void addAttachment( String attachmentFilename, InputStreamSource inputStreamSource, String contentType) - throws MessagingException { + throws MessagingException { Assert.notNull(inputStreamSource, "InputStreamSource must not be null"); if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) { From 5e8e901aba9abc55a9f3dedd0b5d5a0d8841357f Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 9 Jan 2013 18:24:41 +0100 Subject: [PATCH 036/311] FreeMarkerConfigurationFactory properly supports TemplateLoaders when recreating Configurations Issue: SPR-9389 --- .../FreeMarkerConfigurationFactory.java | 27 ++++++++++--------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java b/spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java index 574c7695e7..027f0f4a6b 100644 --- a/spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java +++ b/spring-context-support/src/main/java/org/springframework/ui/freemarker/FreeMarkerConfigurationFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; @@ -147,7 +148,7 @@ public class FreeMarkerConfigurationFactory { * @see #setPostTemplateLoaders */ @Deprecated - public void setTemplateLoaders(TemplateLoader[] templateLoaders) { + public void setTemplateLoaders(TemplateLoader... templateLoaders) { if (templateLoaders != null) { this.templateLoaders.addAll(Arrays.asList(templateLoaders)); } @@ -164,7 +165,7 @@ public class FreeMarkerConfigurationFactory { * @see #setTemplateLoaderPaths * @see #postProcessTemplateLoaders */ - public void setPreTemplateLoaders(TemplateLoader[] preTemplateLoaders) { + public void setPreTemplateLoaders(TemplateLoader... preTemplateLoaders) { this.preTemplateLoaders = Arrays.asList(preTemplateLoaders); } @@ -179,7 +180,7 @@ public class FreeMarkerConfigurationFactory { * @see #setTemplateLoaderPaths * @see #postProcessTemplateLoaders */ - public void setPostTemplateLoaders(TemplateLoader[] postTemplateLoaders) { + public void setPostTemplateLoaders(TemplateLoader... postTemplateLoaders) { this.postTemplateLoaders = Arrays.asList(postTemplateLoaders); } @@ -211,7 +212,7 @@ public class FreeMarkerConfigurationFactory { * @see SpringTemplateLoader * @see #setTemplateLoaders */ - public void setTemplateLoaderPaths(String[] templateLoaderPaths) { + public void setTemplateLoaderPaths(String... templateLoaderPaths) { this.templateLoaderPaths = templateLoaderPaths; } @@ -229,7 +230,7 @@ public class FreeMarkerConfigurationFactory { * Return the Spring ResourceLoader to use for loading FreeMarker template files. */ protected ResourceLoader getResourceLoader() { - return resourceLoader; + return this.resourceLoader; } /** @@ -252,7 +253,7 @@ public class FreeMarkerConfigurationFactory { * Return whether to prefer file system access for template loading. */ protected boolean isPreferFileSystemAccess() { - return preferFileSystemAccess; + return this.preferFileSystemAccess; } @@ -293,25 +294,27 @@ public class FreeMarkerConfigurationFactory { config.setDefaultEncoding(this.defaultEncoding); } + List templateLoaders = new LinkedList(this.templateLoaders); + // Register template loaders that are supposed to kick in early. if (this.preTemplateLoaders != null) { - this.templateLoaders.addAll(this.preTemplateLoaders); + templateLoaders.addAll(this.preTemplateLoaders); } // Register default template loaders. if (this.templateLoaderPaths != null) { for (String path : this.templateLoaderPaths) { - this.templateLoaders.add(getTemplateLoaderForPath(path)); + templateLoaders.add(getTemplateLoaderForPath(path)); } } - postProcessTemplateLoaders(this.templateLoaders); + postProcessTemplateLoaders(templateLoaders); // Register template loaders that are supposed to kick in late. if (this.postTemplateLoaders != null) { - this.templateLoaders.addAll(this.postTemplateLoaders); + templateLoaders.addAll(this.postTemplateLoaders); } - TemplateLoader loader = getAggregateTemplateLoader(this.templateLoaders); + TemplateLoader loader = getAggregateTemplateLoader(templateLoaders); if (loader != null) { config.setTemplateLoader(loader); } From f6d7518013d97ed9f1edfa4c6b65065eafac445b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 9 Jan 2013 18:42:10 +0100 Subject: [PATCH 037/311] SpringContextResourceAdapter implements equals/hashCode according to the JCA 1.5 contract Issue: SPR-9162 --- .../context/SpringContextResourceAdapter.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/spring-tx/src/main/java/org/springframework/jca/context/SpringContextResourceAdapter.java b/spring-tx/src/main/java/org/springframework/jca/context/SpringContextResourceAdapter.java index 25bac95668..41bf544727 100644 --- a/spring-tx/src/main/java/org/springframework/jca/context/SpringContextResourceAdapter.java +++ b/spring-tx/src/main/java/org/springframework/jca/context/SpringContextResourceAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,7 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.StandardEnvironment; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** @@ -228,4 +229,17 @@ public class SpringContextResourceAdapter implements ResourceAdapter { return null; } + + @Override + public boolean equals(Object obj) { + return (obj instanceof SpringContextResourceAdapter && + ObjectUtils.nullSafeEquals(getContextConfigLocation(), + ((SpringContextResourceAdapter) obj).getContextConfigLocation())); + } + + @Override + public int hashCode() { + return ObjectUtils.nullSafeHashCode(getContextConfigLocation()); + } + } From dae4485155096c1b9db1389fc90058c48d8e7906 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 10 Jan 2013 16:47:27 +0100 Subject: [PATCH 038/311] Added dedicated sort method to AnnotationAwareOrderComparator Issue: SPR-9625 --- .../AnnotationAwareOrderComparator.java | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java index a24f2cde3a..bf7232e10a 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,10 @@ package org.springframework.core.annotation; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; @@ -37,7 +41,7 @@ public class AnnotationAwareOrderComparator extends OrderComparator { /** * Shared default instance of AnnotationAwareOrderComparator. */ - public static AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator(); + public static final AnnotationAwareOrderComparator INSTANCE = new AnnotationAwareOrderComparator(); @Override @@ -54,4 +58,31 @@ public class AnnotationAwareOrderComparator extends OrderComparator { return Ordered.LOWEST_PRECEDENCE; } + + /** + * Sort the given List with a default AnnotationAwareOrderComparator. + *

Optimized to skip sorting for lists with size 0 or 1, + * in order to avoid unnecessary array extraction. + * @param list the List to sort + * @see java.util.Collections#sort(java.util.List, java.util.Comparator) + */ + public static void sort(List list) { + if (list.size() > 1) { + Collections.sort(list, INSTANCE); + } + } + + /** + * Sort the given array with a default AnnotationAwareOrderComparator. + *

Optimized to skip sorting for lists with size 0 or 1, + * in order to avoid unnecessary array extraction. + * @param array the array to sort + * @see java.util.Arrays#sort(Object[], java.util.Comparator) + */ + public static void sort(Object[] array) { + if (array.length > 1) { + Arrays.sort(array, INSTANCE); + } + } + } From e806c4eb3d5bd660c169e2b215a4e29b1f43bf35 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 10 Jan 2013 16:55:32 +0100 Subject: [PATCH 039/311] AnnotationAwareOrderComparator is able to sort Class objects as well Issue: SPR-10152 --- .../AnnotationAwareOrderComparator.java | 3 +- .../AnnotationAwareOrderComparatorTests.java | 43 ++++++++++++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java index bf7232e10a..c9d1fe47c5 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationAwareOrderComparator.java @@ -50,7 +50,8 @@ public class AnnotationAwareOrderComparator extends OrderComparator { return ((Ordered) obj).getOrder(); } if (obj != null) { - Order order = obj.getClass().getAnnotation(Order.class); + Class clazz = (obj instanceof Class ? (Class) obj : obj.getClass()); + Order order = clazz.getAnnotation(Order.class); if (order != null) { return order.value(); } diff --git a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java index 9bdd19f54b..47634bb760 100644 --- a/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java +++ b/spring-core/src/test/java/org/springframework/core/annotation/AnnotationAwareOrderComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.core.annotation; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; -import org.junit.Test; - /** - * Unit tests for {@link AnnotationAwareOrderComparator}. - * + * @author Juergen Hoeller * @author Oliver Gierke */ public class AnnotationAwareOrderComparatorTests { @@ -31,4 +34,34 @@ public class AnnotationAwareOrderComparatorTests { public void instanceVariableIsAnAnnotationAwareOrderComparator() { assertThat(AnnotationAwareOrderComparator.INSTANCE, is(instanceOf(AnnotationAwareOrderComparator.class))); } + + @Test + public void sortInstances() { + List list = new ArrayList<>(); + list.add(new B()); + list.add(new A()); + AnnotationAwareOrderComparator.sort(list); + assertTrue(list.get(0) instanceof A); + assertTrue(list.get(1) instanceof B); + } + + @Test + public void sortClasses() { + List list = new ArrayList<>(); + list.add(B.class); + list.add(A.class); + AnnotationAwareOrderComparator.sort(list); + assertEquals(A.class, list.get(0)); + assertEquals(B.class, list.get(1)); + } + + + @Order(1) + private static class A { + } + + @Order(2) + private static class B { + } + } From ea823fd398d0a3030c477399a33074fc6c6acae6 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 10 Jan 2013 17:01:18 +0100 Subject: [PATCH 040/311] AnnotationAwareOrderComparator etc --- src/dist/changelog.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index b9726400ae..f81937f9b5 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -6,11 +6,18 @@ http://www.springsource.org Changes in version 3.2.1 (2013-01-24) -------------------------------------- +* AnnotationAwareOrderComparator is able to sort Class objects as well (SPR-10152) +* added dedicated sort method to AnnotationAwareOrderComparator (SPR-9625) * fixed QualifierAnnotationAutowireCandidateResolver's detection of custom qualifier annotations (SPR-10107) * fixed AbstractAutoProxyCreator to accept null bean names again (SPR-10108) +* AbstractAdvisingBeanPostProcessor caches per bean target class, working for null bean names as well (SPR-10144) +* MessageSourceResourceBundle overrides JDK 1.6 containsKey method, avoiding NPE in getKeys (SPR-10136) * spring-task-3.2.xsd allows for SpEL expressions in initial-delay attribute (SPR-10102) * JmsTemplate uses configured receiveTimeout if shorter than remaining transaction timeout (SPR-10109) * added MappingJackson2MessageConverter for JMS (SPR-10099) +* MimeMessageHelper encodes attachment filename if not ASCII compliant (SPR-9258) +* FreeMarkerConfigurationFactory properly supports TemplateLoaders when recreating Configurations (SPR-9389) +* SpringContextResourceAdapter implements equals/hashCode according to the JCA 1.5 contract (SPR-9162) Changes in version 3.2 GA (2012-12-13) From 2427391286f489e11981e1072aaebbf78dd5d3f7 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 10 Jan 2013 17:33:59 +0100 Subject: [PATCH 041/311] Polish Javadoc in CookieValue and RequestHeader --- .../web/bind/annotation/CookieValue.java | 8 ++++---- .../web/bind/annotation/RequestHeader.java | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java index 7f469a4318..6af1c621de 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/CookieValue.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -55,14 +55,14 @@ public @interface CookieValue { * in case the header is missing in the request. Switch this to * {@code false} if you prefer a {@code null} in case of the * missing header. - *

Alternatively, provide a {@link #defaultValue() defaultValue}, - * which implicitly sets this flag to {@code false}. + *

Alternatively, provide a {@link #defaultValue}, which implicitly sets + * this flag to {@code false}. */ boolean required() default true; /** * The default value to use as a fallback. Supplying a default value implicitly - * sets {@link #required()} to false. + * sets {@link #required} to {@code false}. */ String defaultValue() default ValueConstants.DEFAULT_NONE; diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java index 9d094d75d3..47d2a56727 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestHeader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,14 +49,14 @@ public @interface RequestHeader { *

Default is {@code true}, leading to an exception thrown in case * of the header missing in the request. Switch this to {@code false} * if you prefer a {@code null} in case of the header missing. - *

Alternatively, provide a {@link #defaultValue() defaultValue}, - * which implicitely sets this flag to {@code false}. + *

Alternatively, provide a {@link #defaultValue}, which implicitly sets + * this flag to {@code false}. */ boolean required() default true; /** - * The default value to use as a fallback. Supplying a default value implicitely - * sets {@link #required()} to false. + * The default value to use as a fallback. Supplying a default value implicitly + * sets {@link #required} to {@code false}. */ String defaultValue() default ValueConstants.DEFAULT_NONE; From 91da1383143bc15f945935960a79bc253bd1ce16 Mon Sep 17 00:00:00 2001 From: Rob Winch Date: Thu, 10 Jan 2013 15:17:37 -0600 Subject: [PATCH 042/311] Use explicit JDK versions in aspects.gradle Previously aspects.gradle used the Gradle conventions for the source and target compatibility. This means that unless the conventions were updated the current JDK would be used for both source and target compatibilty. Since an update to build.gradle changed to configure the compileJava and compileTestJava tasks explicitly spring-aspects has been compiled with JDK 7 compatibility. This commit explicitly uses the source and target compatibility from spring-core to ensure that aspects.gradle is kept up to date. Issue: SPR-10161 --- spring-aspects/aspects.gradle | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/spring-aspects/aspects.gradle b/spring-aspects/aspects.gradle index 0432414467..c99fa03183 100644 --- a/spring-aspects/aspects.gradle +++ b/spring-aspects/aspects.gradle @@ -21,6 +21,9 @@ task compileJava(overwrite: true) { inputs.files(project.sourceSets.main.allSource + project.sourceSets.main.compileClasspath) outputs.dir outputDir + ext.sourceCompatibility = project(":spring-core").compileJava.sourceCompatibility + ext.targetCompatibility = project(":spring-core").compileJava.targetCompatibility + doLast{ ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath) @@ -51,6 +54,9 @@ task compileTestJava(overwrite: true) { inputs.files(project.sourceSets.test.allSource + project.sourceSets.test.compileClasspath) outputs.dir outputDir + ext.sourceCompatibility = project(":spring-core").compileTestJava.sourceCompatibility + ext.targetCompatibility = project(":spring-core").compileTestJava.targetCompatibility + doLast{ ant.taskdef(resource: "org/aspectj/tools/ant/taskdefs/aspectjTaskdefs.properties", classpath: configurations.ajc.asPath) From 18bf860c273179f95719d80b14d17c0c9ba99c38 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 11 Jan 2013 00:31:37 +0100 Subject: [PATCH 043/311] Update Javadoc for MockMvc Deleted reference to the obsolete configureWarRootDir() method from the stand-alone spring-test-mvc project. --- .../java/org/springframework/test/web/servlet/MockMvc.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java index a074ff6d14..b18fc3554f 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import org.springframework.util.Assert; * * WebApplicationContext wac = ...; * - * MockMvc mockMvc = webAppContextSetup(wac).configureWarRootDir("src/main/webapp", false).build() + * MockMvc mockMvc = webAppContextSetup(wac).build(); * * mockMvc.perform(get("/form")) * .andExpect(status().isOk()) From a0e5394203d3f485c592c2d05d7d1a6b3cff6ced Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 10 Jan 2013 19:01:40 -0800 Subject: [PATCH 044/311] Exclude stax test dependency Exclude transitive stax 1.0 dependency to prevent compile time eclipse errors. --- build.gradle | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 3ddef1b239..82a22f4922 100644 --- a/build.gradle +++ b/build.gradle @@ -235,7 +235,9 @@ project("spring-core") { optional("net.sf.jopt-simple:jopt-simple:3.0") optional("log4j:log4j:1.2.17") testCompile("xmlunit:xmlunit:1.3") - testCompile("org.codehaus.woodstox:wstx-asl:3.2.7") + testCompile("org.codehaus.woodstox:wstx-asl:3.2.7") { + exclude group: "stax", module: "stax-api" + } } jar { From c425d22151bf4a84459be1703b54143b88e4f547 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 10 Jan 2013 19:02:56 -0800 Subject: [PATCH 045/311] Exclude eclipse WTP generated artifacts --- .gitignore | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index c9e0aca55e..67d798efd4 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,6 @@ jmx.log derby.log spring-test/test-output/ .gradle -.classpath -.project argfile* pom.xml @@ -22,6 +20,11 @@ pom.xml buildSrc/build /spring-*/build +# Eclipse artifacts, including WTP generated manifests +.classpath +.project +spring-*/src/main/java/META-INF/MANIFEST.MF + # IDEA artifacts and output dirs *.iml *.ipr From b8f408ed5faae1bf266331063bc2ea575962bead Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 8 Jan 2013 17:02:43 +0100 Subject: [PATCH 046/311] Replace space indentation with tabs Issue: SPR-9990 --- build.gradle | 14 +- .../gradle/SplitPackageDetectorPlugin.groovy | 156 +++++++++--------- 2 files changed, 85 insertions(+), 85 deletions(-) diff --git a/build.gradle b/build.gradle index 697cdbea53..f67e2740c0 100644 --- a/build.gradle +++ b/build.gradle @@ -753,18 +753,18 @@ configure(rootProject) { apply plugin: "docbook-reference" apply plugin: "groovy" apply from: "${gradleScriptDir}/jdiff.gradle" - apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin + apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin - reference { + reference { sourceDir = file("src/reference/docbook") pdfFilename = "spring-framework-reference.pdf" } - diagnoseSplitPackages { - projectsToScan = project.subprojects - project(":spring-instrument-tomcat") // SPR-10150 - } + diagnoseSplitPackages { + projectsToScan = project.subprojects - project(":spring-instrument-tomcat") // SPR-10150 + } - // don"t publish the default jar for the root project + // don"t publish the default jar for the root project configurations.archives.artifacts.clear() dependencies { // for integration tests @@ -788,7 +788,7 @@ configure(rootProject) { testCompile("hsqldb:hsqldb:${hsqldbVersion}") } - check.dependsOn diagnoseSplitPackages + check.dependsOn diagnoseSplitPackages task api(type: Javadoc) { group = "Documentation" diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy index 01c36fad7a..eddfec385c 100644 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy @@ -31,101 +31,101 @@ import org.gradle.plugins.ide.eclipse.model.EclipseClasspath import org.gradle.plugins.ide.idea.IdeaPlugin class SplitPackageDetectorPlugin implements Plugin { - public void apply(Project project) { - Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) - diagnoseSplitPackages.setDescription('Detects packages which will be split across JARs') - } + public void apply(Project project) { + Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) + diagnoseSplitPackages.setDescription('Detects packages which will be split across JARs') + } } public class SplitPackageDetectorTask extends DefaultTask { - @Input - Set projectsToScan + @Input + Set projectsToScan - @TaskAction - public final void diagnoseSplitPackages() { - def Map mergeMap = [:] - def projects = projectsToScan.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } - projects.each { p -> - mergeMap.put(p, p.merge.into) - } - def splitFound = new org.springframework.build.gradle.SplitPackageDetector(projectsToScan, mergeMap, project.logger).diagnoseSplitPackages(); - assert !splitFound // see error log messages for details of split packages - } + @TaskAction + public final void diagnoseSplitPackages() { + def Map mergeMap = [:] + def projects = projectsToScan.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } + projects.each { p -> + mergeMap.put(p, p.merge.into) + } + def splitFound = new org.springframework.build.gradle.SplitPackageDetector(projectsToScan, mergeMap, project.logger).diagnoseSplitPackages(); + assert !splitFound // see error log messages for details of split packages + } } class SplitPackageDetector { - private static final String HIDDEN_DIRECTORY_PREFIX = "." + private static final String HIDDEN_DIRECTORY_PREFIX = "." - private static final String JAVA_FILE_SUFFIX = ".java" + private static final String JAVA_FILE_SUFFIX = ".java" - private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" + private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" - private static final String PACKAGE_SEPARATOR = "." + private static final String PACKAGE_SEPARATOR = "." - private final Map mergeMap + private final Map mergeMap - private final Map> pkgMap = [:] + private final Map> pkgMap = [:] - private final logger + private final logger - SplitPackageDetector(projectsToScan, mergeMap, logger) { - this.mergeMap = mergeMap - this.logger = logger - projectsToScan.each { Project p -> - def dir = p.projectDir - def packages = getPackagesInDirectory(dir) - if (!packages.isEmpty()) { - pkgMap.put(p, packages) - } - } - } + SplitPackageDetector(projectsToScan, mergeMap, logger) { + this.mergeMap = mergeMap + this.logger = logger + projectsToScan.each { Project p -> + def dir = p.projectDir + def packages = getPackagesInDirectory(dir) + if (!packages.isEmpty()) { + pkgMap.put(p, packages) + } + } + } - private File[] dirList(String dir) { - dirList(new File(dir)) - } + private File[] dirList(String dir) { + dirList(new File(dir)) + } - private File[] dirList(File dir) { - dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) - } + private File[] dirList(File dir) { + dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) + } - private Set getPackagesInDirectory(File dir) { - def pkgs = new HashSet() - addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") - return pkgs; - } + private Set getPackagesInDirectory(File dir) { + def pkgs = new HashSet() + addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") + return pkgs; + } - boolean diagnoseSplitPackages() { - def splitFound = false; - def projs = pkgMap.keySet().toArray() - def numProjects = projs.length - for (int i = 0; i < numProjects - 1; i++) { - for (int j = i + 1; j < numProjects - 1; j++) { - def pi = projs[i] - def pkgi = new HashSet(pkgMap.get(pi)) - def pj = projs[j] - def pkgj = pkgMap.get(pj) - pkgi.retainAll(pkgj) - if (!pkgi.isEmpty() && mergeMap.get(pi) != pj && mergeMap.get(pj) != pi) { - pkgi.each { pkg -> - def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) - logger.error("Package '$readablePkg' is split between $pi and $pj") - } - splitFound = true - } - } - } - return splitFound - } + boolean diagnoseSplitPackages() { + def splitFound = false; + def projs = pkgMap.keySet().toArray() + def numProjects = projs.length + for (int i = 0; i < numProjects - 1; i++) { + for (int j = i + 1; j < numProjects - 1; j++) { + def pi = projs[i] + def pkgi = new HashSet(pkgMap.get(pi)) + def pj = projs[j] + def pkgj = pkgMap.get(pj) + pkgi.retainAll(pkgj) + if (!pkgi.isEmpty() && mergeMap.get(pi) != pj && mergeMap.get(pj) != pi) { + pkgi.each { pkg -> + def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) + logger.error("Package '$readablePkg' is split between $pi and $pj") + } + splitFound = true + } + } + } + return splitFound + } - private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { - def scanDir = new File(dir, pkg) - def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) - if (javaFiles != null && javaFiles.length != 0) { - packages.add(pkg) - } - dirList(scanDir).each { File subDir -> - addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) - } - } -} \ No newline at end of file + private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { + def scanDir = new File(dir, pkg) + def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) + if (javaFiles != null && javaFiles.length != 0) { + packages.add(pkg) + } + dirList(scanDir).each { File subDir -> + addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) + } + } +} From 654c07db344310d8582c433dc643b0a256c8cc7e Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 11 Jan 2013 15:54:11 +0100 Subject: [PATCH 047/311] Refactor detect-split-packages Gradle plugin - Use conventional plugin naming, i.e. "detect-split-packages" instead of applying plugin based on fully-qualified class name - Rename "diagnose" => "detect" consistently throughout plugin, task and method names and generally refactor naming throughout to follow "detect split packages" phrasing - Add Javadoc to DetectSplitPackagesPlugin - Improve error reporting when split packages are detected Upon detecting one or more split packages, `detectSplitPackages` now fails idiomatically, throwing a GradleException to signal task failure (as opposed to the previous approach of using an assert assertion), and the output reads as follows: $ gradle detectSplitPackages [...] :buildSrc:build UP-TO-DATE :detectSplitPackages FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':detectSplitPackages'. > The following split package(s) have been detected: - org.springframework.beans (split across spring-beans and spring-orm) - org.springframework.core.env (split across spring-context and spring-core) - DetectSplitPackagesTask now automatically attaches itself to `check` task lifecycle if the enclosing project contains a `check` task - DetectSplitPackagesTask adds itself to the 'Verification' task group, ensuring that it shows up correctly in `gradle tasks` task listings - packagesToScan now defaults to all subprojects; users may then customize this by removing individual subprojects from the collection Issue: SPR-9990 --- build.gradle | 8 +- .../gradle/DetectSplitPackagesPlugin.groovy | 157 ++++++++++++++++++ .../gradle/SplitPackageDetectorPlugin.groovy | 131 --------------- .../detect-split-packages.properties | 1 + 4 files changed, 161 insertions(+), 136 deletions(-) create mode 100644 buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy delete mode 100644 buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy create mode 100644 buildSrc/src/main/resources/META-INF/gradle-plugins/detect-split-packages.properties diff --git a/build.gradle b/build.gradle index f67e2740c0..11e9ed8bec 100644 --- a/build.gradle +++ b/build.gradle @@ -752,16 +752,16 @@ configure(rootProject) { apply plugin: "docbook-reference" apply plugin: "groovy" + apply plugin: "detect-split-packages" apply from: "${gradleScriptDir}/jdiff.gradle" - apply plugin: org.springframework.build.gradle.SplitPackageDetectorPlugin reference { sourceDir = file("src/reference/docbook") pdfFilename = "spring-framework-reference.pdf" } - diagnoseSplitPackages { - projectsToScan = project.subprojects - project(":spring-instrument-tomcat") // SPR-10150 + detectSplitPackages { + projectsToScan -= project(":spring-instrument-tomcat") } // don"t publish the default jar for the root project @@ -788,8 +788,6 @@ configure(rootProject) { testCompile("hsqldb:hsqldb:${hsqldbVersion}") } - check.dependsOn diagnoseSplitPackages - task api(type: Javadoc) { group = "Documentation" description = "Generates aggregated Javadoc API documentation." diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy new file mode 100644 index 0000000000..8b73878694 --- /dev/null +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy @@ -0,0 +1,157 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.build.gradle + +import org.gradle.api.DefaultTask +import org.gradle.api.GradleException +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.Task +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.TaskAction + +/** + * Gradle plugin that detects identically named, non-empty packages split across multiple + * subprojects, e.g. "org.springframework.context.annotation" existing in both spring-core + * and spring-aspects. Adds a 'detectSplitPackages' task to the current project's task + * collection. If the project already contains a 'check' task (i.e. is a typical Gradle + * project with the "java" plugin applied), the 'check' task will be updated to depend on + * the execution of 'detectSplitPackages'. + * + * By default, all subprojects will be scanned. Use the 'projectsToScan' task property to + * modify this value. Example usage: + * + * apply plugin: 'detect-split-packages // typically applied to root project + * + * detectSplitPackages { + * packagesToScan -= project(":spring-xyz") // scan every project but spring-xyz + * } + * + * @author Rob Winch + * @author Glyn Normington + * @author Chris Beams + */ +public class DetectSplitPackagesPlugin implements Plugin { + public void apply(Project project) { + def tasks = project.tasks + Task detectSplitPackages = tasks.add('detectSplitPackages', DetectSplitPackagesTask.class) + if (tasks.asMap.containsKey('check')) { + tasks.getByName('check').dependsOn detectSplitPackages + } + } +} + +public class DetectSplitPackagesTask extends DefaultTask { + + private static final String JAVA_FILE_SUFFIX = ".java" + private static final String PACKAGE_SEPARATOR = "." + private static final String HIDDEN_DIRECTORY_PREFIX = "." + + @Input + Set projectsToScan = project.subprojects + + public DetectSplitPackagesTask() { + this.group = 'Verification' + this.description = 'Detects packages split across two or more subprojects.' + } + + @TaskAction + public void detectSplitPackages() { + def splitPackages = doDetectSplitPackages() + if (!splitPackages.isEmpty()) { + def message = "The following split package(s) have been detected:\n" + splitPackages.each { pkg, mod -> + message += " - ${pkg} (split across ${mod[0].name} and ${mod[1].name})\n" + } + throw new GradleException(message) + } + } + + private Map> doDetectSplitPackages() { + def splitPackages = [:] + def mergedProjects = findMergedProjects() + def packagesByProject = mapPackagesByProject() + + def projects = packagesByProject.keySet().toArray() + def nProjects = projects.length + + for (int i = 0; i < nProjects - 1; i++) { + for (int j = i + 1; j < nProjects - 1; j++) { + def prj_i = projects[i] + def prj_j = projects[j] + + def pkgs_i = new HashSet(packagesByProject.get(prj_i)) + def pkgs_j = packagesByProject.get(prj_j) + pkgs_i.retainAll(pkgs_j) + + if (!pkgs_i.isEmpty() + && mergedProjects.get(prj_i) != prj_j + && mergedProjects.get(prj_j) != prj_i) { + pkgs_i.each { pkg -> + def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) + splitPackages[readablePkg] = [prj_i, prj_j] + } + } + } + } + return splitPackages; + } + + private Map> mapPackagesByProject() { + def packagesByProject = [:] + this.projectsToScan.each { Project p -> + def packages = new HashSet() + p.sourceSets.main.java.srcDirs.each { File dir -> + findPackages(packages, dir, "") + } + if (!packages.isEmpty()) { + packagesByProject.put(p, packages) + } + } + return packagesByProject; + } + + private Map findMergedProjects() { + def mergedProjects = [:] + this.projectsToScan.findAll { p -> + p.plugins.findPlugin(MergePlugin) + }.findAll { p -> + p.merge.into + }.each { p -> + mergedProjects.put(p, p.merge.into) + } + return mergedProjects + } + + private static void findPackages(Set packages, File dir, String packagePath) { + def scanDir = new File(dir, packagePath) + def File[] javaFiles = scanDir.listFiles({ file -> + !file.isDirectory() && file.name.endsWith(JAVA_FILE_SUFFIX) + } as FileFilter) + + if (javaFiles != null && javaFiles.length != 0) { + packages.add(packagePath) + } + + scanDir.listFiles({ File file -> + file.isDirectory() && !file.name.startsWith(HIDDEN_DIRECTORY_PREFIX) + } as FileFilter).each { File subDir -> + findPackages(packages, dir, packagePath + File.separator + subDir.name) + } + } +} + diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy deleted file mode 100644 index eddfec385c..0000000000 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/SplitPackageDetectorPlugin.groovy +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.build.gradle - -import org.gradle.api.DefaultTask -import org.gradle.api.Plugin -import org.gradle.api.Project -import org.gradle.api.Task -import org.gradle.api.artifacts.Configuration -import org.gradle.api.artifacts.ProjectDependency -import org.gradle.api.artifacts.maven.Conf2ScopeMapping -import org.gradle.api.plugins.MavenPlugin -import org.gradle.api.tasks.Input -import org.gradle.api.tasks.TaskAction -import org.gradle.plugins.ide.eclipse.EclipsePlugin -import org.gradle.plugins.ide.eclipse.model.EclipseClasspath -import org.gradle.plugins.ide.idea.IdeaPlugin - -class SplitPackageDetectorPlugin implements Plugin { - public void apply(Project project) { - Task diagnoseSplitPackages = project.tasks.add('diagnoseSplitPackages', SplitPackageDetectorTask.class) - diagnoseSplitPackages.setDescription('Detects packages which will be split across JARs') - } -} - -public class SplitPackageDetectorTask extends DefaultTask { - @Input - Set projectsToScan - - @TaskAction - public final void diagnoseSplitPackages() { - def Map mergeMap = [:] - def projects = projectsToScan.findAll { it.plugins.findPlugin(org.springframework.build.gradle.MergePlugin) }.findAll { it.merge.into } - projects.each { p -> - mergeMap.put(p, p.merge.into) - } - def splitFound = new org.springframework.build.gradle.SplitPackageDetector(projectsToScan, mergeMap, project.logger).diagnoseSplitPackages(); - assert !splitFound // see error log messages for details of split packages - } -} - -class SplitPackageDetector { - - private static final String HIDDEN_DIRECTORY_PREFIX = "." - - private static final String JAVA_FILE_SUFFIX = ".java" - - private static final String SRC_MAIN_JAVA = "src" + File.separator + "main" + File.separator + "java" - - private static final String PACKAGE_SEPARATOR = "." - - private final Map mergeMap - - private final Map> pkgMap = [:] - - private final logger - - SplitPackageDetector(projectsToScan, mergeMap, logger) { - this.mergeMap = mergeMap - this.logger = logger - projectsToScan.each { Project p -> - def dir = p.projectDir - def packages = getPackagesInDirectory(dir) - if (!packages.isEmpty()) { - pkgMap.put(p, packages) - } - } - } - - private File[] dirList(String dir) { - dirList(new File(dir)) - } - - private File[] dirList(File dir) { - dir.listFiles({ file -> file.isDirectory() && !file.getName().startsWith(HIDDEN_DIRECTORY_PREFIX) } as FileFilter) - } - - private Set getPackagesInDirectory(File dir) { - def pkgs = new HashSet() - addPackagesInDirectory(pkgs, new File(dir, SRC_MAIN_JAVA), "") - return pkgs; - } - - boolean diagnoseSplitPackages() { - def splitFound = false; - def projs = pkgMap.keySet().toArray() - def numProjects = projs.length - for (int i = 0; i < numProjects - 1; i++) { - for (int j = i + 1; j < numProjects - 1; j++) { - def pi = projs[i] - def pkgi = new HashSet(pkgMap.get(pi)) - def pj = projs[j] - def pkgj = pkgMap.get(pj) - pkgi.retainAll(pkgj) - if (!pkgi.isEmpty() && mergeMap.get(pi) != pj && mergeMap.get(pj) != pi) { - pkgi.each { pkg -> - def readablePkg = pkg.substring(1).replaceAll(File.separator, PACKAGE_SEPARATOR) - logger.error("Package '$readablePkg' is split between $pi and $pj") - } - splitFound = true - } - } - } - return splitFound - } - - private void addPackagesInDirectory(HashSet packages, File dir, String pkg) { - def scanDir = new File(dir, pkg) - def File[] javaFiles = scanDir.listFiles({ file -> !file.isDirectory() && file.getName().endsWith(JAVA_FILE_SUFFIX) } as FileFilter) - if (javaFiles != null && javaFiles.length != 0) { - packages.add(pkg) - } - dirList(scanDir).each { File subDir -> - addPackagesInDirectory(packages, dir, pkg + File.separator + subDir.getName()) - } - } -} diff --git a/buildSrc/src/main/resources/META-INF/gradle-plugins/detect-split-packages.properties b/buildSrc/src/main/resources/META-INF/gradle-plugins/detect-split-packages.properties new file mode 100644 index 0000000000..10b1e4e981 --- /dev/null +++ b/buildSrc/src/main/resources/META-INF/gradle-plugins/detect-split-packages.properties @@ -0,0 +1 @@ +implementation-class=org.springframework.build.gradle.DetectSplitPackagesPlugin From 74137794da867703ef8399c9b21e0ca5066f72b3 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 11 Jan 2013 16:28:48 +0100 Subject: [PATCH 048/311] Polish changes from pull request #205 - Replace space intendation with tabs - Remove leading tabs on otherwise empty lines - Remove illegal {@link ...} syntax in Javadoc @see reference Issue: SPR-10093 --- .../servlet/setup/DefaultMockMvcBuilder.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java index 984be0c854..be50b4aee0 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java @@ -54,7 +54,7 @@ public class DefaultMockMvcBuilder extends MockMvcB private final List globalResultMatchers = new ArrayList(); private final List globalResultHandlers = new ArrayList(); - + private Boolean dispatchOptions = Boolean.FALSE; @@ -180,17 +180,17 @@ public class DefaultMockMvcBuilder extends MockMvcB this.globalResultHandlers.add(resultHandler); return (T) this; } - + /** - * Should the {@link DispatcherServlet} dispatch OPTIONS request to controllers. - * @param dispatchOptions - * @see {@link DispatcherServlet#setDispatchOptionsRequest(boolean)} - */ + * Should the {@link DispatcherServlet} dispatch OPTIONS request to controllers. + * @param dispatchOptions + * @see DispatcherServlet#setDispatchOptionsRequest(boolean) + */ @SuppressWarnings("unchecked") - public final T dispatchOptions(boolean dispatchOptions) { - this.dispatchOptions = dispatchOptions; - return (T) this; - } + public final T dispatchOptions(boolean dispatchOptions) { + this.dispatchOptions = dispatchOptions; + return (T) this; + } /** * Build a {@link MockMvc} instance. From c1fe3c056a26c80ffe81d2504664be3e276033c0 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 11 Jan 2013 12:19:52 -0800 Subject: [PATCH 049/311] Polish DetectSplitPackagesPlugin Polish DetectSplitPackagesPlugin to favor double-quoted strings. --- .../build/gradle/DetectSplitPackagesPlugin.groovy | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy index 8b73878694..ddafa956ef 100644 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/DetectSplitPackagesPlugin.groovy @@ -24,6 +24,7 @@ import org.gradle.api.Task import org.gradle.api.tasks.Input import org.gradle.api.tasks.TaskAction + /** * Gradle plugin that detects identically named, non-empty packages split across multiple * subprojects, e.g. "org.springframework.context.annotation" existing in both spring-core @@ -48,9 +49,9 @@ import org.gradle.api.tasks.TaskAction public class DetectSplitPackagesPlugin implements Plugin { public void apply(Project project) { def tasks = project.tasks - Task detectSplitPackages = tasks.add('detectSplitPackages', DetectSplitPackagesTask.class) - if (tasks.asMap.containsKey('check')) { - tasks.getByName('check').dependsOn detectSplitPackages + Task detectSplitPackages = tasks.add("detectSplitPackages", DetectSplitPackagesTask.class) + if (tasks.asMap.containsKey("check")) { + tasks.getByName("check").dependsOn detectSplitPackages } } } @@ -65,8 +66,8 @@ public class DetectSplitPackagesTask extends DefaultTask { Set projectsToScan = project.subprojects public DetectSplitPackagesTask() { - this.group = 'Verification' - this.description = 'Detects packages split across two or more subprojects.' + this.group = "Verification" + this.description = "Detects packages split across two or more subprojects." } @TaskAction From 5b147bfba8d5d5837b96357a52867e433137f64b Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 11 Jan 2013 21:31:46 +0100 Subject: [PATCH 050/311] Improve speed of spring-test build - Now excluding *TestSuite classes from the JUnit test task. - Renamed SpringJUnit4SuiteTests to SpringJUnit4TestSuite so that it is no longer executed in the build. - Reduced sleep time in various timing related tests. --- build.gradle | 2 +- .../context/ClassLevelDirtiesContextTests.java | 8 +++++++- .../context/junit4/RepeatedSpringRunnerTests.java | 14 +++++++------- ...4SuiteTests.java => SpringJUnit4TestSuite.java} | 11 ++++++----- .../context/junit4/TimedSpringRunnerTests.java | 8 ++++---- 5 files changed, 25 insertions(+), 18 deletions(-) rename spring-test/src/test/java/org/springframework/test/context/junit4/{SpringJUnit4SuiteTests.java => SpringJUnit4TestSuite.java} (95%) diff --git a/build.gradle b/build.gradle index 09a4ff20a8..d3b51341d9 100644 --- a/build.gradle +++ b/build.gradle @@ -655,7 +655,7 @@ project("spring-test") { dependsOn testNG useJUnit() // "TestCase" classes are run by other test classes, not the build. - exclude "**/*TestCase.class" + exclude(["**/*TestCase.class", "**/*TestSuite.class"]) } dependencies { diff --git a/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java index 3768b03cb6..bcfe0d3828 100644 --- a/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java @@ -29,6 +29,7 @@ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -179,9 +180,14 @@ public class ClassLevelDirtiesContextTests { @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners( { DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) - @ContextConfiguration("/org/springframework/test/context/junit4/SpringJUnit4ClassRunnerAppCtxTests-context.xml") + @ContextConfiguration public static abstract class BaseTestCase { + @Configuration + static class Config { + /* no beans */ + } + @Autowired protected ApplicationContext applicationContext; diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java index 49d5ad5e7a..7f6a937ce3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java @@ -156,34 +156,34 @@ public class RepeatedSpringRunnerTests { public static final class TimedRepeatedTestCase extends AbstractRepeatedTestCase { @Test - @Timed(millis = 10000) + @Timed(millis = 1000) @Repeat(5) public void repeatedFiveTimesButDoesNotExceedTimeout() throws Exception { incrementInvocationCount(); } @Test - @Timed(millis = 100) + @Timed(millis = 10) @Repeat(1) public void singleRepetitionExceedsTimeout() throws Exception { incrementInvocationCount(); - Thread.sleep(250); + Thread.sleep(15); } @Test - @Timed(millis = 200) + @Timed(millis = 20) @Repeat(4) public void firstRepetitionOfManyExceedsTimeout() throws Exception { incrementInvocationCount(); - Thread.sleep(250); + Thread.sleep(25); } @Test - @Timed(millis = 1000) + @Timed(millis = 100) @Repeat(10) public void collectiveRepetitionsExceedTimeout() throws Exception { incrementInvocationCount(); - Thread.sleep(150); + Thread.sleep(11); } } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4TestSuite.java similarity index 95% rename from spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java rename to spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4TestSuite.java index 2f293d8847..72ddd1b8c4 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4SuiteTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/SpringJUnit4TestSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -42,15 +42,16 @@ import org.springframework.test.context.junit4.profile.xml.DevProfileXmlConfigTe /** * JUnit test suite for tests involving {@link SpringJUnit4ClassRunner} and the - * Spring TestContext Framework. + * Spring TestContext Framework; only intended to be run manually as a + * convenience. * *

This test suite serves a dual purpose of verifying that tests run with * {@link SpringJUnit4ClassRunner} can be used in conjunction with JUnit's * {@link Suite} runner. * *

Note that tests included in this suite will be executed at least twice if - * run from an automated build process, test runner, etc. that is configured to - * run tests based on a "*Tests.class" pattern match. + * run from an automated build process, test runner, etc. that is not configured + * to exclude tests based on a "*TestSuite.class" pattern match. * * @author Sam Brannen * @since 2.5 @@ -104,6 +105,6 @@ StandardJUnit4FeaturesTests.class,// TimedTransactionalSpringRunnerTests.class,// HibernateSessionFlushingTests.class // }) -public class SpringJUnit4SuiteTests { +public class SpringJUnit4TestSuite { /* this test case consists entirely of tests loaded as a suite. */ } diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java index a3679ba75e..db8690072e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java @@ -76,16 +76,16 @@ public class TimedSpringRunnerTests { } // Should Fail due to timeout. - @Test(timeout = 200) + @Test(timeout = 10) public void testJUnitTimeoutWithOneSecondWait() throws Exception { - Thread.sleep(1000); + Thread.sleep(20); } // Should Fail due to timeout. @Test - @Timed(millis = 200) + @Timed(millis = 10) public void testSpringTimeoutWithOneSecondWait() throws Exception { - Thread.sleep(1000); + Thread.sleep(20); } // Should Fail due to duplicate configuration. From 2db7a1228836ff7b39047fe137fe43a915f35e94 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 11 Jan 2013 12:31:16 -0800 Subject: [PATCH 051/311] Generate eclipse project settings from gradle Update gradle to generate the following project specific eclipse settings: - Java formatting - Cleanup options - Warning settings - Code template with copyright header - WTP module meta-data In addition this commit changes the eclipse project .classpath file to output test and main classes to different folders. This is required to prevent eclipse WTP from packaging test classes into /WEB-INF/lib jar files. Issue: SPR-9518 --- build.gradle | 2 - gradle/ide.gradle | 50 ++- src/eclipse/org.eclipse.jdt.core.prefs | 388 ++++++++++++++++++ src/eclipse/org.eclipse.jdt.ui.prefs | 62 +++ src/eclipse/org.eclipse.wst.common.component | 6 + ....eclipse.wst.common.project.facet.core.xml | 7 + 6 files changed, 512 insertions(+), 3 deletions(-) create mode 100644 src/eclipse/org.eclipse.jdt.core.prefs create mode 100644 src/eclipse/org.eclipse.jdt.ui.prefs create mode 100644 src/eclipse/org.eclipse.wst.common.component create mode 100644 src/eclipse/org.eclipse.wst.common.project.facet.core.xml diff --git a/build.gradle b/build.gradle index d3b51341d9..228f10b07c 100644 --- a/build.gradle +++ b/build.gradle @@ -21,8 +21,6 @@ configure(allprojects) { project -> apply plugin: "propdeps" apply plugin: "java" - apply plugin: "propdeps-eclipse" - apply plugin: "propdeps-idea" apply plugin: "test-source-set-dependencies" apply from: "${gradleScriptDir}/ide.gradle" diff --git a/gradle/ide.gradle b/gradle/ide.gradle index e1bb117641..d0071ebaa3 100644 --- a/gradle/ide.gradle +++ b/gradle/ide.gradle @@ -1,7 +1,12 @@ import org.gradle.plugins.ide.eclipse.model.ProjectDependency +import org.gradle.plugins.ide.eclipse.model.SourceFolder + +apply plugin: "propdeps-eclipse" +apply plugin: "propdeps-idea" + +// Replace classpath entries with project dependencies (GRADLE-1116) eclipse.classpath.file.whenMerged { classpath -> - // GRADLE-1116 def regexp = /.*?\/([^\/]+)\/build\/[^\/]+\/(?:main|test)/ // only match those that end in main or test (avoids removing necessary entries like build/classes/jaxb) def projectOutputDependencies = classpath.entries.findAll { entry -> entry.path =~ regexp } projectOutputDependencies.each { entry -> @@ -19,3 +24,46 @@ eclipse.classpath.file.whenMerged { classpath -> } classpath.entries.removeAll { entry -> (entry.path =~ /(?!.*?repack.*\.jar).*?\/([^\/]+)\/build\/libs\/[^\/]+\.jar/) } } + + +// Use separate main/test outputs (prevents WTP from packaging test classes) +eclipse.classpath.defaultOutputDir = file(project.name+"/eclipse/bin") +eclipse.classpath.file.whenMerged { classpath -> + classpath.entries.findAll{ it instanceof SourceFolder }.each { + it.output = "build/eclipse/" + it.path.split("/")[1] + } +} + +// Allow projects to be used as WPT modules +eclipse.project.natures "org.eclipse.wst.common.project.facet.core.nature" + + +// Include project specific settings +task eclipseSettings(type: Copy) { + from rootProject.files( + "src/eclipse/org.eclipse.jdt.ui.prefs", + "src/eclipse/org.eclipse.wst.common.project.facet.core.xml") + into project.file('.settings/') +} + +task eclipseWstComponent(type: Copy) { + from rootProject.files( + "src/eclipse/org.eclipse.wst.common.component") + into project.file('.settings/') + expand(deployname: project.name) +} + +task eclipseJdtPrepare(type: Copy) { + from rootProject.file("src/eclipse/org.eclipse.jdt.core.prefs") + into project.file(".settings/") +} + +task cleanEclipseJdtUi(type: Delete) { + delete project.file(".settings/org.eclipse.jdt.ui.prefs"); + delete project.file(".settings/org.eclipse.wst.common.component"); + delete project.file(".settings/org.eclipse.wst.common.project.facet.core.xml"); +} + +tasks["eclipseJdt"].dependsOn(eclipseJdtPrepare) +tasks["cleanEclipse"].dependsOn(cleanEclipseJdtUi) +tasks["eclipse"].dependsOn(eclipseSettings, eclipseWstComponent) diff --git a/src/eclipse/org.eclipse.jdt.core.prefs b/src/eclipse/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..d6f23343f5 --- /dev/null +++ b/src/eclipse/org.eclipse.jdt.core.prefs @@ -0,0 +1,388 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/main/resources=UTF-8 +encoding//src/test/java=UTF-8 +encoding//src/test/resources=UTF-8 +org.eclipse.jdt.core.codeComplete.argumentPrefixes= +org.eclipse.jdt.core.codeComplete.argumentSuffixes= +org.eclipse.jdt.core.codeComplete.fieldPrefixes= +org.eclipse.jdt.core.codeComplete.fieldSuffixes= +org.eclipse.jdt.core.codeComplete.localPrefixes= +org.eclipse.jdt.core.codeComplete.localSuffixes= +org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= +org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.doc.comment.support=enabled +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=error +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning +org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=protected +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=return_tag +org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled +org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullReference=ignore +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.source=1.7 +org.eclipse.jdt.core.formatter.align_type_members_on_columns=false +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation=0 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant=80 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation=16 +org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_assignment=0 +org.eclipse.jdt.core.formatter.alignment_for_binary_expression=16 +org.eclipse.jdt.core.formatter.alignment_for_compact_if=16 +org.eclipse.jdt.core.formatter.alignment_for_conditional_expression=80 +org.eclipse.jdt.core.formatter.alignment_for_enum_constants=0 +org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer=16 +org.eclipse.jdt.core.formatter.alignment_for_method_declaration=0 +org.eclipse.jdt.core.formatter.alignment_for_multiple_fields=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_resources_in_try=80 +org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation=0 +org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration=16 +org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch=16 +org.eclipse.jdt.core.formatter.blank_lines_after_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_after_package=1 +org.eclipse.jdt.core.formatter.blank_lines_before_field=1 +org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration=1 +org.eclipse.jdt.core.formatter.blank_lines_before_imports=1 +org.eclipse.jdt.core.formatter.blank_lines_before_member_type=1 +org.eclipse.jdt.core.formatter.blank_lines_before_method=1 +org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk=1 +org.eclipse.jdt.core.formatter.blank_lines_before_package=1 +org.eclipse.jdt.core.formatter.blank_lines_between_import_groups=1 +org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations=1 +org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_array_initializer=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_block_in_case=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_constant=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_method_declaration=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_switch=end_of_line +org.eclipse.jdt.core.formatter.brace_position_for_type_declaration=end_of_line +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment=false +org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment=false +org.eclipse.jdt.core.formatter.comment.format_block_comments=true +org.eclipse.jdt.core.formatter.comment.format_header=false +org.eclipse.jdt.core.formatter.comment.format_html=true +org.eclipse.jdt.core.formatter.comment.format_javadoc_comments=true +org.eclipse.jdt.core.formatter.comment.format_line_comments=true +org.eclipse.jdt.core.formatter.comment.format_source_code=true +org.eclipse.jdt.core.formatter.comment.indent_parameter_description=false +org.eclipse.jdt.core.formatter.comment.indent_root_tags=true +org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags=insert +org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter=do not insert +org.eclipse.jdt.core.formatter.comment.line_length=90 +org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries=true +org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries=true +org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments=false +org.eclipse.jdt.core.formatter.compact_else_if=true +org.eclipse.jdt.core.formatter.continuation_indentation=2 +org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer=1 +org.eclipse.jdt.core.formatter.disabling_tag=@formatter\:off +org.eclipse.jdt.core.formatter.enabling_tag=@formatter\:on +org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line=false +org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header=true +org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header=true +org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_empty_lines=false +org.eclipse.jdt.core.formatter.indent_statements_compare_to_block=true +org.eclipse.jdt.core.formatter.indent_statements_compare_to_body=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases=true +org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch=true +org.eclipse.jdt.core.formatter.indentation.size=4 +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type=insert +org.eclipse.jdt.core.formatter.insert_new_line_after_label=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body=insert +org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments=insert +org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters=insert +org.eclipse.jdt.core.formatter.insert_space_after_ellipsis=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources=insert +org.eclipse.jdt.core.formatter.insert_space_after_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter=insert +org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_binary_operator=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_ellipsis=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try=insert +org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return=insert +org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw=insert +org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional=insert +org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources=do not insert +org.eclipse.jdt.core.formatter.insert_space_before_unary_operator=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration=do not insert +org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation=do not insert +org.eclipse.jdt.core.formatter.join_lines_in_comments=true +org.eclipse.jdt.core.formatter.join_wrapped_lines=true +org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line=false +org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line=false +org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line=false +org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line=false +org.eclipse.jdt.core.formatter.lineSplit=90 +org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column=false +org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column=false +org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body=0 +org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve=1 +org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line=true +org.eclipse.jdt.core.formatter.tabulation.char=tab +org.eclipse.jdt.core.formatter.tabulation.size=4 +org.eclipse.jdt.core.formatter.use_on_off_tags=false +org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations=false +org.eclipse.jdt.core.formatter.wrap_before_binary_operator=true +org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch=true +org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested=true diff --git a/src/eclipse/org.eclipse.jdt.ui.prefs b/src/eclipse/org.eclipse.jdt.ui.prefs new file mode 100644 index 0000000000..47eb08906b --- /dev/null +++ b/src/eclipse/org.eclipse.jdt.ui.prefs @@ -0,0 +1,62 @@ +cleanup.add_default_serial_version_id=true +cleanup.add_generated_serial_version_id=false +cleanup.add_missing_annotations=false +cleanup.add_missing_deprecated_annotations=true +cleanup.add_missing_methods=false +cleanup.add_missing_nls_tags=false +cleanup.add_missing_override_annotations=true +cleanup.add_missing_override_annotations_interface_methods=true +cleanup.add_serial_version_id=false +cleanup.always_use_blocks=true +cleanup.always_use_parentheses_in_expressions=false +cleanup.always_use_this_for_non_static_field_access=true +cleanup.always_use_this_for_non_static_method_access=false +cleanup.convert_to_enhanced_for_loop=false +cleanup.correct_indentation=false +cleanup.format_source_code=false +cleanup.format_source_code_changes_only=false +cleanup.make_local_variable_final=false +cleanup.make_parameters_final=false +cleanup.make_private_fields_final=true +cleanup.make_type_abstract_if_missing_method=false +cleanup.make_variable_declarations_final=true +cleanup.never_use_blocks=false +cleanup.never_use_parentheses_in_expressions=true +cleanup.organize_imports=false +cleanup.qualify_static_field_accesses_with_declaring_class=false +cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true +cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true +cleanup.qualify_static_member_accesses_with_declaring_class=true +cleanup.qualify_static_method_accesses_with_declaring_class=false +cleanup.remove_private_constructors=true +cleanup.remove_trailing_whitespaces=true +cleanup.remove_trailing_whitespaces_all=true +cleanup.remove_trailing_whitespaces_ignore_empty=false +cleanup.remove_unnecessary_casts=true +cleanup.remove_unnecessary_nls_tags=true +cleanup.remove_unused_imports=true +cleanup.remove_unused_local_variables=false +cleanup.remove_unused_private_fields=true +cleanup.remove_unused_private_members=false +cleanup.remove_unused_private_methods=true +cleanup.remove_unused_private_types=true +cleanup.sort_members=false +cleanup.sort_members_all=false +cleanup.use_blocks=true +cleanup.use_blocks_only_for_return_and_throw=false +cleanup.use_parentheses_in_expressions=false +cleanup.use_this_for_non_static_field_access=true +cleanup.use_this_for_non_static_field_access_only_if_necessary=false +cleanup.use_this_for_non_static_method_access=false +cleanup.use_this_for_non_static_method_access_only_if_necessary=true +cleanup_profile=_Spring +cleanup_settings_version=2 +eclipse.preferences.version=1 +formatter_profile=_Spring +formatter_settings_version=12 +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=java;javax;org;com; +org.eclipse.jdt.ui.javadoc=true +org.eclipse.jdt.ui.ondemandthreshold=9999 +org.eclipse.jdt.ui.staticondemandthreshold=9999 +org.eclipse.jdt.ui.text.custom_code_templates= diff --git a/src/eclipse/org.eclipse.wst.common.component b/src/eclipse/org.eclipse.wst.common.component new file mode 100644 index 0000000000..ce05d97c85 --- /dev/null +++ b/src/eclipse/org.eclipse.wst.common.component @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/eclipse/org.eclipse.wst.common.project.facet.core.xml b/src/eclipse/org.eclipse.wst.common.project.facet.core.xml new file mode 100644 index 0000000000..e4a5a385a2 --- /dev/null +++ b/src/eclipse/org.eclipse.wst.common.project.facet.core.xml @@ -0,0 +1,7 @@ + + + + + + + From f0a1ff2d762d0cc4aac176e1be55d8758f85db0e Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 11 Jan 2013 21:55:57 +0100 Subject: [PATCH 052/311] JDBC parameter binding uses JDBC 3.0 ParameterMetaData (if available) for type determination Forward-ported from 3.1.2, with minor modifications for defensiveness against the JDBC driver. Issue: SPR-10084 --- .../core/PreparedStatementCreatorFactory.java | 14 +++---- .../jdbc/core/StatementCreatorUtils.java | 40 +++++++++++++------ 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java index 7efe962c64..6ba84b72b8 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/PreparedStatementCreatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -146,7 +146,7 @@ public class PreparedStatementCreatorFactory { * Return a new PreparedStatementSetter for the given parameters. * @param params list of parameters (may be {@code null}) */ - public PreparedStatementSetter newPreparedStatementSetter(List params) { + public PreparedStatementSetter newPreparedStatementSetter(List params) { return new PreparedStatementCreatorImpl(params != null ? params : Collections.emptyList()); } @@ -225,7 +225,7 @@ public class PreparedStatementCreatorFactory { } public PreparedStatement createPreparedStatement(Connection con) throws SQLException { - PreparedStatement ps = null; + PreparedStatement ps; if (generatedKeysColumnNames != null || returnGeneratedKeys) { try { if (generatedKeysColumnNames != null) { @@ -235,10 +235,10 @@ public class PreparedStatementCreatorFactory { ps = con.prepareStatement(this.actualSql, PreparedStatement.RETURN_GENERATED_KEYS); } } - catch (AbstractMethodError ex) { + catch (AbstractMethodError err) { throw new InvalidDataAccessResourceUsageException( - "The JDBC driver is not compliant to JDBC 3.0 and thus " + - "does not support retrieval of auto-generated keys", ex); + "Your JDBC driver is not compliant with JDBC 3.0 - " + + "it does not support retrieval of auto-generated keys", err); } } else if (resultSetType == ResultSet.TYPE_FORWARD_ONLY && !updatableResults) { @@ -263,7 +263,7 @@ public class PreparedStatementCreatorFactory { int sqlColIndx = 1; for (int i = 0; i < this.parameters.size(); i++) { Object in = this.parameters.get(i); - SqlParameter declaredParameter = null; + SqlParameter declaredParameter; // SqlParameterValue overrides declared parameter metadata, in particular for // independence from the declared parameter position in case of named parameters. if (in instanceof SqlParameterValue) { diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java index 1e6a263ca4..ea8e74501e 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/StatementCreatorUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import java.math.BigInteger; import java.sql.Blob; import java.sql.Clob; import java.sql.DatabaseMetaData; +import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Types; @@ -189,7 +190,7 @@ public abstract class StatementCreatorUtils { if (inValue instanceof SqlParameterValue) { SqlParameterValue parameterValue = (SqlParameterValue) inValue; if (logger.isDebugEnabled()) { - logger.debug("Overriding typeinfo with runtime info from SqlParameterValue: column index " + paramIndex + + logger.debug("Overriding type info with runtime info from SqlParameterValue: column index " + paramIndex + ", SQL type " + parameterValue.getSqlType() + ", Type name " + parameterValue.getTypeName()); } @@ -228,18 +229,31 @@ public abstract class StatementCreatorUtils { boolean useSetObject = false; sqlType = Types.NULL; try { - DatabaseMetaData dbmd = ps.getConnection().getMetaData(); - String databaseProductName = dbmd.getDatabaseProductName(); - String jdbcDriverName = dbmd.getDriverName(); - if (databaseProductName.startsWith("Informix") || - jdbcDriverName.startsWith("Microsoft SQL Server")) { - useSetObject = true; + ParameterMetaData pmd = null; + try { + pmd = ps.getParameterMetaData(); } - else if (databaseProductName.startsWith("DB2") || - jdbcDriverName.startsWith("jConnect") || - jdbcDriverName.startsWith("SQLServer")|| - jdbcDriverName.startsWith("Apache Derby")) { - sqlType = Types.VARCHAR; + catch (Throwable ex) { + // JDBC driver not compliant with JDBC 3.0 + // -> proceed with database-specific checks + } + if (pmd != null) { + sqlType = pmd.getParameterType(paramIndex); + } + else { + DatabaseMetaData dbmd = ps.getConnection().getMetaData(); + String databaseProductName = dbmd.getDatabaseProductName(); + String jdbcDriverName = dbmd.getDriverName(); + if (databaseProductName.startsWith("Informix") || + jdbcDriverName.startsWith("Microsoft SQL Server")) { + useSetObject = true; + } + else if (databaseProductName.startsWith("DB2") || + jdbcDriverName.startsWith("jConnect") || + jdbcDriverName.startsWith("SQLServer")|| + jdbcDriverName.startsWith("Apache Derby")) { + sqlType = Types.VARCHAR; + } } } catch (Throwable ex) { From 54c873b4c430a6c13698080fcde99835ca2a541b Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 11 Jan 2013 16:25:47 -0500 Subject: [PATCH 053/311] Support multiple Validators in DataBinder DataBinder now allows registering additional Validator instances. This may be useful when adding a Spring Validator to a globally registered JSR-303 LocalValidatorFactoryBean. Issue: SPR-9436 --- .../validation/DataBinder.java | 76 +++++++++++++++---- 1 file changed, 60 insertions(+), 16 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/validation/DataBinder.java b/spring-context/src/main/java/org/springframework/validation/DataBinder.java index a9d5d83587..35e0ea4a56 100644 --- a/spring-context/src/main/java/org/springframework/validation/DataBinder.java +++ b/spring-context/src/main/java/org/springframework/validation/DataBinder.java @@ -18,7 +18,11 @@ package org.springframework.validation; import java.beans.PropertyEditor; import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; @@ -141,7 +145,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter { private BindingErrorProcessor bindingErrorProcessor = new DefaultBindingErrorProcessor(); - private Validator validator; + private final List validators = new ArrayList(); private ConversionService conversionService; @@ -493,21 +497,58 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** * Set the Validator to apply after each binding step. + * @see #addValidators(Validator...) + * @see #replaceValidators(Validator...) */ public void setValidator(Validator validator) { - if (validator != null && (getTarget() != null && !validator.supports(getTarget().getClass()))) { - throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + getTarget()); + assertValidators(validator); + this.validators.clear(); + this.validators.add(validator); + } + + private void assertValidators(Validator... validators) { + Assert.notNull(validators, "Validators required"); + for (Validator validator : validators) { + if (validator != null && (getTarget() != null && !validator.supports(getTarget().getClass()))) { + throw new IllegalStateException("Invalid target for Validator [" + validator + "]: " + getTarget()); + } } - this.validator = validator; } /** - * Return the Validator to apply after each binding step, if any. + * Add Validators to apply after each binding step. + * @see #setValidator(Validator) + * @see #replaceValidators(Validator...) */ - public Validator getValidator() { - return this.validator; + public void addValidators(Validator... validators) { + assertValidators(validators); + this.validators.addAll(Arrays.asList(validators)); } + /** + * Replace the Validators to apply after each binding step. + * @see #setValidator(Validator) + * @see #addValidators(Validator...) + */ + public void replaceValidators(Validator... validators) { + assertValidators(validators); + this.validators.clear(); + this.validators.addAll(Arrays.asList(validators)); + } + + /** + * Return the primary Validator to apply after each binding step, if any. + */ + public Validator getValidator() { + return this.validators.size() > 0 ? this.validators.get(0) : null; + } + + /** + * Return the Validators to apply after data binding. + */ + public List getValidators() { + return Collections.unmodifiableList(this.validators); + } //--------------------------------------------------------------------- // Implementation of PropertyEditorRegistry/TypeConverter interface @@ -708,28 +749,31 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter { /** - * Invoke the specified Validator, if any. + * Invoke the specified Validators, if any. * @see #setValidator(Validator) * @see #getBindingResult() */ public void validate() { - this.validator.validate(getTarget(), getBindingResult()); + for (Validator validator : this.validators) { + validator.validate(getTarget(), getBindingResult()); + } } /** - * Invoke the specified Validator, if any, with the given validation hints. + * Invoke the specified Validators, if any, with the given validation hints. *

Note: Validation hints may get ignored by the actual target Validator. * @param validationHints one or more hint objects to be passed to a {@link SmartValidator} * @see #setValidator(Validator) * @see SmartValidator#validate(Object, Errors, Object...) */ public void validate(Object... validationHints) { - Validator validator = getValidator(); - if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { - ((SmartValidator) validator).validate(getTarget(), getBindingResult(), validationHints); - } - else if (validator != null) { - validator.validate(getTarget(), getBindingResult()); + for (Validator validator : getValidators()) { + if (!ObjectUtils.isEmpty(validationHints) && validator instanceof SmartValidator) { + ((SmartValidator) validator).validate(getTarget(), getBindingResult(), validationHints); + } + else if (validator != null) { + validator.validate(getTarget(), getBindingResult()); + } } } From 5ddc313beffac6459f027e9c41cfc3597bf184f4 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 11 Jan 2013 14:19:59 -0800 Subject: [PATCH 054/311] Upgrade to prop-deps gradle plugin 0.0.3 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 228f10b07c..d37870c20f 100644 --- a/build.gradle +++ b/build.gradle @@ -3,7 +3,7 @@ buildscript { maven { url "http://repo.springsource.org/plugins-release" } } dependencies { - classpath("org.springframework.build.gradle:propdeps-plugin:0.0.1") + classpath("org.springframework.build.gradle:propdeps-plugin:0.0.3") classpath("org.springframework.build.gradle:docbook-reference-plugin:0.2.4") } } From fce7adc400d4b519da40d361a1b1f62fc58e185a Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 11 Jan 2013 14:55:52 -0800 Subject: [PATCH 055/311] Consider bridge methods in SpEL properties Revert ReflectivePropertyAccessor changes from 107fafb and instead consider all methods when resolving properties. Methods are now sorted such that non-bridge methods are considered before bridge methods. Issue: SPR-10162 --- .../support/ReflectivePropertyAccessor.java | 26 +++++++++++++++---- .../expression/spel/SpelReproTests.java | 23 +++++++++++++++- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java index 97d87d50c3..7b7ce34179 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java @@ -21,6 +21,8 @@ import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Comparator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -310,13 +312,13 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { * Find a getter method for the specified property. */ protected Method findGetterForProperty(String propertyName, Class clazz, boolean mustBeStatic) { - Method[] ms = clazz.getMethods(); + Method[] ms = getSortedClassMethods(clazz); String propertyMethodSuffix = getPropertyMethodSuffix(propertyName); // Try "get*" method... String getterName = "get" + propertyMethodSuffix; for (Method method : ms) { - if (!method.isBridge() && method.getName().equals(getterName) && method.getParameterTypes().length == 0 && + if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 && (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) { return method; } @@ -324,7 +326,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { // Try "is*" method... getterName = "is" + propertyMethodSuffix; for (Method method : ms) { - if (!method.isBridge() && method.getName().equals(getterName) && method.getParameterTypes().length == 0 && + if (method.getName().equals(getterName) && method.getParameterTypes().length == 0 && (boolean.class.equals(method.getReturnType()) || Boolean.class.equals(method.getReturnType())) && (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) { return method; @@ -337,10 +339,10 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { * Find a setter method for the specified property. */ protected Method findSetterForProperty(String propertyName, Class clazz, boolean mustBeStatic) { - Method[] methods = clazz.getMethods(); + Method[] methods = getSortedClassMethods(clazz); String setterName = "set" + getPropertyMethodSuffix(propertyName); for (Method method : methods) { - if (!method.isBridge() && method.getName().equals(setterName) && method.getParameterTypes().length == 1 && + if (method.getName().equals(setterName) && method.getParameterTypes().length == 1 && (!mustBeStatic || Modifier.isStatic(method.getModifiers()))) { return method; } @@ -348,6 +350,20 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { return null; } + /** + * Returns class methods ordered with non bridge methods appearing higher. + */ + private Method[] getSortedClassMethods(Class clazz) { + Method[] methods = clazz.getMethods(); + Arrays.sort(methods, new Comparator() { + @Override + public int compare(Method o1, Method o2) { + return (o1.isBridge() == o2.isBridge()) ? 0 : (o1.isBridge() ? 1 : -1); + } + }); + return methods; + } + protected String getPropertyMethodSuffix(String propertyName) { if (propertyName.length() > 1 && Character.isUpperCase(propertyName.charAt(1))) { return propertyName; diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index e1122ab04f..9cb0a58253 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,6 +56,7 @@ import static org.junit.Assert.*; * @author Andy Clement * @author Juergen Hoeller * @author Clark Duplichien + * @author Phillip Webb */ public class SpelReproTests extends ExpressionTestCase { @@ -1656,6 +1657,15 @@ public class SpelReproTests extends ExpressionTestCase { assertEquals(Integer.class, value.getTypeDescriptor().getType()); } + @Test + public void SPR_10162_onlyBridgeMethodTest() throws Exception { + ReflectivePropertyAccessor accessor = new ReflectivePropertyAccessor(); + StandardEvaluationContext context = new StandardEvaluationContext(); + Object target = new OnlyBridgeMethod(); + TypedValue value = accessor.read(context, target , "property"); + assertEquals(Integer.class, value.getTypeDescriptor().getType()); + } + @Test public void SPR_10091_simpleTestValueType() { ExpressionParser parser = new SpelExpressionParser(); @@ -1722,4 +1732,15 @@ public class SpelReproTests extends ExpressionTestCase { } } + static class PackagePrivateClassWithGetter { + + public Integer getProperty() { + return null; + } + } + + public static class OnlyBridgeMethod extends PackagePrivateClassWithGetter { + + } + } From e8fcde09abc958436ddd7a15d7e708080de72cfd Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 11 Jan 2013 15:12:59 -0800 Subject: [PATCH 056/311] Polish author and copyright year --- .../expression/spel/support/ReflectivePropertyAccessor.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java index 7b7ce34179..ffe188bae8 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,6 +44,7 @@ import org.springframework.util.StringUtils; * * @author Andy Clement * @author Juergen Hoeller + * @author Phillip Webb * @since 3.0 */ public class ReflectivePropertyAccessor implements PropertyAccessor { From e4c1361c60450c7aef16e28ee6db80e96c4965ef Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 11 Jan 2013 15:25:12 -0800 Subject: [PATCH 057/311] Remove accidentally committed interface @Override --- .../expression/spel/support/ReflectivePropertyAccessor.java | 1 - 1 file changed, 1 deletion(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java index ffe188bae8..015c02fd52 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java @@ -357,7 +357,6 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { private Method[] getSortedClassMethods(Class clazz) { Method[] methods = clazz.getMethods(); Arrays.sort(methods, new Comparator() { - @Override public int compare(Method o1, Method o2) { return (o1.isBridge() == o2.isBridge()) ? 0 : (o1.isBridge() ? 1 : -1); } From 8a37521a3cd5dc0d51599abf9824c35513816fbb Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 14 Jan 2013 11:40:21 +0100 Subject: [PATCH 058/311] Fix copyright year & method names in spring-test This commit fixes the copyright year for changes made in commit 5b147bfba8d5d5837b96357a52867e433137f64b. In addition, method names have been changed to reflect the semantic changes made in that same commit. --- .../test/context/ClassLevelDirtiesContextTests.java | 4 ++-- .../context/junit4/RepeatedSpringRunnerTests.java | 2 +- .../test/context/junit4/TimedSpringRunnerTests.java | 12 ++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java b/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java index bcfe0d3828..0be28a871e 100644 --- a/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/ClassLevelDirtiesContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,7 +38,7 @@ import org.springframework.test.context.support.DependencyInjectionTestExecution import org.springframework.test.context.support.DirtiesContextTestExecutionListener; /** - * JUnit 4 based integration test which verifies correct {@link ContextCache + * JUnit 4 based integration test which verifies correct {@linkplain ContextCache * application context caching} in conjunction with the * {@link SpringJUnit4ClassRunner} and the {@link DirtiesContext * @DirtiesContext} annotation at the class level. diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java index 7f6a937ce3..6b7241261b 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/RepeatedSpringRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java index db8690072e..446bbb95d3 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,34 +64,34 @@ public class TimedSpringRunnerTests { // Should Pass. @Test(timeout = 2000) - public void testJUnitTimeoutWithNoOp() { + public void jUnitTimeoutWithNoOp() { /* no-op */ } // Should Pass. @Test @Timed(millis = 2000) - public void testSpringTimeoutWithNoOp() { + public void springTimeoutWithNoOp() { /* no-op */ } // Should Fail due to timeout. @Test(timeout = 10) - public void testJUnitTimeoutWithOneSecondWait() throws Exception { + public void jUnitTimeoutWithSleep() throws Exception { Thread.sleep(20); } // Should Fail due to timeout. @Test @Timed(millis = 10) - public void testSpringTimeoutWithOneSecondWait() throws Exception { + public void springTimeoutWithSleep() throws Exception { Thread.sleep(20); } // Should Fail due to duplicate configuration. @Test(timeout = 200) @Timed(millis = 200) - public void testSpringAndJUnitTimeout() { + public void springAndJUnitTimeouts() { /* no-op */ } } From 8694a0aac06388332373765a3cf0a494b0243a90 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Mon, 14 Jan 2013 12:24:12 +0100 Subject: [PATCH 059/311] Minor changes to AnnotationUtils - Polished Javadoc for isAnnotationDeclaredLocally() and isAnnotationInherited(). - Removed unnecessary call to Arrays.asList() in isAnnotationDeclaredLocally(). --- .../core/annotation/AnnotationUtils.java | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java index e3dce1b2b4..a1701c9db1 100644 --- a/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java +++ b/spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.core.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; -import java.util.Arrays; + import java.util.Map; import java.util.WeakHashMap; @@ -255,8 +255,9 @@ public abstract class AnnotationUtils { * declared locally on the supplied {@code clazz}. The supplied {@link Class} * may represent any type. *

Note: This method does not determine if the annotation is - * {@link java.lang.annotation.Inherited inherited}. For greater clarity regarding inherited - * annotations, consider using {@link #isAnnotationInherited(Class, Class)} instead. + * {@linkplain java.lang.annotation.Inherited inherited}. For greater clarity + * regarding inherited annotations, consider using + * {@link #isAnnotationInherited(Class, Class)} instead. * @param annotationType the Class object corresponding to the annotation type * @param clazz the Class object corresponding to the class on which to check for the annotation * @return {@code true} if an annotation for the specified {@code annotationType} @@ -268,7 +269,7 @@ public abstract class AnnotationUtils { Assert.notNull(annotationType, "Annotation type must not be null"); Assert.notNull(clazz, "Class must not be null"); boolean declaredLocally = false; - for (Annotation annotation : Arrays.asList(clazz.getDeclaredAnnotations())) { + for (Annotation annotation : clazz.getDeclaredAnnotations()) { if (annotation.annotationType().equals(annotationType)) { declaredLocally = true; break; @@ -279,16 +280,16 @@ public abstract class AnnotationUtils { /** * Determine whether an annotation for the specified {@code annotationType} is present - * on the supplied {@code clazz} and is {@link java.lang.annotation.Inherited inherited} - * i.e., not declared locally for the class). + * on the supplied {@code clazz} and is {@linkplain java.lang.annotation.Inherited inherited} + * (i.e., not declared locally for the class). *

If the supplied {@code clazz} is an interface, only the interface itself will be checked. * In accordance with standard meta-annotation semantics, the inheritance hierarchy for interfaces - * will not be traversed. See the {@link java.lang.annotation.Inherited JavaDoc} for the - * @Inherited meta-annotation for further details regarding annotation inheritance. + * will not be traversed. See the {@linkplain java.lang.annotation.Inherited Javadoc} for the + * {@code @Inherited} meta-annotation for further details regarding annotation inheritance. * @param annotationType the Class object corresponding to the annotation type * @param clazz the Class object corresponding to the class on which to check for the annotation * @return {@code true} if an annotation for the specified {@code annotationType} is present - * on the supplied {@code clazz} and is {@link java.lang.annotation.Inherited inherited} + * on the supplied {@code clazz} and is inherited * @see Class#isAnnotationPresent(Class) * @see #isAnnotationDeclaredLocally(Class, Class) */ From f57c24cd8c84f0456766c4efc30916affc5d39a5 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 14 Jan 2013 10:25:33 -0800 Subject: [PATCH 060/311] Allow 'gradle eclipse' without 'cleanEclipse' Allow eclipse projects to be regenerated without first requiring the 'gradle cleanEclipse' task to be executed. --- gradle/ide.gradle | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/gradle/ide.gradle b/gradle/ide.gradle index d0071ebaa3..05b62dfb09 100644 --- a/gradle/ide.gradle +++ b/gradle/ide.gradle @@ -28,6 +28,13 @@ eclipse.classpath.file.whenMerged { classpath -> // Use separate main/test outputs (prevents WTP from packaging test classes) eclipse.classpath.defaultOutputDir = file(project.name+"/eclipse/bin") +eclipse.classpath.file.beforeMerged { classpath -> + classpath.entries.findAll{ it instanceof SourceFolder }.each { + if(it.output.startsWith("build/eclipse")) { + it.output = null + } + } +} eclipse.classpath.file.whenMerged { classpath -> classpath.entries.findAll{ it instanceof SourceFolder }.each { it.output = "build/eclipse/" + it.path.split("/")[1] From 8bb67149a79d20c649902eb0984b766141d94581 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 14 Jan 2013 11:42:12 -0800 Subject: [PATCH 061/311] Fix eclipse .settings generation Fix issues where gradle would not regenerate .settings files due to the task being considered UP-TO-DATE. --- gradle/ide.gradle | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/gradle/ide.gradle b/gradle/ide.gradle index 05b62dfb09..af43e6bc9d 100644 --- a/gradle/ide.gradle +++ b/gradle/ide.gradle @@ -51,6 +51,7 @@ task eclipseSettings(type: Copy) { "src/eclipse/org.eclipse.jdt.ui.prefs", "src/eclipse/org.eclipse.wst.common.project.facet.core.xml") into project.file('.settings/') + outputs.upToDateWhen { false } } task eclipseWstComponent(type: Copy) { @@ -58,17 +59,20 @@ task eclipseWstComponent(type: Copy) { "src/eclipse/org.eclipse.wst.common.component") into project.file('.settings/') expand(deployname: project.name) + outputs.upToDateWhen { false } } task eclipseJdtPrepare(type: Copy) { from rootProject.file("src/eclipse/org.eclipse.jdt.core.prefs") into project.file(".settings/") + outputs.upToDateWhen { false } } task cleanEclipseJdtUi(type: Delete) { - delete project.file(".settings/org.eclipse.jdt.ui.prefs"); - delete project.file(".settings/org.eclipse.wst.common.component"); - delete project.file(".settings/org.eclipse.wst.common.project.facet.core.xml"); + delete project.file(".settings/org.eclipse.jdt.ui.prefs") + delete project.file("org.eclipse.jdt.core.prefs") + delete project.file(".settings/org.eclipse.wst.common.component") + delete project.file(".settings/org.eclipse.wst.common.project.facet.core.xml") } tasks["eclipseJdt"].dependsOn(eclipseJdtPrepare) From d40bd8bd192bbbc6d9e9bf1dbabfae4a48d9f4d1 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 14 Jan 2013 11:43:58 -0800 Subject: [PATCH 062/311] Tweak eclipse warning settings Hide raw-type, generic and resource leak warnings. --- src/eclipse/org.eclipse.jdt.core.prefs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/eclipse/org.eclipse.jdt.core.prefs b/src/eclipse/org.eclipse.jdt.core.prefs index d6f23343f5..2286420ffe 100644 --- a/src/eclipse/org.eclipse.jdt.core.prefs +++ b/src/eclipse/org.eclipse.jdt.core.prefs @@ -11,6 +11,11 @@ org.eclipse.jdt.core.codeComplete.localPrefixes= org.eclipse.jdt.core.codeComplete.localSuffixes= org.eclipse.jdt.core.codeComplete.staticFieldPrefixes= org.eclipse.jdt.core.codeComplete.staticFieldSuffixes= +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve @@ -30,6 +35,7 @@ org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod= org.eclipse.jdt.core.compiler.problem.discouragedReference=warning org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore @@ -45,10 +51,12 @@ org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=protected +org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=default org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled @@ -65,12 +73,17 @@ org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignor org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error org.eclipse.jdt.core.compiler.problem.nullReference=ignore +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore -org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=ignore +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore @@ -84,6 +97,7 @@ org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore From bff36fb1456ff498354960a725f63f9116ee5b74 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 14 Jan 2013 14:07:26 -0800 Subject: [PATCH 063/311] Improve exceptions for multi-operand expressions Fix SpEL expression parser and tokenizer to provide better exceptions when dealing with operations that expect two operands. For example, prior to this commit the expression '/foo' would throw a NPE due to missing operands to the left of '/'. Issue: SPR-10146 --- .../expression/spel/SpelMessage.java | 5 +-- .../InternalSpelExpressionParser.java | 26 +++++++++++----- .../expression/spel/standard/Tokenizer.java | 17 +++++++--- .../expression/spel/SpelReproTests.java | 31 +++++++++++++++++-- 4 files changed, 62 insertions(+), 17 deletions(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java b/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java index a7f457e147..d9ae1a2efb 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,7 +108,8 @@ public enum SpelMessage { OPERAND_NOT_INCREMENTABLE(Kind.ERROR,1066,"the expression component ''{0}'' does not support increment"), // OPERAND_NOT_DECREMENTABLE(Kind.ERROR,1067,"the expression component ''{0}'' does not support decrement"), // NOT_ASSIGNABLE(Kind.ERROR,1068,"the expression component ''{0}'' is not assignable"), // - ; + MISSING_CHARACTER(Kind.ERROR,1069,"missing expected character ''{0}''"), + LEFT_OPERAND_PROBLEM(Kind.ERROR,1070, "Problem parsing left operand"); private Kind kind; private int code; diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java index be8e988157..c243b5d7f4 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,6 +37,7 @@ import org.springframework.util.StringUtils; * Hand written SpEL parser. Instances are reusable but are not thread safe. * * @author Andy Clement + * @author Phillip Webb * @since 3.0 */ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { @@ -104,8 +105,8 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { Token t = peekToken(); if (t.kind==TokenKind.ASSIGN) { // a=b if (expr==null) { - expr = new NullLiteral(toPos(t.startpos-1,t.endpos-1)); - } + expr = new NullLiteral(toPos(t.startpos-1,t.endpos-1)); + } nextToken(); SpelNodeImpl assignedValue = eatLogicalOrExpression(); return new Assign(toPos(t),expr,assignedValue); @@ -139,7 +140,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { while (peekIdentifierToken("or") || peekToken(TokenKind.SYMBOLIC_OR)) { Token t = nextToken(); //consume OR SpelNodeImpl rhExpr = eatLogicalAndExpression(); - checkRightOperand(t,rhExpr); + checkOperands(t,expr,rhExpr); expr = new OpOr(toPos(t),expr,rhExpr); } return expr; @@ -151,7 +152,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { while (peekIdentifierToken("and") || peekToken(TokenKind.SYMBOLIC_AND)) { Token t = nextToken();// consume 'AND' SpelNodeImpl rhExpr = eatRelationalExpression(); - checkRightOperand(t,rhExpr); + checkOperands(t,expr,rhExpr); expr = new OpAnd(toPos(t),expr,rhExpr); } return expr; @@ -164,7 +165,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { if (relationalOperatorToken != null) { Token t = nextToken(); //consume relational operator token SpelNodeImpl rhExpr = eatSumExpression(); - checkRightOperand(t,rhExpr); + checkOperands(t,expr,rhExpr); TokenKind tk = relationalOperatorToken.kind; if (relationalOperatorToken.isNumericRelationalOperator()) { int pos = toPos(t); @@ -217,7 +218,7 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { while (peekToken(TokenKind.STAR,TokenKind.DIV,TokenKind.MOD)) { Token t = nextToken(); // consume STAR/DIV/MOD SpelNodeImpl rhExpr = eatPowerIncDecExpression(); - checkRightOperand(t,rhExpr); + checkOperands(t,expr,rhExpr); if (t.kind==TokenKind.STAR) { expr = new OpMultiply(toPos(t),expr,rhExpr); } else if (t.kind==TokenKind.DIV) { @@ -836,6 +837,17 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { } } + private void checkOperands(Token token, SpelNodeImpl left, SpelNodeImpl right) { + checkLeftOperand(token, left); + checkRightOperand(token, right); + } + + private void checkLeftOperand(Token token, SpelNodeImpl operandExpression) { + if (operandExpression==null) { + raiseInternalException(token.startpos,SpelMessage.LEFT_OPERAND_PROBLEM); + } + } + private void checkRightOperand(Token token, SpelNodeImpl operandExpression) { if (operandExpression==null) { raiseInternalException(token.startpos,SpelMessage.RIGHT_OPERAND_PROBLEM); diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java index 396c8f17ff..4223a40542 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ import org.springframework.util.Assert; * Lex some input data into a stream of tokens that can then be parsed. * * @author Andy Clement + * @author Phillip Webb * @since 3.0 */ class Tokenizer { @@ -137,14 +138,20 @@ class Tokenizer { } break; case '&': - if (isTwoCharToken(TokenKind.SYMBOLIC_AND)) { - pushPairToken(TokenKind.SYMBOLIC_AND); + if (!isTwoCharToken(TokenKind.SYMBOLIC_AND)) { + throw new InternalParseException(new SpelParseException( + expressionString, pos, + SpelMessage.MISSING_CHARACTER, "&")); } + pushPairToken(TokenKind.SYMBOLIC_AND); break; case '|': - if (isTwoCharToken(TokenKind.SYMBOLIC_OR)) { - pushPairToken(TokenKind.SYMBOLIC_OR); + if (!isTwoCharToken(TokenKind.SYMBOLIC_OR)) { + throw new InternalParseException(new SpelParseException( + expressionString, pos, + SpelMessage.MISSING_CHARACTER, "|")); } + pushPairToken(TokenKind.SYMBOLIC_OR); break; case '?': if (isTwoCharToken(TokenKind.SELECT)) { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 9cb0a58253..01ff05220e 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -16,6 +16,11 @@ package org.springframework.expression.spel; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; @@ -26,8 +31,9 @@ import java.util.Map; import java.util.Properties; import org.junit.Ignore; +import org.junit.Rule; import org.junit.Test; - +import org.junit.rules.ExpectedException; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; import org.springframework.expression.BeanResolver; @@ -48,8 +54,6 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.expression.spel.support.StandardTypeLocator; import org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver; -import static org.junit.Assert.*; - /** * Reproduction tests cornering various SpEL JIRA issues. * @@ -60,6 +64,9 @@ import static org.junit.Assert.*; */ public class SpelReproTests extends ExpressionTestCase { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Test public void testNPE_SPR5661() { evaluate("joinThreeStrings('a',null,'c')", "anullc", String.class); @@ -1694,6 +1701,24 @@ public class SpelReproTests extends ExpressionTestCase { Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext); } + @Test + public void SPR_10146_malformedExpressions() throws Exception { + doTestSpr10146("/foo", "EL1070E:(pos 0): Problem parsing left operand"); + doTestSpr10146("*foo", "EL1070E:(pos 0): Problem parsing left operand"); + doTestSpr10146("%foo", "EL1070E:(pos 0): Problem parsing left operand"); + doTestSpr10146("foo", "EL1070E:(pos 0): Problem parsing left operand"); + doTestSpr10146("&&foo", "EL1070E:(pos 0): Problem parsing left operand"); + doTestSpr10146("||foo", "EL1070E:(pos 0): Problem parsing left operand"); + doTestSpr10146("&foo", "EL1069E:(pos 0): missing expected character '&'"); + doTestSpr10146("|foo", "EL1069E:(pos 0): missing expected character '|'"); + } + + private void doTestSpr10146(String expression, String expectedMessage) { + thrown.expect(SpelParseException.class); + thrown.expectMessage(expectedMessage); + new SpelExpressionParser().parseExpression(expression); + } public static class BooleanHolder { From ad91fa63faa28370c0263e2dada2405a3e48592f Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 14 Jan 2013 15:49:38 -0800 Subject: [PATCH 064/311] SpEL support for static finals on interfaces Update ReflectivePropertyAccessor to search for fields on super classes and implemented interfaces. Although the javadoc Class.getFields() implies that all public fields of class should be returned SpelReproTests demonstrates that this is not always the case. Issue: SPR-10125 --- .../support/ReflectivePropertyAccessor.java | 12 ++++++++++ .../expression/spel/SpelReproTests.java | 23 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java index 015c02fd52..4c31c3f6b2 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java @@ -383,6 +383,18 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { return field; } } + if(clazz.getSuperclass() != null) { + Field field = findField(name, clazz.getSuperclass(), mustBeStatic); + if(field != null) { + return field; + } + } + for (Class implementedInterface : clazz.getInterfaces()) { + Field field = findField(name, implementedInterface, mustBeStatic); + if(field != null) { + return field; + } + } return null; } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 01ff05220e..765422302a 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -16,8 +16,10 @@ package org.springframework.expression.spel; +import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -1720,6 +1722,15 @@ public class SpelReproTests extends ExpressionTestCase { new SpelExpressionParser().parseExpression(expression); } + @Test + public void SPR_10125() throws Exception { + StandardEvaluationContext context = new StandardEvaluationContext(); + String fromInterface = parser.parseExpression("T("+StaticFinalImpl1.class.getName()+").VALUE").getValue(context, String.class); + assertThat(fromInterface, is("interfaceValue")); + String fromClass = parser.parseExpression("T("+StaticFinalImpl2.class.getName()+").VALUE").getValue(context, String.class); + assertThat(fromClass, is("interfaceValue")); + } + public static class BooleanHolder { private Boolean simpleProperty = true; @@ -1768,4 +1779,16 @@ public class SpelReproTests extends ExpressionTestCase { } + public static interface StaticFinal { + public static final String VALUE = "interfaceValue"; + } + + public abstract static class AbstractStaticFinal implements StaticFinal { + } + + public static class StaticFinalImpl1 extends AbstractStaticFinal implements StaticFinal { + } + + public static class StaticFinalImpl2 extends AbstractStaticFinal { + } } From ad025b59c5e933fb7181c76f530e1f4ecc8f7c50 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 14 Jan 2013 18:19:44 -0500 Subject: [PATCH 065/311] Prepend context/servlet path to FormTag action The Form tag now fills in the context and servlet path if not present in the specified action. Issue: SPR-8684 --- .../web/servlet/support/RequestContext.java | 13 +++--- .../web/servlet/tags/form/FormTag.java | 5 +++ .../web/servlet/tags/form/FormTagTests.java | 44 +++++++++++++++++++ 3 files changed, 56 insertions(+), 6 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java index 3f586a9446..cf63a425c3 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java @@ -36,6 +36,7 @@ import org.springframework.ui.context.ThemeSource; import org.springframework.ui.context.support.ResourceBundleThemeSource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; import org.springframework.validation.BindException; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; @@ -422,14 +423,14 @@ public class RequestContext { * context path and the servlet path of the original request. This is useful * for building links to other resources within the application where a * servlet mapping of the style {@code "/main/*"} is used. - *

Delegates to the UrlPathHelper for decoding the context path. - * @see javax.servlet.http.HttpServletRequest#getContextPath - * @see javax.servlet.http.HttpServletRequest#getServletPath() - * @see #getUrlPathHelper + * Delegates to the UrlPathHelper to determine the context and servlet path. */ public String getPathToServlet() { - return this.urlPathHelper.getOriginatingContextPath(this.request) - + this.urlPathHelper.getOriginatingServletPath(this.request); + String path = this.urlPathHelper.getOriginatingContextPath(this.request); + if (StringUtils.hasText(this.urlPathHelper.getPathWithinServletMapping(this.request))) { + path += this.urlPathHelper.getOriginatingServletPath(this.request); + } + return path; } /** diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java index d3b6752ade..120b910727 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java @@ -32,6 +32,7 @@ import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.servlet.support.RequestDataValueProcessor; import org.springframework.web.util.HtmlUtils; +import org.springframework.web.util.UrlPathHelper; /** * Databinding-aware JSP tag for rendering an HTML '{@code form}' whose @@ -411,6 +412,10 @@ public class FormTag extends AbstractHtmlElementTag { protected String resolveAction() throws JspException { String action = getAction(); if (StringUtils.hasText(action)) { + String pathToServlet = getRequestContext().getPathToServlet(); + if (action.startsWith("/") && !action.startsWith(getRequestContext().getContextPath())) { + action = pathToServlet + action; + } action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action)); return processAction(action); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index 23bacd5b94..c3cd6764af 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -166,6 +166,50 @@ public class FormTagTests extends AbstractHtmlElementTagTests { assertAttributeNotPresent(output, "name"); } + public void testPrependServletPath() throws Exception { + + this.request.setContextPath("/myApp"); + this.request.setServletPath("/main"); + this.request.setPathInfo("/index.html"); + + String commandName = "myCommand"; + String action = "/form.html"; + String enctype = "my/enctype"; + String method = "POST"; + String onsubmit = "onsubmit"; + String onreset = "onreset"; + + this.tag.setCommandName(commandName); + this.tag.setAction(action); + this.tag.setMethod(method); + this.tag.setEnctype(enctype); + this.tag.setOnsubmit(onsubmit); + this.tag.setOnreset(onreset); + + int result = this.tag.doStartTag(); + assertEquals(Tag.EVAL_BODY_INCLUDE, result); + assertEquals("Form attribute not exposed", commandName, + getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + + result = this.tag.doEndTag(); + assertEquals(Tag.EVAL_PAGE, result); + + this.tag.doFinally(); + assertNull("Form attribute not cleared after tag ends", + getPageContext().getAttribute(FormTag.MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE)); + + String output = getOutput(); + assertFormTagOpened(output); + assertFormTagClosed(output); + + assertContainsAttribute(output, "action", "/myApp/main/form.html"); + assertContainsAttribute(output, "method", method); + assertContainsAttribute(output, "enctype", enctype); + assertContainsAttribute(output, "onsubmit", onsubmit); + assertContainsAttribute(output, "onreset", onreset); + assertAttributeNotPresent(output, "name"); + } + public void testWithNullResolvedCommand() throws Exception { try { tag.setCommandName("${null}"); From a16bad04f0939f04210f937fbff8fb620951fb90 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 14 Jan 2013 21:04:18 -0500 Subject: [PATCH 066/311] Update Validation chapter The Validation chapter now includes information on combining JSR-303 Bean Validation with additional Spring Validator's that don't require the use of annotations. Issue: SPR-9437 --- src/reference/docbook/validation.xml | 42 ++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/reference/docbook/validation.xml b/src/reference/docbook/validation.xml index 5ad3faeee8..2eb98a76b0 100644 --- a/src/reference/docbook/validation.xml +++ b/src/reference/docbook/validation.xml @@ -12,6 +12,24 @@

Introduction + + JSR-303 Bean Validation + + The Spring Framework supports JSR-303 Bean Validation adapting + it to Spring's Validator interface. + + An application can choose to enable JSR-303 Bean Validation once globally, + as described in , and use it + exclusively for all validation needs. + + An application can also register + additional Spring Validator instances + per DataBinder instance, as described in + . This may be useful for + plugging in validation logic without the use of annotations. + + + There are pros and cons for considering validation as business logic, and Spring offers a design for validation (and data binding) that does not exclude either one of them. Specifically validation should not be tied to @@ -1778,6 +1796,16 @@ binder.validate(); // get BindingResult that includes any validation errors BindingResult results = binder.getBindingResult(); + + A DataBinder can also be configured with multiple + Validator instances + via dataBinder.addValidators + and dataBinder.replaceValidators. + This is useful when combining globally configured JSR-303 Bean Validation + with a Spring Validator configured + locally on a DataBinder instance. + See . +
@@ -1847,6 +1875,20 @@ public class MyController { ]]> + + To combine a global and a local validator, configure the + global validator as shown above and then add a local validator: + + +
From 9dc7b5feef01272af0dc563248a5e60e6ada9be3 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 14 Jan 2013 21:25:11 -0500 Subject: [PATCH 067/311] Use MessageSource to resolve @ResponseStatus.reason The reason attribute of @ResponseStatus can now be a code resolvable through the ApplicationContext's MessageSource. Issue: SPR-6044 --- .../ResponseStatusExceptionResolver.java | 18 +++++++++-- .../ResponseStatusExceptionResolverTests.java | 32 +++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java index 0d58e8c134..3e5fd73659 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ package org.springframework.web.servlet.mvc.annotation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.context.MessageSource; +import org.springframework.context.MessageSourceAware; +import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.ResponseStatus; @@ -32,9 +35,17 @@ import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver; *

This exception resolver is enabled by default in the {@link org.springframework.web.servlet.DispatcherServlet}. * * @author Arjen Poutsma + * @author Rossen Stoyanchev * @since 3.0 */ -public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver { +public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionResolver implements MessageSourceAware { + + private MessageSource messageSource; + + + public void setMessageSource(MessageSource messageSource) { + this.messageSource = messageSource; + } @Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, @@ -69,6 +80,9 @@ public class ResponseStatusExceptionResolver extends AbstractHandlerExceptionRes int statusCode = responseStatus.value().value(); String reason = responseStatus.reason(); + if (this.messageSource != null) { + reason = this.messageSource.getMessage(reason, null, reason, LocaleContextHolder.getLocale()); + } if (!StringUtils.hasLength(reason)) { response.sendError(statusCode); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java index 684550e18d..25348f53f7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java @@ -1,13 +1,20 @@ package org.springframework.web.servlet.mvc.annotation; import static org.junit.Assert.*; + +import java.util.Locale; + import org.junit.Before; import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.support.StaticMessageSource; import org.springframework.http.HttpStatus; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.context.support.StaticWebApplicationContext; import org.springframework.web.servlet.ModelAndView; /** @author Arjen Poutsma */ @@ -46,6 +53,24 @@ public class ResponseStatusExceptionResolverTests { assertEquals("Invalid status reason", "You suck!", response.getErrorMessage()); } + @Test + public void statusCodeAndReasonMessage() { + Locale locale = Locale.CHINESE; + LocaleContextHolder.setLocale(locale); + try { + StaticMessageSource messageSource = new StaticMessageSource(); + messageSource.addMessage("gone.reason", locale, "Gone reason message"); + exceptionResolver.setMessageSource(messageSource); + + StatusCodeAndReasonMessageException ex = new StatusCodeAndReasonMessageException(); + ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); + assertEquals("Invalid status reason", "Gone reason message", response.getErrorMessage()); + } + finally { + LocaleContextHolder.resetLocaleContext(); + } + } + @Test public void notAnnotated() { Exception ex = new Exception(); @@ -65,4 +90,11 @@ public class ResponseStatusExceptionResolverTests { private static class StatusCodeAndReasonException extends Exception { } + + @ResponseStatus(value = HttpStatus.GONE, reason = "gone.reason") + @SuppressWarnings("serial") + private static class StatusCodeAndReasonMessageException extends Exception { + + } + } From b2d6596901bc782a96685a0778d0da848e5755b6 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 14 Jan 2013 21:38:51 -0500 Subject: [PATCH 068/311] Add contentTypeCompatibleWith option to Spring MVC Test An expectation such as content().contentType(MediaType.TEXT_PLAIN) fails if the actual media type contains a charset or another parameter. A new method allows comparing the media type and subtype only via content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN). Issue: SPR-10165 --- .../client/match/ContentRequestMatchers.java | 27 +++++++++++++-- .../servlet/result/ContentResultMatchers.java | 33 +++++++++++++++++-- .../resultmatchers/ContentAssertionTests.java | 6 ++-- 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java b/spring-test-mvc/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java index 5b89cef1a7..1bcb49a5b9 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/client/match/ContentRequestMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package org.springframework.test.web.client.match; import static org.springframework.test.util.AssertionErrors.assertEquals; -import static org.springframework.test.util.MatcherAssertionErrors.assertThat; import static org.springframework.test.util.AssertionErrors.assertTrue; +import static org.springframework.test.util.MatcherAssertionErrors.assertThat; import java.io.IOException; @@ -72,6 +72,29 @@ public class ContentRequestMatchers { }; } + /** + * Assert the request content type is compatible with the given + * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}. + */ + public RequestMatcher contentTypeCompatibleWith(String contentType) { + return contentTypeCompatibleWith(MediaType.parseMediaType(contentType)); + } + + /** + * Assert the request content type is compatible with the given + * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}. + */ + public RequestMatcher contentTypeCompatibleWith(final MediaType contentType) { + return new RequestMatcher() { + public void match(ClientHttpRequest request) throws IOException, AssertionError { + MediaType actualContentType = request.getHeaders().getContentType(); + assertTrue("Content type not set", actualContentType != null); + assertTrue("Content type [" + actualContentType + "] is not compatible with [" + contentType + "]", + actualContentType.isCompatibleWith(contentType)); + } + }; + } + /** * Get the body of the request as a UTF-8 string and appply the given {@link Matcher}. */ diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java index b39875baaa..c71dc98b7f 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,7 +54,9 @@ public class ContentResultMatchers { } /** - * Assert the ServletResponse content type. + * Assert the ServletResponse content type. The given content type must + * fully match including type, sub-type, and parameters. For checking + * only the type and sub-type see {@link #contentTypeCompatibleWith(String)}. */ public ResultMatcher contentType(String contentType) { return contentType(MediaType.parseMediaType(contentType)); @@ -62,6 +64,9 @@ public class ContentResultMatchers { /** * Assert the ServletResponse content type after parsing it as a MediaType. + * The given content type must fully match including type, sub-type, and + * parameters. For checking only the type and sub-type see + * {@link #contentTypeCompatibleWith(MediaType)}. */ public ResultMatcher contentType(final MediaType contentType) { return new ResultMatcher() { @@ -73,6 +78,30 @@ public class ContentResultMatchers { }; } + /** + * Assert the ServletResponse content type is compatible with the given + * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}. + */ + public ResultMatcher contentTypeCompatibleWith(String contentType) { + return contentTypeCompatibleWith(MediaType.parseMediaType(contentType)); + } + + /** + * Assert the ServletResponse content type is compatible with the given + * content type as defined by {@link MediaType#isCompatibleWith(MediaType)}. + */ + public ResultMatcher contentTypeCompatibleWith(final MediaType contentType) { + return new ResultMatcher() { + public void match(MvcResult result) throws Exception { + String actual = result.getResponse().getContentType(); + assertTrue("Content type not set", actual != null); + MediaType actualContentType = MediaType.parseMediaType(actual); + assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]", + actualContentType.isCompatibleWith(contentType)); + } + }; + } + /** * Assert the character encoding in the ServletResponse. * @see HttpServletResponse#getCharacterEncoding() diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java index 80a0d138f3..4777e5e5e4 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,9 @@ public class ContentAssertionTests { this.mockMvc.perform(get("/handleUtf8")) .andExpect(content().contentType(MediaType.valueOf("text/plain;charset=UTF-8"))) - .andExpect(content().contentType("text/plain;charset=UTF-8")); + .andExpect(content().contentType("text/plain;charset=UTF-8")) + .andExpect(content().contentTypeCompatibleWith("text/plan")) + .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)); } @Test From 33ee0ea4a6eb4a47e4a4291e36124ec631a2f814 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 15 Jan 2013 11:56:27 +0100 Subject: [PATCH 069/311] Fix broken test in ContentAssertionTests --- .../standalone/resultmatchers/ContentAssertionTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java index 4777e5e5e4..568f765564 100644 --- a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/ContentAssertionTests.java @@ -63,7 +63,7 @@ public class ContentAssertionTests { this.mockMvc.perform(get("/handleUtf8")) .andExpect(content().contentType(MediaType.valueOf("text/plain;charset=UTF-8"))) .andExpect(content().contentType("text/plain;charset=UTF-8")) - .andExpect(content().contentTypeCompatibleWith("text/plan")) + .andExpect(content().contentTypeCompatibleWith("text/plain")) .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN)); } From f3e5f8bb4ee3c6066d7078f7d752d6ad7b85104c Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 15 Jan 2013 12:11:44 +0100 Subject: [PATCH 070/311] Update copyright year, author tags, and Javadoc --- .../web/servlet/support/RequestContext.java | 68 +++++++++++-------- .../web/servlet/tags/form/FormTag.java | 2 +- .../web/servlet/tags/form/FormTagTests.java | 1 + 3 files changed, 42 insertions(+), 29 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java index cf63a425c3..cf33995355 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/RequestContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,6 +62,7 @@ import org.springframework.web.util.WebUtils; * appropriate fallback for the locale (the HttpServletRequest's primary locale). * * @author Juergen Hoeller + * @author Rossen Stoyanchev * @since 03.03.2003 * @see org.springframework.web.servlet.DispatcherServlet * @see org.springframework.web.servlet.view.AbstractView#setRequestContextAttribute @@ -234,8 +235,10 @@ public class RequestContext { } /** - * Determine the fallback locale for this context.

The default implementation checks for a JSTL locale attribute - * in request, session or application scope; if not found, returns the {@code HttpServletRequest.getLocale()}. + * Determine the fallback locale for this context. + *

The default implementation checks for a JSTL locale attribute in request, + * session or application scope; if not found, returns the + * {@code HttpServletRequest.getLocale()}. * @return the fallback locale (never {@code null}) * @see javax.servlet.http.HttpServletRequest#getLocale() */ @@ -250,8 +253,8 @@ public class RequestContext { } /** - * Determine the fallback theme for this context.

The default implementation returns the default theme (with name - * "theme"). + * Determine the fallback theme for this context. + *

The default implementation returns the default theme (with name "theme"). * @return the fallback theme (never {@code null}) */ protected Theme getFallbackTheme() { @@ -310,8 +313,8 @@ public class RequestContext { } /** - * Return the current theme (never {@code null}).

Resolved lazily for more efficiency when theme support is - * not being used. + * Return the current theme (never {@code null}). + *

Resolved lazily for more efficiency when theme support is not being used. */ public final Theme getTheme() { if (this.theme == null) { @@ -351,7 +354,8 @@ public class RequestContext { /** * Set the UrlPathHelper to use for context path and request URI decoding. Can be used to pass a shared - * UrlPathHelper instance in.

A default UrlPathHelper is always available. + * UrlPathHelper instance in. + *

A default UrlPathHelper is always available. */ public void setUrlPathHelper(UrlPathHelper urlPathHelper) { Assert.notNull(urlPathHelper, "UrlPathHelper must not be null"); @@ -360,7 +364,8 @@ public class RequestContext { /** * Return the UrlPathHelper used for context path and request URI decoding. Can be used to configure the current - * UrlPathHelper.

A default UrlPathHelper is always available. + * UrlPathHelper. + *

A default UrlPathHelper is always available. */ public UrlPathHelper getUrlPathHelper() { return this.urlPathHelper; @@ -377,8 +382,8 @@ public class RequestContext { /** * Return the context path of the original request, that is, the path that indicates the current web application. - * This is useful for building links to other resources within the application.

Delegates to the UrlPathHelper - * for decoding. + * This is useful for building links to other resources within the application. + *

Delegates to the UrlPathHelper for decoding. * @see javax.servlet.http.HttpServletRequest#getContextPath * @see #getUrlPathHelper */ @@ -423,7 +428,7 @@ public class RequestContext { * context path and the servlet path of the original request. This is useful * for building links to other resources within the application where a * servlet mapping of the style {@code "/main/*"} is used. - * Delegates to the UrlPathHelper to determine the context and servlet path. + *

Delegates to the UrlPathHelper to determine the context and servlet path. */ public String getPathToServlet() { String path = this.urlPathHelper.getOriginatingContextPath(this.request); @@ -437,8 +442,8 @@ public class RequestContext { * Return the request URI of the original request, that is, the invoked URL without parameters. This is particularly * useful as HTML form action target, possibly in combination with the original query string.

Note this * implementation will correctly resolve to the URI of any originating root request in the presence of a forwarded - * request. However, this can only work when the Servlet 2.4 'forward' request attributes are present.

Delegates - * to the UrlPathHelper for decoding. + * request. However, this can only work when the Servlet 2.4 'forward' request attributes are present. + *

Delegates to the UrlPathHelper for decoding. * @see #getQueryString * @see org.springframework.web.util.UrlPathHelper#getOriginatingRequestUri * @see #getUrlPathHelper @@ -574,8 +579,9 @@ public class RequestContext { } /** - * Retrieve the theme message for the given code.

Note that theme messages are never HTML-escaped, as they - * typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the theme message for the given code. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param code code of the message * @param defaultMessage String to return if the lookup fails * @return the message @@ -585,8 +591,9 @@ public class RequestContext { } /** - * Retrieve the theme message for the given code.

Note that theme messages are never HTML-escaped, as they - * typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the theme message for the given code. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param code code of the message * @param args arguments for the message, or {@code null} if none * @param defaultMessage String to return if the lookup fails @@ -597,8 +604,9 @@ public class RequestContext { } /** - * Retrieve the theme message for the given code.

Note that theme messages are never HTML-escaped, as they - * typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the theme message for the given code. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param code code of the message * @param args arguments for the message as a List, or {@code null} if none * @param defaultMessage String to return if the lookup fails @@ -610,8 +618,9 @@ public class RequestContext { } /** - * Retrieve the theme message for the given code.

Note that theme messages are never HTML-escaped, as they - * typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the theme message for the given code. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param code code of the message * @return the message * @throws org.springframework.context.NoSuchMessageException if not found @@ -621,8 +630,9 @@ public class RequestContext { } /** - * Retrieve the theme message for the given code.

Note that theme messages are never HTML-escaped, as they - * typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the theme message for the given code. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param code code of the message * @param args arguments for the message, or {@code null} if none * @return the message @@ -633,8 +643,9 @@ public class RequestContext { } /** - * Retrieve the theme message for the given code.

Note that theme messages are never HTML-escaped, as they - * typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the theme message for the given code. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param code code of the message * @param args arguments for the message as a List, or {@code null} if none * @return the message @@ -645,8 +656,9 @@ public class RequestContext { } /** - * Retrieve the given MessageSourceResolvable in the current theme.

Note that theme messages are never - * HTML-escaped, as they typically denote theme-specific resource paths and not client-visible messages. + * Retrieve the given MessageSourceResolvable in the current theme. + *

Note that theme messages are never HTML-escaped, as they typically denote + * theme-specific resource paths and not client-visible messages. * @param resolvable the MessageSourceResolvable * @return the message * @throws org.springframework.context.NoSuchMessageException if not found diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java index 120b910727..1af5e3972f 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java @@ -32,7 +32,6 @@ import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.servlet.support.RequestDataValueProcessor; import org.springframework.web.util.HtmlUtils; -import org.springframework.web.util.UrlPathHelper; /** * Databinding-aware JSP tag for rendering an HTML '{@code form}' whose @@ -51,6 +50,7 @@ import org.springframework.web.util.UrlPathHelper; * @author Rob Harrop * @author Juergen Hoeller * @author Scott Andrews + * @author Rossen Stoyanchev * @since 2.0 * @see org.springframework.web.servlet.mvc.SimpleFormController */ diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java index c3cd6764af..3f4247033b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/form/FormTagTests.java @@ -34,6 +34,7 @@ import org.springframework.web.servlet.support.RequestDataValueProcessor; * @author Juergen Hoeller * @author Scott Andrews * @author Jeremy Grelle + * @author Rossen Stoyanchev */ public class FormTagTests extends AbstractHtmlElementTagTests { From a3211782a6f82d589e226732a38dcd7117f103d6 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 15 Jan 2013 15:54:14 +0100 Subject: [PATCH 071/311] AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup Issue: SPR-7955 --- .../cache/support/AbstractCacheManager.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java b/spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java index 5d301d85f4..29a5a98973 100644 --- a/spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java +++ b/spring-context/src/main/java/org/springframework/cache/support/AbstractCacheManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import java.util.concurrent.ConcurrentMap; import org.springframework.beans.factory.InitializingBean; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -import org.springframework.util.Assert; /** * Abstract base class implementing the common {@link CacheManager} methods. @@ -45,10 +44,10 @@ public abstract class AbstractCacheManager implements CacheManager, Initializing public void afterPropertiesSet() { Collection caches = loadCaches(); - Assert.notEmpty(caches, "loadCaches must not return an empty Collection"); - this.cacheMap.clear(); // preserve the initial order of the cache names + this.cacheMap.clear(); + this.cacheNames.clear(); for (Cache cache : caches) { this.cacheMap.put(cache.getName(), decorateCache(cache)); this.cacheNames.add(cache.getName()); From abbe1db1065dd62fee790a33aae288d3e2a17a18 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 15 Jan 2013 16:52:09 +0100 Subject: [PATCH 072/311] Polishing along with backport --- .../spel/support/ReflectivePropertyAccessor.java | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java index 4c31c3f6b2..6c5b249114 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectivePropertyAccessor.java @@ -287,7 +287,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { private Method findGetterForProperty(String propertyName, Class clazz, Object target) { Method method = findGetterForProperty(propertyName, clazz, target instanceof Class); - if(method == null && target instanceof Class) { + if (method == null && target instanceof Class) { method = findGetterForProperty(propertyName, target.getClass(), false); } return method; @@ -295,7 +295,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { private Method findSetterForProperty(String propertyName, Class clazz, Object target) { Method method = findSetterForProperty(propertyName, clazz, target instanceof Class); - if(method == null && target instanceof Class) { + if (method == null && target instanceof Class) { method = findSetterForProperty(propertyName, target.getClass(), false); } return method; @@ -303,7 +303,7 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { private Field findField(String name, Class clazz, Object target) { Field field = findField(name, clazz, target instanceof Class); - if(field == null && target instanceof Class) { + if (field == null && target instanceof Class) { field = findField(name, target.getClass(), false); } return field; @@ -383,15 +383,17 @@ public class ReflectivePropertyAccessor implements PropertyAccessor { return field; } } - if(clazz.getSuperclass() != null) { + // We'll search superclasses and implemented interfaces explicitly, + // although it shouldn't be necessary - however, see SPR-10125. + if (clazz.getSuperclass() != null) { Field field = findField(name, clazz.getSuperclass(), mustBeStatic); - if(field != null) { + if (field != null) { return field; } } for (Class implementedInterface : clazz.getInterfaces()) { Field field = findField(name, implementedInterface, mustBeStatic); - if(field != null) { + if (field != null) { return field; } } From 450dbb2810f40f55628df74fc5adb887ef8d657b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 15 Jan 2013 22:05:21 +0100 Subject: [PATCH 073/311] Reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd Issue: SPR-10177 --- .../scheduling/config/spring-task-3.1.xsd | 33 +++++++++++++++++++ .../scheduling/config/spring-task-3.2.xsd | 33 +++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.1.xsd b/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.1.xsd index 91b49de327..56680707c2 100644 --- a/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.1.xsd +++ b/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.1.xsd @@ -52,6 +52,39 @@ ]]> + + + + + + + + + + + + + + + + diff --git a/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.2.xsd b/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.2.xsd index 34b479d12c..eb23e55017 100644 --- a/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.2.xsd +++ b/spring-context/src/main/resources/org/springframework/scheduling/config/spring-task-3.2.xsd @@ -52,6 +52,39 @@ ]]> + + + + + + + + + + + + + + + + From 2cd23a79a3a04b5bc003df57c0f89f7cae4968a9 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 15 Jan 2013 22:06:48 +0100 Subject: [PATCH 074/311] Polishing --- .../annotation/AnnotationScopeMetadataResolver.java | 8 ++++---- .../org/springframework/core/io/ClassPathResource.java | 10 +++------- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java index f678425ea8..6a7db8bd31 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/AnnotationScopeMetadataResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,9 +39,10 @@ import static org.springframework.context.annotation.MetadataUtils.*; */ public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver { + private final ScopedProxyMode defaultProxyMode; + protected Class scopeAnnotationType = Scope.class; - private final ScopedProxyMode defaultProxyMode; /** * Create a new instance of the {@code AnnotationScopeMetadataResolver} class. @@ -77,8 +78,7 @@ public class AnnotationScopeMetadataResolver implements ScopeMetadataResolver { ScopeMetadata metadata = new ScopeMetadata(); if (definition instanceof AnnotatedBeanDefinition) { AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition; - AnnotationAttributes attributes = - attributesFor(annDef.getMetadata(), this.scopeAnnotationType); + AnnotationAttributes attributes = attributesFor(annDef.getMetadata(), this.scopeAnnotationType); if (attributes != null) { metadata.setScopeName(attributes.getString("value")); ScopedProxyMode proxyMode = attributes.getEnum("proxyMode"); diff --git a/spring-core/src/main/java/org/springframework/core/io/ClassPathResource.java b/spring-core/src/main/java/org/springframework/core/io/ClassPathResource.java index e881d4034c..3e8467178d 100644 --- a/spring-core/src/main/java/org/springframework/core/io/ClassPathResource.java +++ b/spring-core/src/main/java/org/springframework/core/io/ClassPathResource.java @@ -205,18 +205,14 @@ public class ClassPathResource extends AbstractFileResolvingResource { */ public String getDescription() { StringBuilder builder = new StringBuilder("class path resource ["); - String pathToUse = path; - if (this.clazz != null && !pathToUse.startsWith("/")) { builder.append(ClassUtils.classPackageAsResourcePath(this.clazz)); builder.append('/'); } - if (pathToUse.startsWith("/")) { pathToUse = pathToUse.substring(1); } - builder.append(pathToUse); builder.append(']'); return builder.toString(); @@ -232,9 +228,9 @@ public class ClassPathResource extends AbstractFileResolvingResource { } if (obj instanceof ClassPathResource) { ClassPathResource otherRes = (ClassPathResource) obj; - return (this.path.equals(otherRes.path) - && ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && ObjectUtils.nullSafeEquals( - this.clazz, otherRes.clazz)); + return (this.path.equals(otherRes.path) && + ObjectUtils.nullSafeEquals(this.classLoader, otherRes.classLoader) && + ObjectUtils.nullSafeEquals(this.clazz, otherRes.clazz)); } return false; } From e44b4b831e198651316068a35730f7c861e4a4cd Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 15 Jan 2013 22:10:14 +0100 Subject: [PATCH 075/311] Further fixes for 3.2.1 --- src/dist/changelog.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index f81937f9b5..6f53ecc731 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -6,13 +6,17 @@ http://www.springsource.org Changes in version 3.2.1 (2013-01-24) -------------------------------------- +* SpEL support for static finals on interfaces (SPR-10125) * AnnotationAwareOrderComparator is able to sort Class objects as well (SPR-10152) * added dedicated sort method to AnnotationAwareOrderComparator (SPR-9625) * fixed QualifierAnnotationAutowireCandidateResolver's detection of custom qualifier annotations (SPR-10107) * fixed AbstractAutoProxyCreator to accept null bean names again (SPR-10108) * AbstractAdvisingBeanPostProcessor caches per bean target class, working for null bean names as well (SPR-10144) * MessageSourceResourceBundle overrides JDK 1.6 containsKey method, avoiding NPE in getKeys (SPR-10136) +* AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup (SPR-7955) * spring-task-3.2.xsd allows for SpEL expressions in initial-delay attribute (SPR-10102) +* reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd (SPR-10177) +* JDBC parameter binding uses JDBC 3.0 ParameterMetaData (if available) for type determination (SPR-10084) * JmsTemplate uses configured receiveTimeout if shorter than remaining transaction timeout (SPR-10109) * added MappingJackson2MessageConverter for JMS (SPR-10099) * MimeMessageHelper encodes attachment filename if not ASCII compliant (SPR-9258) From 6888a6f2867d6264fce832d8ae00205988ed5a94 Mon Sep 17 00:00:00 2001 From: Rob Winch Date: Tue, 15 Jan 2013 15:29:28 -0600 Subject: [PATCH 076/311] Restore *.aj whitespace The removal of whitespace to the *.aj files made in 1762157 cause NoSuchMethodError for code compiled against previous versions of spring-aspects due to a bug in AspectJ (see SPR-10178 for details). This commit reverts all the whitespace changes made in 1762157 which resolves the NoSuchMethodErrors. Issue: SPR-10178 --- .../aspectj/AbstractBeanConfigurerAspect.aj | 12 ++-- .../AbstractDependencyInjectionAspect.aj | 36 +++++----- ...nterfaceDrivenDependencyInjectionAspect.aj | 68 +++++++++---------- .../aspectj/AnnotationBeanConfigurerAspect.aj | 12 ++-- ...nterfaceDrivenDependencyInjectionAspect.aj | 38 +++++------ .../cache/aspectj/AbstractCacheAspect.aj | 4 +- .../cache/aspectj/AnnotationCacheAspect.aj | 2 +- .../AbstractMethodMockingControl.aj | 26 +++---- ...otationDrivenStaticEntityMockingControl.aj | 16 ++--- .../aspectj/JpaExceptionTranslatorAspect.aj | 38 +++-------- .../aspectj/AbstractAsyncExecutionAspect.aj | 4 +- .../aspectj/AbstractTransactionAspect.aj | 6 +- .../aspectj/AnnotationTransactionAspect.aj | 12 ++-- 13 files changed, 129 insertions(+), 145 deletions(-) diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj index 760cea9dc1..85342e838b 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + package org.springframework.beans.factory.aspectj; import org.aspectj.lang.annotation.SuppressAjWarnings; @@ -23,12 +23,12 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; * Abstract superaspect for AspectJ aspects that can perform Dependency * Injection on objects, however they may be created. Define the beanCreation() * pointcut in subaspects. - * + * *

Subaspects may also need a metadata resolution strategy, in the - * {@code BeanWiringInfoResolver} interface. The default implementation + * BeanWiringInfoResolver interface. The default implementation * looks for a bean with the same name as the FQN. This is the default name * of a bean in a Spring container if the id value is not supplied explicitly. - * + * * @author Rob Harrop * @author Rod Johnson * @author Adrian Colyer @@ -62,7 +62,7 @@ public abstract aspect AbstractBeanConfigurerAspect extends BeanConfigurerSuppor /** * The initialization of a new object. - * + * *

WARNING: Although this pointcut is non-abstract for backwards * compatibility reasons, it is meant to be overridden to select * initialization of any configurable bean. diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj index 390e1dc989..23b012ecc7 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import org.aspectj.lang.annotation.SuppressAjWarnings; /** * Abstract base aspect that can perform Dependency * Injection on objects, however they may be created. - * + * * @author Ramnivas Laddad * @since 2.5.2 */ @@ -29,26 +29,26 @@ public abstract aspect AbstractDependencyInjectionAspect { /** * Select construction join points for objects to inject dependencies */ - public abstract pointcut beanConstruction(Object bean); + public abstract pointcut beanConstruction(Object bean); /** * Select deserialization join points for objects to inject dependencies */ public abstract pointcut beanDeserialization(Object bean); - + /** * Select join points in a configurable bean */ public abstract pointcut inConfigurableBean(); - + /** * Select join points in beans to be configured prior to construction? * By default, use post-construction injection matching the default in the Configurable annotation. */ public pointcut preConstructionConfiguration() : if(false); - + /** - * Select the most-specific initialization join point + * Select the most-specific initialization join point * (most concrete class) for the initialization of an instance. */ public pointcut mostSpecificSubTypeConstruction() : @@ -58,25 +58,25 @@ public abstract aspect AbstractDependencyInjectionAspect { * Select least specific super type that is marked for DI (so that injection occurs only once with pre-construction inejection */ public abstract pointcut leastSpecificSuperTypeConstruction(); - + /** * Configure the bean */ public abstract void configureBean(Object bean); - - private pointcut preConstructionCondition() : + + private pointcut preConstructionCondition() : leastSpecificSuperTypeConstruction() && preConstructionConfiguration(); - + private pointcut postConstructionCondition() : mostSpecificSubTypeConstruction() && !preConstructionConfiguration(); - + /** * Pre-construction configuration. */ @SuppressAjWarnings("adviceDidNotMatch") - before(Object bean) : - beanConstruction(bean) && preConstructionCondition() && inConfigurableBean() { + before(Object bean) : + beanConstruction(bean) && preConstructionCondition() && inConfigurableBean() { configureBean(bean); } @@ -84,18 +84,18 @@ public abstract aspect AbstractDependencyInjectionAspect { * Post-construction configuration. */ @SuppressAjWarnings("adviceDidNotMatch") - after(Object bean) returning : + after(Object bean) returning : beanConstruction(bean) && postConstructionCondition() && inConfigurableBean() { configureBean(bean); } - + /** * Post-deserialization configuration. */ @SuppressAjWarnings("adviceDidNotMatch") - after(Object bean) returning : + after(Object bean) returning : beanDeserialization(bean) && inConfigurableBean() { configureBean(bean); } - + } diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj index 5cd0140d46..8e8b634ef0 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,36 +26,36 @@ import java.io.Serializable; * upon deserialization. Subaspects need to simply provide definition for the configureBean() method. This * method may be implemented without relying on Spring container if so desired. *

- *

+ *

* There are two cases that needs to be handled: *

    - *
  1. Normal object creation via the '{@code new}' operator: this is - * taken care of by advising {@code initialization()} join points.
  2. + *
  3. Normal object creation via the 'new' operator: this is + * taken care of by advising initialization() join points.
  4. *
  5. Object creation through deserialization: since no constructor is * invoked during deserialization, the aspect needs to advise a method that a * deserialization mechanism is going to invoke. Ideally, we should not * require user classes to implement any specific method. This implies that * we need to introduce the chosen method. We should also handle the cases * where the chosen method is already implemented in classes (in which case, - * the user's implementation for that method should take precedence over the + * the user's implementation for that method should take precedence over the * introduced implementation). There are a few choices for the chosen method: *
      *
    • readObject(ObjectOutputStream): Java requires that the method must be - * {@code private}. Since aspects cannot introduce a private member, + * private

      . Since aspects cannot introduce a private member, * while preserving its name, this option is ruled out.
    • - *
    • readResolve(): Java doesn't pose any restriction on an access specifier. - * Problem solved! There is one (minor) limitation of this approach in - * that if a user class already has this method, that method must be - * {@code public}. However, this shouldn't be a big burden, since - * use cases that need classes to implement readResolve() (custom enums, + *
    • readResolve(): Java doesn't pose any restriction on an access specifier. + * Problem solved! There is one (minor) limitation of this approach in + * that if a user class already has this method, that method must be + * public. However, this shouldn't be a big burden, since + * use cases that need classes to implement readResolve() (custom enums, * for example) are unlikely to be marked as @Configurable, and - * in any case asking to make that method {@code public} should not + * in any case asking to make that method public should not * pose any undue burden.
    • *
    - * The minor collaboration needed by user classes (i.e., that the - * implementation of {@code readResolve()}, if any, must be - * {@code public}) can be lifted as well if we were to use an - * experimental feature in AspectJ - the {@code hasmethod()} PCD.
  6. + * The minor collaboration needed by user classes (i.e., that the + * implementation of readResolve(), if any, must be + * public) can be lifted as well if we were to use an + * experimental feature in AspectJ - the hasmethod() PCD. *
*

@@ -63,7 +63,7 @@ import java.io.Serializable; * is to use a 'declare parents' statement another aspect (a subaspect of this aspect would be a logical choice) * that declares the classes that need to be configured by supplying the {@link ConfigurableObject} interface. *

- * + * * @author Ramnivas Laddad * @since 2.5.2 */ @@ -71,8 +71,8 @@ public abstract aspect AbstractInterfaceDrivenDependencyInjectionAspect extends /** * Select initialization join point as object construction */ - public pointcut beanConstruction(Object bean) : - initialization(ConfigurableObject+.new(..)) && this(bean); + public pointcut beanConstruction(Object bean) : + initialization(ConfigurableObject+.new(..)) && this(bean); /** * Select deserialization join point made available through ITDs for ConfigurableDeserializationSupport @@ -80,40 +80,40 @@ public abstract aspect AbstractInterfaceDrivenDependencyInjectionAspect extends public pointcut beanDeserialization(Object bean) : execution(Object ConfigurableDeserializationSupport+.readResolve()) && this(bean); - + public pointcut leastSpecificSuperTypeConstruction() : initialization(ConfigurableObject.new(..)); - - - + + + // Implementation to support re-injecting dependencies once an object is deserialized /** - * Declare any class implementing Serializable and ConfigurableObject as also implementing - * ConfigurableDeserializationSupport. This allows us to introduce the readResolve() + * Declare any class implementing Serializable and ConfigurableObject as also implementing + * ConfigurableDeserializationSupport. This allows us to introduce the readResolve() * method and select it with the beanDeserialization() pointcut. - * + * *

Here is an improved version that uses the hasmethod() pointcut and lifts * even the minor requirement on user classes: * *

declare parents: ConfigurableObject+ Serializable+
-	 *		            && !hasmethod(Object readResolve() throws ObjectStreamException)
+	 *		            && !hasmethod(Object readResolve() throws ObjectStreamException) 
 	 *		            implements ConfigurableDeserializationSupport;
 	 * 
*/ - declare parents: + declare parents: ConfigurableObject+ && Serializable+ implements ConfigurableDeserializationSupport; - + /** - * A marker interface to which the {@code readResolve()} is introduced. + * A marker interface to which the readResolve() is introduced. */ static interface ConfigurableDeserializationSupport extends Serializable { } - + /** - * Introduce the {@code readResolve()} method so that we can advise its + * Introduce the readResolve() method so that we can advise its * execution to configure the object. - * + * *

Note if a method with the same signature already exists in a - * {@code Serializable} class of ConfigurableObject type, + * Serializable class of ConfigurableObject type, * that implementation will take precedence (a good thing, since we are * merely interested in an opportunity to detect deserialization.) */ diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj index 5313df9ed1..4cdc292dbb 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; * annotation to identify which classes need autowiring. * *

The bean name to look up will be taken from the - * {@code @Configurable} annotation if specified, otherwise the + * @Configurable annotation if specified, otherwise the * default bean name to look up will be the FQN of the class being configured. * * @author Rod Johnson @@ -43,7 +43,7 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; * @see org.springframework.beans.factory.annotation.Configurable * @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver */ -public aspect AnnotationBeanConfigurerAspect +public aspect AnnotationBeanConfigurerAspect extends AbstractInterfaceDrivenDependencyInjectionAspect implements BeanFactoryAware, InitializingBean, DisposableBean { @@ -51,7 +51,7 @@ public aspect AnnotationBeanConfigurerAspect public pointcut inConfigurableBean() : @this(Configurable); - public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*); + public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*); declare parents: @Configurable * implements ConfigurableObject; @@ -80,10 +80,10 @@ public aspect AnnotationBeanConfigurerAspect private pointcut preConstructionConfigurationSupport(Configurable c) : @this(c) && if(c.preConstruction()); /* - * This declaration shouldn't be needed, + * This declaration shouldn't be needed, * except for an AspectJ bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=214559) */ - declare parents: @Configurable Serializable+ + declare parents: @Configurable Serializable+ implements ConfigurableDeserializationSupport; } diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj index 351c11d7d9..03f446ca78 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,38 +17,38 @@ package org.springframework.beans.factory.aspectj; /** * Generic-based dependency injection aspect. - *

- * This aspect allows users to implement efficient, type-safe dependency injection without + *

+ * This aspect allows users to implement efficient, type-safe dependency injection without * the use of the @Configurable annotation. - * - * The subaspect of this aspect doesn't need to include any AOP constructs. - * For example, here is a subaspect that configures the {@code PricingStrategyClient} objects. + * + * The subaspect of this aspect doesn't need to include any AOP constructs. + * For example, here is a subaspect that configures the PricingStrategyClient objects. *

- * aspect PricingStrategyDependencyInjectionAspect
+ * aspect PricingStrategyDependencyInjectionAspect 
  *        extends GenericInterfaceDrivenDependencyInjectionAspect {
  *     private PricingStrategy pricingStrategy;
- *
- *     public void configure(PricingStrategyClient bean) {
- *         bean.setPricingStrategy(pricingStrategy);
- *     }
- *
- *     public void setPricingStrategy(PricingStrategy pricingStrategy) {
- *         this.pricingStrategy = pricingStrategy;
+ *     
+ *     public void configure(PricingStrategyClient bean) { 
+ *         bean.setPricingStrategy(pricingStrategy); 
  *     }
+ *     
+ *     public void setPricingStrategy(PricingStrategy pricingStrategy) { 
+ *         this.pricingStrategy = pricingStrategy; 
+ *     } 
  * }
  * 
* @author Ramnivas Laddad * @since 3.0.0 */ public abstract aspect GenericInterfaceDrivenDependencyInjectionAspect extends AbstractInterfaceDrivenDependencyInjectionAspect { - declare parents: I implements ConfigurableObject; - + declare parents: I implements ConfigurableObject; + public pointcut inConfigurableBean() : within(I+); - + public final void configureBean(Object bean) { configure((I)bean); } - - // Unfortunately, erasure used with generics won't allow to use the same named method + + // Unfortunately, erasure used with generics won't allow to use the same named method protected abstract void configure(I bean); } diff --git a/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj b/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj index a9a6da82e9..dbe15b8fb3 100644 --- a/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -62,7 +62,7 @@ public abstract aspect AbstractCacheAspect extends CacheAspectSupport { } }; - return execute(aspectJInvoker, thisJoinPoint.getTarget(), method, thisJoinPoint.getArgs()); + return execute(aspectJInvoker, thisJoinPoint.getTarget(), method, thisJoinPoint.getArgs()); } /** diff --git a/spring-aspects/src/main/java/org/springframework/cache/aspectj/AnnotationCacheAspect.aj b/spring-aspects/src/main/java/org/springframework/cache/aspectj/AnnotationCacheAspect.aj index be3957a3a0..5418488b53 100644 --- a/spring-aspects/src/main/java/org/springframework/cache/aspectj/AnnotationCacheAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/cache/aspectj/AnnotationCacheAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj index e373607d55..7ab3fcd0c3 100644 --- a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj +++ b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,9 @@ import java.util.List; /** * Abstract aspect to enable mocking of methods picked out by a pointcut. * Sub-aspects must define the mockStaticsTestMethod() pointcut to - * indicate call stacks when mocking should be triggered, and the + * indicate call stacks when mocking should be triggered, and the * methodToMock() pointcut to pick out a method invocations to mock. - * + * * @author Rod Johnson * @author Ramnivas Laddad */ @@ -42,7 +42,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth // Represents a list of expected calls to static entity methods // Public to allow inserted code to access: is this normal?? public class Expectations { - + // Represents an expected call to a static entity method private class Call { private final String signature; @@ -50,21 +50,21 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth private Object responseObject; // return value or throwable private CallResponse responseType = CallResponse.nothing; - + public Call(String name, Object[] args) { this.signature = name; this.args = args; } - + public boolean hasResponseSpecified() { return responseType != CallResponse.nothing; } - + public void setReturnVal(Object retVal) { this.responseObject = retVal; responseType = CallResponse.return_; } - + public void setThrow(Throwable throwable) { this.responseObject = throwable; responseType = CallResponse.throw_; @@ -89,7 +89,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth } } } - + private List calls = new LinkedList(); // Calls already verified @@ -101,12 +101,12 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth + " calls, received " + verified); } } - + /** * Validate the call and provide the expected return value * @param lastSig * @param args - * @return the return value + * @return */ public Object respond(String lastSig, Object[] args) { Call call = nextCall(); @@ -114,7 +114,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth if (responseType == CallResponse.return_) { return call.returnValue(lastSig, args); } else if(responseType == CallResponse.throw_) { - return call.throwException(lastSig, args); + return (RuntimeException)call.throwException(lastSig, args); } else if(responseType == CallResponse.nothing) { // do nothing } @@ -175,7 +175,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth return expectations.respond(thisJoinPointStaticPart.toLongString(), thisJoinPoint.getArgs()); } } - + public void expectReturnInternal(Object retVal) { if (!recording) { throw new IllegalStateException("Not recording: Cannot set return value"); diff --git a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj index 1c50c64bbe..031978ca91 100644 --- a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj +++ b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,16 +18,16 @@ package org.springframework.mock.staticmock; /** * Annotation-based aspect to use in test build to enable mocking static methods - * on JPA-annotated {@code @Entity} classes, as used by Roo for finders. + * on JPA-annotated @Entity classes, as used by Roo for finders. * - *

Mocking will occur in the call stack of any method in a class (typically a test class) - * that is annotated with the @MockStaticEntityMethods annotation. + *

Mocking will occur in the call stack of any method in a class (typically a test class) + * that is annotated with the @MockStaticEntityMethods annotation. * *

Also provides static methods to simplify the programming model for * entering playback mode and setting expected return values. * *

Usage: - *

    + *
      *
    1. Annotate a test class with @MockStaticEntityMethods. *
    2. In each test method, AnnotationDrivenStaticEntityMockingControl will begin in recording mode. * Invoke static methods on Entity classes, with each recording-mode invocation @@ -37,20 +37,20 @@ package org.springframework.mock.staticmock; *
    3. Call the code you wish to test that uses the static methods. Verification will * occur automatically. *
    - * + * * @author Rod Johnson * @author Ramnivas Laddad * @see MockStaticEntityMethods */ public aspect AnnotationDrivenStaticEntityMockingControl extends AbstractMethodMockingControl { - + /** * Stop recording mock calls and enter playback state */ public static void playback() { AnnotationDrivenStaticEntityMockingControl.aspectOf().playbackInternal(); } - + public static void expectReturn(Object retVal) { AnnotationDrivenStaticEntityMockingControl.aspectOf().expectReturnInternal(retVal); } diff --git a/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj b/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj index 3594725aae..6ff44249d0 100644 --- a/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj @@ -1,19 +1,3 @@ -/* - * 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.orm.jpa.aspectj; import javax.persistence.EntityManager; @@ -25,14 +9,14 @@ import org.springframework.dao.DataAccessException; import org.springframework.orm.jpa.EntityManagerFactoryUtils; public aspect JpaExceptionTranslatorAspect { - pointcut entityManagerCall(): call(* EntityManager.*(..)) || call(* EntityManagerFactory.*(..)) || call(* EntityTransaction.*(..)) || call(* Query.*(..)); - - after() throwing(RuntimeException re): entityManagerCall() { - DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(re); - if (dex != null) { - throw dex; - } else { - throw re; - } - } -} + pointcut entityManagerCall(): call(* EntityManager.*(..)) || call(* EntityManagerFactory.*(..)) || call(* EntityTransaction.*(..)) || call(* Query.*(..)); + + after() throwing(RuntimeException re): entityManagerCall() { + DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(re); + if (dex != null) { + throw dex; + } else { + throw re; + } + } +} \ No newline at end of file diff --git a/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj b/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj index a64def7ed1..6cb3ad60e3 100644 --- a/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ import org.springframework.core.task.AsyncTaskExecutor; /** * Abstract aspect that routes selected methods asynchronously. * - *

    This aspect needs to be injected with an implementation of + *

    This aspect needs to be injected with an implementation of * {@link Executor} to activate it for a specific thread pool. * Otherwise it will simply delegate all calls synchronously. * diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj index ed0956ef9f..3ce264d9e1 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ import org.springframework.transaction.interceptor.TransactionAttributeSource; /** * Abstract superaspect for AspectJ transaction aspects. Concrete - * subaspects will implement the {@code transactionalMethodExecution()} + * subaspects will implement the transactionalMethodExecution() * pointcut using a strategy such as Java 5 annotations. * *

    Suitable for use inside or outside the Spring IoC container. @@ -66,7 +66,7 @@ public abstract aspect AbstractTransactionAspect extends TransactionAspectSuppor @SuppressAjWarnings("adviceDidNotMatch") after(Object txObject) throwing(Throwable t) : transactionalMethodExecution(txObject) { try { - completeTransactionAfterThrowing(TransactionAspectSupport.currentTransactionInfo(), t); + completeTransactionAfterThrowing(TransactionAspectSupport.currentTransactionInfo(), t); } catch (Throwable t2) { logger.error("Failed to close transaction after throwing in a transactional method", t2); diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj index 1fe8de9030..2ea8f9e3f5 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,17 +21,17 @@ import org.springframework.transaction.annotation.Transactional; /** * Concrete AspectJ transaction aspect using Spring's @Transactional annotation. - * + * *

    When using this aspect, you must annotate the implementation class * (and/or methods within that class), not the interface (if any) that - * the class implements. AspectJ follows Java's rule that annotations on + * the class implements. AspectJ follows Java's rule that annotations on * interfaces are not inherited. * *

    An @Transactional annotation on a class specifies the default transaction * semantics for the execution of any public operation in the class. * *

    An @Transactional annotation on a method within the class overrides the - * default transaction semantics given by the class annotation (if present). + * default transaction semantics given by the class annotation (if present). * Any method may be annotated (regardless of visibility). * Annotating non-public methods directly is the only way * to get transaction demarcation for the execution of such operations. @@ -57,7 +57,7 @@ public aspect AnnotationTransactionAspect extends AbstractTransactionAspect { execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *); /** - * Matches the execution of any method with the + * Matches the execution of any method with the * Transactional annotation. */ private pointcut executionOfTransactionalMethod() : @@ -66,7 +66,7 @@ public aspect AnnotationTransactionAspect extends AbstractTransactionAspect { /** * Definition of pointcut from super aspect - matched join points * will have Spring transaction management applied. - */ + */ protected pointcut transactionalMethodExecution(Object txObject) : (executionOfAnyPublicMethodInAtTransactionalType() || executionOfTransactionalMethod() ) From 26d5ef93e6ddb7d3ba5774b5e427b0dc6b61516f Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Thu, 20 Dec 2012 00:26:08 +0100 Subject: [PATCH 077/311] Handle non-void write methods deterministically This change resolves a specific issue with processing java.math.BigDecimal via ExtendedBeanInfo. BigDecimal has a particular constellation of #setScale methods that, prior to this change, had the potential to cause ExtendedBeanInfo to throw an IntrospectionException depending on the order in which the methods were processed. Because JDK 7 no longer returns deterministic results from Class#getDeclaredMethods, it became a genuine possibility - indeed a statistical certainty that the 'wrong' setScale method handling order happens sooner or later. Typically one could observe this failure once out of every four test runs. This commit introduces deterministic method ordering of all discovered non-void returning write methods in such a way that solves the problem for BigDecimal as well as for any other class having a similar method arrangement. Also: - Remove unnecessary cast - Pass no method information to PropertyDescriptor superclasses when invoking super(...). This ensures that any 'type mismatch' IntrospectionExceptions are handled locally in ExtendedBeanInfo and its Simple* PropertyDescriptor variants where we have full control. Issue: SPR-10111, SPR-9702 Backport-Commit: aa3e0be (forward-ported via cherry-pick from 3.1.x) --- .../beans/ExtendedBeanInfo.java | 13 ++++++++-- .../beans/ExtendedBeanInfoTests.java | 26 ++++++++++++------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java index 54467cd3ea..c3609c10c2 100644 --- a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java +++ b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java @@ -31,6 +31,7 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.List; @@ -116,6 +117,14 @@ class ExtendedBeanInfo implements BeanInfo { matches.add(method); } } + // sort non-void returning write methods to guard against the ill effects of + // non-deterministic sorting of methods returned from Class#getDeclaredMethods + // under JDK 7. See http://bugs.sun.com/view_bug.do?bug_id=7023180 + Collections.sort(matches, new Comparator() { + public int compare(Method m1, Method m2) { + return m2.toString().compareTo(m1.toString()); + } + }); return matches; } @@ -264,7 +273,7 @@ class SimpleNonIndexedPropertyDescriptor extends PropertyDescriptor { public SimpleNonIndexedPropertyDescriptor(String propertyName, Method readMethod, Method writeMethod) throws IntrospectionException { - super(propertyName, readMethod, writeMethod); + super(propertyName, null, null); this.setReadMethod(readMethod); this.setWriteMethod(writeMethod); this.propertyType = findPropertyType(readMethod, writeMethod); @@ -353,7 +362,7 @@ class SimpleIndexedPropertyDescriptor extends IndexedPropertyDescriptor { Method indexedReadMethod, Method indexedWriteMethod) throws IntrospectionException { - super(propertyName, readMethod, writeMethod, indexedReadMethod, indexedWriteMethod); + super(propertyName, null, null, null, null); this.setReadMethod(readMethod); this.setWriteMethod(writeMethod); this.propertyType = findPropertyType(readMethod, writeMethod); diff --git a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java index aaf6e56092..ec2ca31e2b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -23,6 +23,7 @@ import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; +import java.math.BigDecimal; import org.junit.Test; @@ -192,7 +193,6 @@ public class ExtendedBeanInfoTests { } } class Child extends Parent { - @Override public Integer getProperty1() { return 2; } @@ -214,7 +214,6 @@ public class ExtendedBeanInfoTests { @Test public void cornerSpr9453() throws IntrospectionException { final class Bean implements Spr9453> { - @Override public Class getProp() { return null; } @@ -583,6 +582,20 @@ public class ExtendedBeanInfoTests { } } + /** + * Prior to SPR-10111 (a follow-up fix for SPR-9702), this method would throw an + * IntrospectionException regarding a "type mismatch between indexed and non-indexed + * methods" intermittently (approximately one out of every four times) under JDK 7 + * due to non-deterministic results from {@link Class#getDeclaredMethods()}. + * See http://bugs.sun.com/view_bug.do?bug_id=7023180 + * @see #cornerSpr9702() + */ + @Test + public void cornerSpr10111() throws Exception { + new ExtendedBeanInfo(Introspector.getBeanInfo(BigDecimal.class)); + } + + @Test public void subclassWriteMethodWithCovariantReturnType() throws IntrospectionException { @SuppressWarnings("unused") class B { @@ -590,9 +603,7 @@ public class ExtendedBeanInfoTests { public Number setFoo(String foo) { return null; } } class C extends B { - @Override public String getFoo() { return null; } - @Override public Integer setFoo(String foo) { return null; } } @@ -695,7 +706,7 @@ public class ExtendedBeanInfoTests { for (PropertyDescriptor pd : ebi.getPropertyDescriptors()) { if (pd.getName().equals("foo")) { - assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", int.class))); + assertThat(pd.getWriteMethod(), is(C.class.getMethod("setFoo", String.class))); return; } } @@ -733,7 +744,7 @@ public class ExtendedBeanInfoTests { assertThat(hasReadMethodForProperty(ebi, "dateFormat"), is(false)); assertThat(hasWriteMethodForProperty(ebi, "dateFormat"), is(true)); assertThat(hasIndexedReadMethodForProperty(ebi, "dateFormat"), is(false)); - assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat"), is(true)); + assertThat(hasIndexedWriteMethodForProperty(ebi, "dateFormat"), is(trueUntilJdk17())); } @Test @@ -864,7 +875,6 @@ public class ExtendedBeanInfoTests { } interface TextBookOperations extends BookOperations { - @Override TextBook getBook(); } @@ -874,7 +884,6 @@ public class ExtendedBeanInfoTests { } class LawLibrary extends Library implements TextBookOperations { - @Override public LawBook getBook() { return null; } } @@ -889,7 +898,6 @@ public class ExtendedBeanInfoTests { } class B extends A { - @Override public boolean isTargetMethod() { return false; } From 19445508b31c9e032f62498521cd39c1d75902d5 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Wed, 16 Jan 2013 08:55:58 +0100 Subject: [PATCH 078/311] Polish build.gradle --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index d37870c20f..143e6a79dc 100644 --- a/build.gradle +++ b/build.gradle @@ -776,7 +776,7 @@ configure(rootProject) { projectsToScan -= project(":spring-instrument-tomcat") } - // don"t publish the default jar for the root project + // don't publish the default jar for the root project configurations.archives.artifacts.clear() dependencies { // for integration tests From e659deab4f014d550ff2da5d81b0d76b9cdf2c19 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Wed, 16 Jan 2013 08:56:06 +0100 Subject: [PATCH 079/311] Remove .aj sources from spring-aspects jar Issue: SPR-10179 --- spring-aspects/aspects.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-aspects/aspects.gradle b/spring-aspects/aspects.gradle index c99fa03183..8172830316 100644 --- a/spring-aspects/aspects.gradle +++ b/spring-aspects/aspects.gradle @@ -33,7 +33,7 @@ task compileJava(overwrite: true) { destDir: outputDir.absolutePath, aspectPath: configurations.aspects.asPath, inpath: configurations.ajInpath.asPath, - sourceRootCopyFilter: "**/*.java", + sourceRootCopyFilter: "**/*.java,**/*.aj", classpath: (sourceSets.main.runtimeClasspath + configurations.rt).asPath) { sourceroots { sourceSets.main.java.srcDirs.each { From 6a5744e61cc0a60a812580c26b9b004709cbe6e0 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 16 Jan 2013 10:24:05 +0100 Subject: [PATCH 080/311] CachedIntrospectionResults.clearClassLoader(null) removes cached classes for the system class loader Issue: SPR-9189 --- .../beans/CachedIntrospectionResults.java | 11 ++++------- .../beans/CachedIntrospectionResultsTests.java | 13 ++++++++++--- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java b/spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java index 47ff208dd4..7c8cd51cec 100644 --- a/spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java +++ b/spring-beans/src/main/java/org/springframework/beans/CachedIntrospectionResults.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -107,9 +107,6 @@ public class CachedIntrospectionResults { * @param classLoader the ClassLoader to clear the cache for */ public static void clearClassLoader(ClassLoader classLoader) { - if (classLoader == null) { - return; - } synchronized (classCache) { for (Iterator it = classCache.keySet().iterator(); it.hasNext();) { Class beanClass = it.next(); @@ -199,12 +196,12 @@ public class CachedIntrospectionResults { * @param parent the parent ClassLoader to check for */ private static boolean isUnderneathClassLoader(ClassLoader candidate, ClassLoader parent) { - if (candidate == null) { - return false; - } if (candidate == parent) { return true; } + if (candidate == null) { + return false; + } ClassLoader classLoaderToCheck = candidate; while (classLoaderToCheck != null) { classLoaderToCheck = classLoaderToCheck.getParent(); diff --git a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java index a4fe92acc9..618ced2e49 100644 --- a/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/CachedIntrospectionResultsTests.java @@ -18,9 +18,8 @@ package org.springframework.beans; import java.beans.BeanInfo; import java.beans.PropertyDescriptor; +import java.util.ArrayList; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import org.junit.Test; import org.springframework.core.OverridingClassLoader; @@ -37,7 +36,7 @@ import static org.junit.Assert.*; public final class CachedIntrospectionResultsTests { @Test - public void acceptClassLoader() throws Exception { + public void acceptAndClearClassLoader() throws Exception { BeanWrapper bw = new BeanWrapperImpl(TestBean.class); assertTrue(bw.isWritableProperty("name")); assertTrue(bw.isWritableProperty("age")); @@ -57,6 +56,14 @@ public final class CachedIntrospectionResultsTests { assertTrue(CachedIntrospectionResults.classCache.containsKey(TestBean.class)); } + @Test + public void clearClassLoaderForSystemClassLoader() throws Exception { + BeanUtils.getPropertyDescriptors(ArrayList.class); + assertTrue(CachedIntrospectionResults.classCache.containsKey(ArrayList.class)); + CachedIntrospectionResults.clearClassLoader(ArrayList.class.getClassLoader()); + assertFalse(CachedIntrospectionResults.classCache.containsKey(ArrayList.class)); + } + @Test public void shouldUseExtendedBeanInfoWhenApplicable() throws NoSuchMethodException, SecurityException { // given a class with a non-void returning setter method From d55877ccf2d050af4c4194c7983ffaac9db88aea Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 17 Jan 2013 12:30:02 +0100 Subject: [PATCH 081/311] spring-jms-3.2.xsd allows for SpEL expressions in prefetch and receive-timeout attributes Issue: SPR-9553 --- .../org/springframework/jms/config/spring-jms-3.2.xsd | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-jms/src/main/resources/org/springframework/jms/config/spring-jms-3.2.xsd b/spring-jms/src/main/resources/org/springframework/jms/config/spring-jms-3.2.xsd index be338f0fc0..c5ac3bb32d 100644 --- a/spring-jms/src/main/resources/org/springframework/jms/config/spring-jms-3.2.xsd +++ b/spring-jms/src/main/resources/org/springframework/jms/config/spring-jms-3.2.xsd @@ -225,7 +225,7 @@ ]]> - + - + - + Date: Fri, 18 Jan 2013 13:42:21 +0100 Subject: [PATCH 082/311] Removed reference to AttributesJmxAttributeSource Issue: SPR-8916 --- src/reference/docbook/jmx.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/jmx.xml b/src/reference/docbook/jmx.xml index 85ae5d0d27..05e8588ebf 100644 --- a/src/reference/docbook/jmx.xml +++ b/src/reference/docbook/jmx.xml @@ -1061,7 +1061,7 @@ public class AnnotationTestBean implements IJmxTestBean { + class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/> ]]> From cd2183f9e1eb7b098edaa86472014197f5d6e6aa Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 13:47:11 +0100 Subject: [PATCH 083/311] Fixed ConnectionSpecConnectionFactoryAdapter explanation Issue: SPR-9466 --- src/reference/docbook/cci.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/reference/docbook/cci.xml b/src/reference/docbook/cci.xml index e5fc3bb82f..051d587da5 100644 --- a/src/reference/docbook/cci.xml +++ b/src/reference/docbook/cci.xml @@ -169,9 +169,9 @@ allows for specifying a ConnectionSpec instance to use for all operations on a given factory. If the adapter's connectionSpec property is specified, the adapter - uses the getConnection variant without argument, else - the one with the ConnectionSpec - argument. + uses the getConnection variant with the + ConnectionSpec argument, otherwise + the variant without argument. <bean id="managedConnectionFactory" class="com.sun.connector.cciblackbox.CciLocalTxManagedConnectionFactory"> From 13cf1fceaa88add6c02b4cebb58c7a5721c93946 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 13:49:57 +0100 Subject: [PATCH 084/311] Fixed reference to "fallbackToNoOpCache" flag Issue: SPR-9064 --- src/reference/docbook/cache.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/reference/docbook/cache.xml b/src/reference/docbook/cache.xml index b96eaa3c91..08d2f34c0e 100644 --- a/src/reference/docbook/cache.xml +++ b/src/reference/docbook/cache.xml @@ -570,10 +570,10 @@ public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)]]>< - + ]]> - The CompositeCacheManager above chains multiple CacheManagers and additionally, through the addNoOpManager flag, adds a + The CompositeCacheManager above chains multiple CacheManagers and additionally, through the fallbackToNoOpCache flag, adds a no op cache that for all the definitions not handled by the configured cache managers. That is, every cache definition not found in either jdkCache or gemfireCache (configured above) will be handled by the no op cache, which will not store any information causing the target method to be executed every time. From be606f4169ce8a79f88ca0bfd02233095a3cff40 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 13:58:22 +0100 Subject: [PATCH 085/311] Added hint towards not using orm.hibernate3 classes with Hibernate 4 Issue: SPR-9365 --- .../org/springframework/orm/hibernate4/package-info.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/package-info.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/package-info.java index 809ced77e6..6715263e75 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/package-info.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/package-info.java @@ -6,10 +6,13 @@ * *

    Contains an implementation of Spring's transaction SPI for local Hibernate transactions. * This package is intentionally rather minimal, with no template classes or the like, - * in order to follow native Hibernate recommendations as closely as possible. + * in order to follow Hibernate recommendations as closely as possible. We recommend + * using Hibernate's native sessionFactory.getCurrentSession() style. * *

    This package supports Hibernate 4.x only. * See the {@code org.springframework.orm.hibernate3} package for Hibernate 3.x support. + * Note: Do not use HibernateTemplate or other classes from the hibernate3 package + * with Hibernate 4; this will lead to class definition exceptions at runtime. * */ package org.springframework.orm.hibernate4; From 20c4ba40d8735c0b86bc3e5dc20af4b7664b94ae Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 14:02:13 +0100 Subject: [PATCH 086/311] AbstractDriverBasedDataSource does not rely on Properties chaining anymore Issue: SPR-9461 --- .../jdbc/datasource/AbstractDriverBasedDataSource.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java index 00aedb4c22..6df3d53e57 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -139,7 +139,8 @@ public abstract class AbstractDriverBasedDataSource extends AbstractDataSource { * @see java.sql.Driver#connect(String, java.util.Properties) */ protected Connection getConnectionFromDriver(String username, String password) throws SQLException { - Properties props = new Properties(getConnectionProperties()); + Properties props = new Properties(); + props.putAll(getConnectionProperties()); if (username != null) { props.setProperty("user", username); } From 721fa9db6a3416f805350b0ae2fba538cdf8e0e6 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 14:12:02 +0100 Subject: [PATCH 087/311] SpringBeanAutowiringInterceptor eagerly releases BeanFactory if post-construction fails Issue: SPR-10013 --- .../beans/factory/access/BeanFactoryReference.java | 6 ++---- .../interceptor/SpringBeanAutowiringInterceptor.java | 10 +++++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/access/BeanFactoryReference.java b/spring-beans/src/main/java/org/springframework/beans/factory/access/BeanFactoryReference.java index 35c3d3f51f..c2c0a7c629 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/access/BeanFactoryReference.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/access/BeanFactoryReference.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ package org.springframework.beans.factory.access; -import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.BeanFactory; /** @@ -49,11 +48,10 @@ public interface BeanFactoryReference { *

    In an EJB usage scenario this would normally be called from * {@code ejbRemove()} and {@code ejbPassivate()}. *

    This is safe to call multiple times. - * @throws FatalBeanException if the {@code BeanFactory} cannot be released * @see BeanFactoryLocator * @see org.springframework.context.access.ContextBeanFactoryReference * @see org.springframework.context.ConfigurableApplicationContext#close() */ - void release() throws FatalBeanException; + void release(); } diff --git a/spring-context/src/main/java/org/springframework/ejb/interceptor/SpringBeanAutowiringInterceptor.java b/spring-context/src/main/java/org/springframework/ejb/interceptor/SpringBeanAutowiringInterceptor.java index 89d5067451..33c1596630 100644 --- a/spring-context/src/main/java/org/springframework/ejb/interceptor/SpringBeanAutowiringInterceptor.java +++ b/spring-context/src/main/java/org/springframework/ejb/interceptor/SpringBeanAutowiringInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,8 +71,6 @@ import org.springframework.context.access.ContextSingletonBeanFactoryLocator; * @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor * @see org.springframework.context.access.ContextSingletonBeanFactoryLocator * @see #getBeanFactoryLocatorKey - * @see org.springframework.ejb.support.AbstractEnterpriseBean#setBeanFactoryLocator - * @see org.springframework.ejb.support.AbstractEnterpriseBean#setBeanFactoryLocatorKey */ public class SpringBeanAutowiringInterceptor { @@ -99,9 +97,15 @@ public class SpringBeanAutowiringInterceptor { invocationContext.proceed(); } catch (RuntimeException ex) { + doReleaseBean(invocationContext.getTarget()); throw ex; } + catch (Error err) { + doReleaseBean(invocationContext.getTarget()); + throw err; + } catch (Exception ex) { + doReleaseBean(invocationContext.getTarget()); // Cannot declare a checked exception on WebSphere here - so we need to wrap. throw new EJBException(ex); } From 3dd817585b6258fe51d3279262234dc41f34009b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 14:43:11 +0100 Subject: [PATCH 088/311] MBeanExporter does not log warnings for manually unregistered MBeans Issue: SPR-9451 --- .../jmx/support/MBeanRegistrationSupport.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java b/spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java index 74b0a3f3c0..38339d4b7f 100644 --- a/spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java +++ b/spring-context/src/main/java/org/springframework/jmx/support/MBeanRegistrationSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.jmx.support; +import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import javax.management.InstanceAlreadyExistsException; @@ -112,7 +113,7 @@ public class MBeanRegistrationSupport { /** * The beans that have been registered by this exporter. */ - protected final Set registeredBeans = new LinkedHashSet(); + private final Set registeredBeans = Collections.synchronizedSet(new LinkedHashSet()); /** * The policy used when registering an MBean and finding that it already exists. @@ -228,10 +229,9 @@ public class MBeanRegistrationSupport { * Unregisters all beans that have been registered by an instance of this class. */ protected void unregisterBeans() { - for (ObjectName objectName : this.registeredBeans) { + for (ObjectName objectName : new LinkedHashSet(this.registeredBeans)) { doUnregister(objectName); } - this.registeredBeans.clear(); } /** @@ -257,6 +257,7 @@ public class MBeanRegistrationSupport { logger.error("Could not unregister MBean [" + objectName + "]", ex); } } + this.registeredBeans.remove(objectName); } /** From ed952ccba1118af716747eb183ea95b5beef8421 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 14:52:24 +0100 Subject: [PATCH 089/311] LocalVariableTableParameterNameDiscoverer works for bridge methods as well Issue: SPR-9429 --- .../LocalVariableTableParameterNameDiscoverer.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java b/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java index 588472532c..3cab216bf0 100644 --- a/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java +++ b/spring-core/src/main/java/org/springframework/core/LocalVariableTableParameterNameDiscoverer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,15 +65,15 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD public String[] getParameterNames(Method method) { - Class declaringClass = method.getDeclaringClass(); + Method originalMethod = BridgeMethodResolver.findBridgedMethod(method); + Class declaringClass = originalMethod.getDeclaringClass(); Map map = this.parameterNamesCache.get(declaringClass); if (map == null) { - // initialize cache map = inspectClass(declaringClass); this.parameterNamesCache.put(declaringClass, map); } if (map != NO_DEBUG_INFO_MAP) { - return map.get(method); + return map.get(originalMethod); } return null; } @@ -82,14 +82,12 @@ public class LocalVariableTableParameterNameDiscoverer implements ParameterNameD Class declaringClass = ctor.getDeclaringClass(); Map map = this.parameterNamesCache.get(declaringClass); if (map == null) { - // initialize cache map = inspectClass(declaringClass); this.parameterNamesCache.put(declaringClass, map); } if (map != NO_DEBUG_INFO_MAP) { return map.get(ctor); } - return null; } From 8c9383da7c9ce02408c4e22eb8b6fdc07043582d Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 15:00:00 +0100 Subject: [PATCH 090/311] BridgeMethodResolver properly handles bridge methods in interfaces Issue: SPR-9330 --- .../org/springframework/core/BridgeMethodResolver.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java b/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java index c16cdb39dc..1027d4dfc9 100644 --- a/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java +++ b/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; @@ -145,7 +144,7 @@ public abstract class BridgeMethodResolver { private static Method findGenericDeclaration(Method bridgeMethod) { // Search parent types for method that has same signature as bridge. Class superclass = bridgeMethod.getDeclaringClass().getSuperclass(); - while (!Object.class.equals(superclass)) { + while (superclass != null && !Object.class.equals(superclass)) { Method method = searchForMatch(superclass, bridgeMethod); if (method != null && !method.isBridge()) { return method; @@ -219,8 +218,6 @@ public abstract class BridgeMethodResolver { * @return whether signatures match as described */ public static boolean isVisibilityBridgeMethodPair(Method bridgeMethod, Method bridgedMethod) { - Assert.isTrue(bridgeMethod != null); - Assert.isTrue(bridgedMethod != null); if (bridgeMethod == bridgedMethod) { return true; } From 701c5f11100b56c4809d61bcb889294a1cb3eb3e Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 15:20:55 +0100 Subject: [PATCH 091/311] ContextLoader properly detects pre-refreshed WebApplicationContext Issue: SPR-9996 --- .../web/context/ContextLoader.java | 29 +++++++++++-------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java index 6afd42b16c..9880e9875e 100644 --- a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java +++ b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,11 +23,11 @@ import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; - import javax.servlet.ServletContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.access.BeanFactoryLocator; import org.springframework.beans.factory.access.BeanFactoryReference; @@ -280,7 +280,18 @@ public class ContextLoader { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { - configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)this.context, servletContext); + ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; + if (!cwac.isActive()) { + // The context has not yet been refreshed -> provide services such as + // setting the parent context, setting the application context id, etc + if (cwac.getParent() == null) { + // The context instance was injected without an explicit parent -> + // determine parent for root web application context, if any. + ApplicationContext parent = loadParentContext(servletContext); + cwac.setParent(parent); + } + configureAndRefreshWebApplicationContext(cwac, servletContext); + } } servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); @@ -333,9 +344,7 @@ public class ContextLoader { throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]"); } - ConfigurableWebApplicationContext wac = - (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); - return wac; + return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); } /** @@ -370,10 +379,6 @@ public class ContextLoader { } } - // Determine parent for root web application context, if any. - ApplicationContext parent = loadParentContext(sc); - - wac.setParent(parent); wac.setServletContext(sc); String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (initParameter != null) { @@ -472,11 +477,11 @@ public class ContextLoader { Class contextClass = applicationContext.getClass(); ArrayList> initializerInstances = - new ArrayList>(); + new ArrayList>(); for (Class> initializerClass : initializerClasses) { Class initializerContextClass = - GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class); + GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class); Assert.isAssignable(initializerContextClass, contextClass, String.format( "Could not add context initializer [%s] as its generic parameter [%s] " + "is not assignable from the type of application context used by this " + From cca255bc7964ede0cde75bfdea08ecba74f3a069 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 16:51:21 +0100 Subject: [PATCH 092/311] Added "exposeAccessContext" flag JndiRmiClientInterceptor/ProxyFactoryBean (for WebLogic) Issue: SPR-9428 --- .../rmi/JndiRmiClientInterceptor.java | 33 +++++++++++++++---- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java b/spring-context/src/main/java/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java index 8660e2cf5b..caa7f51452 100644 --- a/spring-context/src/main/java/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java +++ b/spring-context/src/main/java/org/springframework/remoting/rmi/JndiRmiClientInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,7 @@ package org.springframework.remoting.rmi; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.rmi.RemoteException; - +import javax.naming.Context; import javax.naming.NamingException; import javax.rmi.PortableRemoteObject; @@ -88,6 +88,8 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho private boolean refreshStubOnConnectFailure = false; + private boolean exposeAccessContext = false; + private Object cachedStub; private final Object stubMonitor = new Object(); @@ -166,6 +168,18 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho this.refreshStubOnConnectFailure = refreshStubOnConnectFailure; } + /** + * Set whether to expose the JNDI environment context for all access to the target + * RMI stub, i.e. for all method invocations on the exposed object reference. + *

    Default is "false", i.e. to only expose the JNDI context for object lookup. + * Switch this flag to "true" in order to expose the JNDI environment (including + * the authorization context) for each RMI invocation, as needed by WebLogic + * for RMI stubs with authorization requirements. + */ + public void setExposeAccessContext(boolean exposeAccessContext) { + this.exposeAccessContext = exposeAccessContext; + } + @Override public void afterPropertiesSet() throws NamingException { @@ -190,8 +204,8 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho else if (getServiceInterface() != null) { boolean isImpl = getServiceInterface().isInstance(remoteObj); logger.debug("Using service interface [" + getServiceInterface().getName() + - "] for JNDI RMI object [" + getJndiName() + "] - " + - (!isImpl ? "not " : "") + "directly implemented"); + "] for JNDI RMI object [" + getJndiName() + "] - " + + (!isImpl ? "not " : "") + "directly implemented"); } } if (this.cacheStub) { @@ -268,13 +282,15 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho * @see java.rmi.NoSuchObjectException */ public Object invoke(MethodInvocation invocation) throws Throwable { - Object stub = null; + Object stub; try { stub = getStub(); } catch (NamingException ex) { throw new RemoteLookupFailureException("JNDI lookup for RMI service [" + getJndiName() + "] failed", ex); } + + Context ctx = (this.exposeAccessContext ? getJndiTemplate().getContext() : null); try { return doInvoke(invocation, stub); } @@ -297,6 +313,9 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho throw ex; } } + finally { + getJndiTemplate().releaseContext(ctx); + } } /** @@ -354,7 +373,7 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho * @see #invoke */ protected Object refreshAndRetry(MethodInvocation invocation) throws Throwable { - Object freshStub = null; + Object freshStub; synchronized (this.stubMonitor) { this.cachedStub = null; freshStub = lookupStub(); @@ -426,7 +445,7 @@ public class JndiRmiClientInterceptor extends JndiObjectLocator implements Metho * @see org.springframework.remoting.support.RemoteInvocation */ protected Object doInvoke(MethodInvocation methodInvocation, RmiInvocationHandler invocationHandler) - throws RemoteException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { + throws RemoteException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (AopUtils.isToStringMethod(methodInvocation.getMethod())) { return "RMI invoker proxy for service URL [" + getJndiName() + "]"; From 944e1c95e6e6cbe83dd709fa3fe608f79b2c8f36 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 17:58:24 +0100 Subject: [PATCH 093/311] EhCacheManagerFactoryBean applies cacheManagerName ahead of creation (for EHCache 2.5 compatibility) Issue: SPR-9171 --- .../ehcache/EhCacheManagerFactoryBean.java | 54 ++++++++++++++----- .../cache/ehcache/EhCacheSupportTests.java | 3 +- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java index 8ae68321dc..a170eb84f8 100644 --- a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java +++ b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,9 +18,12 @@ package org.springframework.cache.ehcache; import java.io.IOException; import java.io.InputStream; +import java.lang.reflect.Method; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.config.ConfigurationFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -28,6 +31,8 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.io.Resource; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; /** * {@link FactoryBean} that exposes an EHCache {@link net.sf.ehcache.CacheManager} @@ -54,6 +59,10 @@ import org.springframework.core.io.Resource; */ public class EhCacheManagerFactoryBean implements FactoryBean, InitializingBean, DisposableBean { + // Check whether EHCache 2.1+ CacheManager.create(Configuration) method is available... + private static final Method createWithConfiguration = + ClassUtils.getMethodIfAvailable(CacheManager.class, "create", Configuration.class); + protected final Log logger = LogFactory.getLog(getClass()); private Resource configLocation; @@ -98,21 +107,42 @@ public class EhCacheManagerFactoryBean implements FactoryBean, Ini public void afterPropertiesSet() throws IOException, CacheException { logger.info("Initializing EHCache CacheManager"); - if (this.configLocation != null) { - InputStream is = this.configLocation.getInputStream(); - try { - this.cacheManager = (this.shared ? CacheManager.create(is) : new CacheManager(is)); + InputStream is = (this.configLocation != null ? this.configLocation.getInputStream() : null); + try { + // A bit convoluted for EHCache 1.x/2.0 compatibility. + // To be much simpler once we require EHCache 2.1+ + if (this.cacheManagerName != null) { + if (this.shared && createWithConfiguration == null) { + // No CacheManager.create(Configuration) method available before EHCache 2.1; + // can only set CacheManager name after creation. + this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create()); + this.cacheManager.setName(this.cacheManagerName); + } + else { + Configuration configuration = (is != null ? ConfigurationFactory.parseConfiguration(is) : + ConfigurationFactory.parseConfiguration()); + configuration.setName(this.cacheManagerName); + if (this.shared) { + this.cacheManager = (CacheManager) ReflectionUtils.invokeMethod(createWithConfiguration, null, configuration); + } + else { + this.cacheManager = new CacheManager(configuration); + } + } } - finally { + // For strict backwards compatibility: use simplest possible constructors... + else if (this.shared) { + this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create()); + } + else { + this.cacheManager = (is != null ? new CacheManager(is) : new CacheManager()); + } + } + finally { + if (is != null) { is.close(); } } - else { - this.cacheManager = (this.shared ? CacheManager.create() : new CacheManager()); - } - if (this.cacheManagerName != null) { - this.cacheManager.setName(this.cacheManagerName); - } } diff --git a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java index 646a679717..fcfe221642 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,6 +38,7 @@ public class EhCacheSupportTests extends TestCase { public void testLoadingBlankCacheManager() throws Exception { EhCacheManagerFactoryBean cacheManagerFb = new EhCacheManagerFactoryBean(); + cacheManagerFb.setCacheManagerName("myCacheManager"); assertEquals(CacheManager.class, cacheManagerFb.getObjectType()); assertTrue("Singleton property", cacheManagerFb.isSingleton()); cacheManagerFb.afterPropertiesSet(); From 87968e5a71929a4cce6f1fd4c0e2e194a631715a Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 18:01:33 +0100 Subject: [PATCH 094/311] Further preparations for 3.2.1 --- src/dist/changelog.txt | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 6f53ecc731..8c0d7fbfab 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -9,19 +9,28 @@ Changes in version 3.2.1 (2013-01-24) * SpEL support for static finals on interfaces (SPR-10125) * AnnotationAwareOrderComparator is able to sort Class objects as well (SPR-10152) * added dedicated sort method to AnnotationAwareOrderComparator (SPR-9625) +* BridgeMethodResolver properly handles bridge methods in interfaces (SPR-9330) +* LocalVariableTableParameterNameDiscoverer works for bridge methods as well (SPR-9429) +* CachedIntrospectionResults.clearClassLoader(null) removes cached classes for the system class loader (SPR-9189) * fixed QualifierAnnotationAutowireCandidateResolver's detection of custom qualifier annotations (SPR-10107) * fixed AbstractAutoProxyCreator to accept null bean names again (SPR-10108) * AbstractAdvisingBeanPostProcessor caches per bean target class, working for null bean names as well (SPR-10144) * MessageSourceResourceBundle overrides JDK 1.6 containsKey method, avoiding NPE in getKeys (SPR-10136) +* SpringBeanAutowiringInterceptor eagerly releases BeanFactory if post-construction fails (SPR-10013) +* added "exposeAccessContext" flag JndiRmiClientInterceptor/ProxyFactoryBean (for WebLogic; SPR-9428) +* MBeanExporter does not log warnings for manually unregistered MBeans (SPR-9451) * AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup (SPR-7955) -* spring-task-3.2.xsd allows for SpEL expressions in initial-delay attribute (SPR-10102) -* reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd (SPR-10177) +* EhCacheManagerFactoryBean applies cacheManagerName ahead of creation (for EHCache 2.5 compatibility; SPR-9171) * JDBC parameter binding uses JDBC 3.0 ParameterMetaData (if available) for type determination (SPR-10084) +* reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd (SPR-10177) +* spring-task-3.2.xsd allows for SpEL expressions in initial-delay attribute (SPR-10102) +* spring-jms-3.2.xsd allows for SpEL expressions in prefetch and receive-timeout attributes (SPR-9553) * JmsTemplate uses configured receiveTimeout if shorter than remaining transaction timeout (SPR-10109) * added MappingJackson2MessageConverter for JMS (SPR-10099) * MimeMessageHelper encodes attachment filename if not ASCII compliant (SPR-9258) * FreeMarkerConfigurationFactory properly supports TemplateLoaders when recreating Configurations (SPR-9389) * SpringContextResourceAdapter implements equals/hashCode according to the JCA 1.5 contract (SPR-9162) +* ContextLoader properly detects pre-refreshed WebApplicationContext (SPR-9996) Changes in version 3.2 GA (2012-12-13) From 5d9ad5b1d1ceb5e8d0ede2a7ede5203d94964ec2 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 18 Jan 2013 19:07:30 +0100 Subject: [PATCH 095/311] AbstractDriverBasedDataSource does not rely on Properties chaining anymore Issue: SPR-9461 --- .../datasource/AbstractDriverBasedDataSource.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java index 6df3d53e57..c7e7e19918 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/AbstractDriverBasedDataSource.java @@ -139,15 +139,18 @@ public abstract class AbstractDriverBasedDataSource extends AbstractDataSource { * @see java.sql.Driver#connect(String, java.util.Properties) */ protected Connection getConnectionFromDriver(String username, String password) throws SQLException { - Properties props = new Properties(); - props.putAll(getConnectionProperties()); + Properties mergedProps = new Properties(); + Properties connProps = getConnectionProperties(); + if (connProps != null) { + mergedProps.putAll(connProps); + } if (username != null) { - props.setProperty("user", username); + mergedProps.setProperty("user", username); } if (password != null) { - props.setProperty("password", password); + mergedProps.setProperty("password", password); } - return getConnectionFromDriver(props); + return getConnectionFromDriver(mergedProps); } /** From 24cc33306def7aff4aa2c797cd4aea320a4f8523 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Mon, 21 Jan 2013 11:05:50 +0100 Subject: [PATCH 096/311] Fix typo in reference documentation Issue: SPR-10171 --- src/reference/docbook/overview.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/overview.xml b/src/reference/docbook/overview.xml index a4de366ef8..9bef8ee488 100644 --- a/src/reference/docbook/overview.xml +++ b/src/reference/docbook/overview.xml @@ -362,7 +362,7 @@ TR: OK. Added to diagram.--> places: On the community download site http://www.springsource.org/downloads/community. + xl:href="http://www.springsource.org/download/community">http://www.springsource.org/download/community. Here you find all the Spring jars bundled together into a zip file for easy download. The names of the jars here since version 3.0 are in the form From d40c8cfc58298f3c5f0fea5870d0aed495ba3fb9 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Mon, 21 Jan 2013 11:21:44 +0100 Subject: [PATCH 097/311] Fix broken Castor URLs in ref docs and mapping XML Issue: SPR-10189 --- .../java/org/springframework/oxm/castor/package-info.java | 2 +- .../test/resources/org/springframework/oxm/castor/mapping.xml | 4 ++-- src/reference/docbook/oxm.xml | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-oxm/src/main/java/org/springframework/oxm/castor/package-info.java b/spring-oxm/src/main/java/org/springframework/oxm/castor/package-info.java index 42f8cdade2..1f1167ab09 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/castor/package-info.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/castor/package-info.java @@ -1,7 +1,7 @@ /** * - * Package providing integration of Castor within Springs O/X Mapping + * Package providing integration of Castor within Springs O/X Mapping * support * */ diff --git a/spring-oxm/src/test/resources/org/springframework/oxm/castor/mapping.xml b/spring-oxm/src/test/resources/org/springframework/oxm/castor/mapping.xml index e85971251c..f54e293fdf 100644 --- a/spring-oxm/src/test/resources/org/springframework/oxm/castor/mapping.xml +++ b/spring-oxm/src/test/resources/org/springframework/oxm/castor/mapping.xml @@ -1,5 +1,5 @@ - + Castor generated mapping file @@ -28,4 +28,4 @@ xmlns:tns="http://samples.springframework.org/flight"/> - \ No newline at end of file + diff --git a/src/reference/docbook/oxm.xml b/src/reference/docbook/oxm.xml index f5797b2c4b..00ae396620 100644 --- a/src/reference/docbook/oxm.xml +++ b/src/reference/docbook/oxm.xml @@ -438,7 +438,7 @@ public class Application { though a mapping file can be used to have more control over the behavior of Castor. - For more information on Castor, refer to the + For more information on Castor, refer to the Castor web site. The Spring integration classes reside in the org.springframework.oxm.castor package. @@ -462,7 +462,7 @@ public class Application { Although it is possible to rely on Castor's default marshalling behavior, it might be necessary to have more control over it. This can be accomplished using a Castor mapping file. For more information, refer - to Castor XML Mapping. + to Castor XML Mapping. The mapping can be set using the mappingLocation resource property, indicated From fc6377cc533df9fe719b5092cb7760c31645f633 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Mon, 21 Jan 2013 12:41:43 +0100 Subject: [PATCH 098/311] Add TimedSpringRunnerTests to performance test group Issue: SPR-9984 --- .../test/context/junit4/TimedSpringRunnerTests.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java index a3679ba75e..5594d3206c 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/TimedSpringRunnerTests.java @@ -25,6 +25,8 @@ import org.junit.runner.notification.RunNotifier; import org.junit.runners.JUnit4; import org.springframework.test.annotation.Timed; import org.springframework.test.context.TestExecutionListeners; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; /** * Verifies proper handling of the following in conjunction with the @@ -42,6 +44,7 @@ public class TimedSpringRunnerTests { @Test public void timedTests() throws Exception { + Assume.group(TestGroup.PERFORMANCE); Class testClass = TimedSpringRunnerTestCase.class; TrackingRunListener listener = new TrackingRunListener(); RunNotifier notifier = new RunNotifier(); From 4dc3fcecbd9b274398b73614e31d794b72799adf Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Mon, 21 Jan 2013 13:57:32 +0100 Subject: [PATCH 099/311] Ensure -PtestGroups is passed through to unit tests Issue: SPR-9984 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 84c2ce6286..a6359fcc49 100644 --- a/build.gradle +++ b/build.gradle @@ -67,7 +67,7 @@ configure(allprojects) { project -> test { systemProperty("java.awt.headless", "true") - systemProperty("testGroups", properties.get("testGroups")) + systemProperty("testGroups", project.properties.get("testGroups")) } repositories { From cb8dc73fbb326a82324cf797a0116786d54e99b0 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Mon, 21 Jan 2013 14:03:36 +0100 Subject: [PATCH 100/311] Attempt to repro ReflectionUtils performance issue Issue: SPR-10197 --- .../util/ReflectionUtilsTests.java | 54 +++++++++++++++---- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java index 6b791a154b..7d555076ba 100644 --- a/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java @@ -16,15 +16,6 @@ package org.springframework.util; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -33,10 +24,18 @@ import java.rmi.RemoteException; import java.util.LinkedList; import java.util.List; +import org.hamcrest.Matchers; + import org.junit.Ignore; import org.junit.Test; + +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; import org.springframework.tests.sample.objects.TestObject; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller @@ -347,6 +346,43 @@ public class ReflectionUtilsTests { assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1"))); } + @Test + public void getUniqueDeclaredMethods_isFastEnough() { + Assume.group(TestGroup.PERFORMANCE); + + @SuppressWarnings("unused") + class C { + void m00() { } void m01() { } void m02() { } void m03() { } void m04() { } + void m05() { } void m06() { } void m07() { } void m08() { } void m09() { } + void m10() { } void m11() { } void m12() { } void m13() { } void m14() { } + void m15() { } void m16() { } void m17() { } void m18() { } void m19() { } + void m20() { } void m21() { } void m22() { } void m23() { } void m24() { } + void m25() { } void m26() { } void m27() { } void m28() { } void m29() { } + void m30() { } void m31() { } void m32() { } void m33() { } void m34() { } + void m35() { } void m36() { } void m37() { } void m38() { } void m39() { } + void m40() { } void m41() { } void m42() { } void m43() { } void m44() { } + void m45() { } void m46() { } void m47() { } void m48() { } void m49() { } + void m50() { } void m51() { } void m52() { } void m53() { } void m54() { } + void m55() { } void m56() { } void m57() { } void m58() { } void m59() { } + void m60() { } void m61() { } void m62() { } void m63() { } void m64() { } + void m65() { } void m66() { } void m67() { } void m68() { } void m69() { } + void m70() { } void m71() { } void m72() { } void m73() { } void m74() { } + void m75() { } void m76() { } void m77() { } void m78() { } void m79() { } + void m80() { } void m81() { } void m82() { } void m83() { } void m84() { } + void m85() { } void m86() { } void m87() { } void m88() { } void m89() { } + void m90() { } void m91() { } void m92() { } void m93() { } void m94() { } + void m95() { } void m96() { } void m97() { } void m98() { } void m99() { } + } + + StopWatch sw = new StopWatch(); + sw.start(); + Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(C.class); + sw.stop(); + long totalMs = sw.getTotalTimeMillis(); + assertThat(methods.length, Matchers.greaterThan(100)); + assertThat(totalMs, Matchers.lessThan(10L)); + } + private static class ListSavingMethodCallback implements ReflectionUtils.MethodCallback { private List methodNames = new LinkedList(); From 8e1685caefae49ccd796ef9a8f707bc94d54680a Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 21 Jan 2013 11:55:31 -0500 Subject: [PATCH 101/311] Fix ClassCastException in TilesConfigurer Issue: SPR-10195 --- build.gradle | 3 + .../servlet/view/tiles3/TilesConfigurer.java | 76 +++++++++++-------- 2 files changed, 47 insertions(+), 32 deletions(-) diff --git a/build.gradle b/build.gradle index 7d147c1443..813816bdfd 100644 --- a/build.gradle +++ b/build.gradle @@ -613,6 +613,9 @@ project("spring-webmvc-tiles3") { optional("org.apache.tiles:tiles-jsp:3.0.1") { exclude group: "org.slf4j", module: "jcl-over-slf4j" } + optional("org.apache.tiles:tiles-extras:3.0.1") { + exclude group: "org.slf4j", module: "jcl-over-slf4j" + } optional("org.apache.tiles:tiles-el:3.0.1") { exclude group: "org.slf4j", module: "jcl-over-slf4j" } diff --git a/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java b/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java index f01f25dd1a..d23ac0033b 100644 --- a/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java +++ b/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,19 +32,21 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tiles.TilesContainer; import org.apache.tiles.TilesException; -import org.apache.tiles.access.TilesAccess; import org.apache.tiles.definition.DefinitionsFactory; import org.apache.tiles.definition.DefinitionsReader; import org.apache.tiles.definition.dao.BaseLocaleUrlDefinitionDAO; import org.apache.tiles.definition.dao.CachingLocaleUrlDefinitionDAO; import org.apache.tiles.definition.digester.DigesterDefinitionsReader; import org.apache.tiles.el.ELAttributeEvaluator; +import org.apache.tiles.el.ScopeELResolver; import org.apache.tiles.el.TilesContextBeanELResolver; import org.apache.tiles.el.TilesContextELResolver; import org.apache.tiles.evaluator.AttributeEvaluator; import org.apache.tiles.evaluator.AttributeEvaluatorFactory; import org.apache.tiles.evaluator.BasicAttributeEvaluatorFactory; import org.apache.tiles.evaluator.impl.DirectAttributeEvaluator; +import org.apache.tiles.extras.complete.CompleteAutoloadTilesContainerFactory; +import org.apache.tiles.extras.complete.CompleteAutoloadTilesInitializer; import org.apache.tiles.factory.AbstractTilesContainerFactory; import org.apache.tiles.factory.BasicTilesContainerFactory; import org.apache.tiles.impl.BasicTilesContainer; @@ -72,7 +74,9 @@ import org.springframework.web.context.ServletContextAware; *

    The TilesConfigurer simply configures a TilesContainer using a set of files * containing definitions, to be accessed by {@link TilesView} instances. This is a * Spring-based alternative (for usage in Spring configuration) to the Tiles-provided - * {@link org.apache.tiles.web.startup.TilesListener} (for usage in {@code web.xml}). + * {@code ServletContextListener} + * (e.g. {@link org.apache.tiles.extras.complete.CompleteAutoloadTilesListener} + * for usage in {@code web.xml}. * *

    TilesViews can be managed by any {@link org.springframework.web.servlet.ViewResolver}. * For simple convention-based view resolution, consider using {@link TilesViewResolver}. @@ -110,8 +114,6 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D private TilesInitializer tilesInitializer; - private boolean completeAutoload = false; - private String[] definitions; private boolean checkRefresh = false; @@ -154,17 +156,14 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D public void setCompleteAutoload(boolean completeAutoload) { if (completeAutoload) { try { - Class clazz = getClass().getClassLoader().loadClass( - "org.apache.tiles.extras.complete.CompleteAutoloadTilesInitializer"); - this.tilesInitializer = (TilesInitializer) clazz.newInstance(); + this.tilesInitializer = new SpringCompleteAutoloadTilesInitializer(); } catch (Exception ex) { - throw new IllegalStateException("Tiles-Extras 3.0 not available", ex); + throw new IllegalStateException("tiles-extras 3.x not available", ex); } } else { this.tilesInitializer = null; } - this.completeAutoload = completeAutoload; } /** @@ -192,7 +191,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D /** * Set the {@link org.apache.tiles.definition.DefinitionsFactory} implementation to use. - * Default is {@link org.apache.tiles.definition.UrlDefinitionsFactory}, + * Default is {@link org.apache.tiles.definition.UnresolvingLocaleDefinitionsFactory}, * operating on definition resource URLs. *

    Specify a custom DefinitionsFactory, e.g. a UrlDefinitionsFactory subclass, * to customize the creation of Tiles Definition objects. Note that such a @@ -204,8 +203,8 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D } /** - * Set the {@link org.apache.tiles.preparer.PreparerFactory} implementation to use. - * Default is {@link org.apache.tiles.preparer.BasicPreparerFactory}, creating + * Set the {@link org.apache.tiles.preparer.factory.PreparerFactory} implementation to use. + * Default is {@link org.apache.tiles.preparer.factory.BasicPreparerFactory}, creating * shared instances for specified preparer classes. *

    Specify {@link SimpleSpringPreparerFactory} to autowire * {@link org.apache.tiles.preparer.ViewPreparer} instances based on specified @@ -230,7 +229,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D * Set whether to use a MutableTilesContainer (typically the CachingTilesContainer * implementation) for this application. Default is "false". * @see org.apache.tiles.mgmt.MutableTilesContainer - * @see org.apache.tiles.mgmt.CachingTilesContainer + * @see org.apache.tiles.impl.mgmt.CachingTilesContainer */ public void setUseMutableTilesContainer(boolean useMutableTilesContainer) { this.useMutableTilesContainer = useMutableTilesContainer; @@ -246,26 +245,11 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D * @throws TilesException in case of setup failure */ public void afterPropertiesSet() throws TilesException { - - SpringWildcardServletTilesApplicationContext preliminaryContext = - new SpringWildcardServletTilesApplicationContext(this.servletContext); - + ApplicationContext preliminaryContext = new SpringWildcardServletTilesApplicationContext(this.servletContext); if (this.tilesInitializer == null) { this.tilesInitializer = new SpringTilesInitializer(); } this.tilesInitializer.initialize(preliminaryContext); - - if (this.completeAutoload) { - // We need to do this after initialization simply because we're reusing the - // original CompleteAutoloadTilesInitializer above. We cannot subclass - // CompleteAutoloadTilesInitializer when compiling against Tiles 2.1... - logger.debug("Registering Tiles 3.0 SpringLocaleResolver for complete-autoload setup"); - BasicTilesContainer container = (BasicTilesContainer) TilesAccess.getContainer(preliminaryContext); - BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(container.getDefinitionsFactory()); - if (bw.isWritableProperty("localeResolver")) { - bw.setPropertyValue("localeResolver", new SpringLocaleResolver()); - } - } } /** @@ -332,8 +316,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D if (definitionsFactoryClass != null) { DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass); if (factory instanceof org.apache.tiles.request.ApplicationContextAware) { - ((org.apache.tiles.request.ApplicationContextAware) factory) - .setApplicationContext(applicationContext); + ((org.apache.tiles.request.ApplicationContextAware) factory).setApplicationContext(applicationContext); } BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory); if (bw.isWritableProperty("localeResolver")) { @@ -380,6 +363,34 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D } } + private class SpringCompleteAutoloadTilesInitializer extends CompleteAutoloadTilesInitializer { + + @Override + protected AbstractTilesContainerFactory createContainerFactory(ApplicationContext context) { + return new SpringCompleteAutoloadTilesContainerFactory(); + } + } + + private class SpringCompleteAutoloadTilesContainerFactory extends CompleteAutoloadTilesContainerFactory { + + @Override + protected AttributeEvaluatorFactory createAttributeEvaluatorFactory( + ApplicationContext applicationContext, LocaleResolver resolver) { + return new BasicAttributeEvaluatorFactory(new DirectAttributeEvaluator()); + } + + @Override + public TilesContainer createContainer(ApplicationContext applicationContext) { + CachingTilesContainer cachingContainer = (CachingTilesContainer) super.createContainer(applicationContext); + BasicTilesContainer tilesContainer = (BasicTilesContainer) cachingContainer.getWrappedContainer(); + BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(tilesContainer.getDefinitionsFactory()); + if (bw.isWritableProperty("localeResolver")) { + bw.setPropertyValue("localeResolver", new SpringLocaleResolver()); + } + return tilesContainer; + } + } + private class TilesElActivator { @@ -405,6 +416,7 @@ public class TilesConfigurer implements ServletContextAware, InitializingBean, D private static class CompositeELResolverImpl extends CompositeELResolver { public CompositeELResolverImpl() { + add(new ScopeELResolver()); add(new TilesContextELResolver(new TilesContextBeanELResolver())); add(new TilesContextBeanELResolver()); add(new ArrayELResolver(false)); From e4fcad9f936ba492f28ec5f0421eea4b3f76f8aa Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 21 Jan 2013 12:34:56 -0500 Subject: [PATCH 102/311] Fix exception message about producible media types Issue: SPR-10175 --- .../annotation/AbstractMessageConverterMethodProcessor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java index ccdf7d3703..48cff20fe5 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java @@ -123,7 +123,7 @@ public abstract class AbstractMessageConverterMethodProcessor extends AbstractMe } } if (compatibleMediaTypes.isEmpty()) { - throw new HttpMediaTypeNotAcceptableException(allSupportedMediaTypes); + throw new HttpMediaTypeNotAcceptableException(producibleMediaTypes); } List mediaTypes = new ArrayList(compatibleMediaTypes); From 21becef1bdd36aac41c519798a772dbadb5d6973 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 21 Jan 2013 10:51:21 -0800 Subject: [PATCH 103/311] Support Date to String in JodaTimeConverters Update JodaTimeConverters in include support for Date to String conversion. The JodaTimeFormattingTests and DateFormattingTests have been extended to ensure that Date to String conversion is supported with or without Joda. Issue: SPR-10198 --- .../format/datetime/DateFormatterRegistrar.java | 4 ++-- .../format/datetime/joda/JodaTimeConverters.java | 14 +++++++++++++- .../format/datetime/DateFormattingTests.java | 12 ++++++++++-- .../datetime/joda/JodaTimeFormattingTests.java | 12 +++++++++++- 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java index eb413a6ea7..aedf118437 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -57,7 +57,7 @@ public class DateFormatterRegistrar implements FormatterRegistrar { * @param dateFormatter the date formatter */ public void setFormatter(DateFormatter dateFormatter) { - Assert.notNull(dateFormatter,"DateFormatter must not be null"); + Assert.notNull(dateFormatter, "DateFormatter must not be null"); this.dateFormatter = dateFormatter; } diff --git a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeConverters.java b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeConverters.java index 6943ad4241..b49b607255 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeConverters.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeConverters.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import org.springframework.format.datetime.DateFormatterRegistrar; * Installs lower-level type converters required to integrate Joda Time support into Spring's field formatting system. * * @author Keith Donald + * @author Phillip Webb * @since 3.0 */ final class JodaTimeConverters { @@ -55,6 +56,7 @@ final class JodaTimeConverters { registry.addConverter(new DateTimeToCalendarConverter()); registry.addConverter(new DateTimeToLongConverter()); registry.addConverter(new CalendarToReadableInstantConverter()); + registry.addConverter(new DateToReadableInstantConverter()); } @@ -159,4 +161,14 @@ final class JodaTimeConverters { } } + /** + * Used when printing a java.util.Date field with a ReadableInstantPrinter. + * @see MillisecondInstantPrinter + * @see JodaDateTimeFormatAnnotationFormatterFactory + */ + private static class DateToReadableInstantConverter implements Converter { + public ReadableInstant convert(Date source) { + return new DateTime(source); + } + } } diff --git a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java index 087e8e9521..5698ed0651 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,10 +30,10 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.MutablePropertyValues; import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; -import org.springframework.format.datetime.DateFormatterRegistrar; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; @@ -186,6 +186,14 @@ public class DateFormattingTests { assertEquals("10/31/09", binder.getBindingResult().getFieldValue("children[0].dateAnnotated")); } + @Test + public void dateToString() throws Exception { + Date date = new Date(); + Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); + String expected = new DateFormatter().print(date, Locale.US); + assertEquals(expected, actual); + } + @SuppressWarnings("unused") private static class SimpleDateBean { diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java index 597a3820b5..237df0509f 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import org.junit.Test; import org.springframework.beans.MutablePropertyValues; import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.core.convert.TypeDescriptor; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; @@ -46,6 +47,7 @@ import static org.junit.Assert.*; /** * @author Keith Donald * @author Juergen Hoeller + * @author Phillip Webb */ public class JodaTimeFormattingTests { @@ -456,6 +458,14 @@ public class JodaTimeFormattingTests { assertEquals("2009-10-31T07:00:00.000-05:00", binder.getBindingResult().getFieldValue("mutableDateTimeAnnotated")); } + @Test + public void dateToString() throws Exception { + Date date = new Date(); + Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); + String expected = JodaTimeContextHolder.getFormatter(org.joda.time.format.DateTimeFormat.shortDateTime(), Locale.US).print(new DateTime(date)); + assertEquals(expected, actual); + } + @SuppressWarnings("unused") private static class JodaTimeBean { From 0c56e86bfb7617b8a92ff187c9aec20c20db9da2 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 21 Jan 2013 13:23:59 -0500 Subject: [PATCH 104/311] Fix NPE in FormHttpMessageConverter Issue: SPR-10187 --- .../http/converter/FormHttpMessageConverter.java | 10 ++++++---- .../http/converter/FormHttpMessageConverterTests.java | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java index 0bbe671083..f66a38bf19 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java @@ -265,10 +265,12 @@ public class FormHttpMessageConverter implements HttpMessageConverter> entry : parts.entrySet()) { String name = entry.getKey(); for (Object part : entry.getValue()) { - writeBoundary(boundary, os); - HttpEntity entity = getEntity(part); - writePart(name, entity, os); - writeNewLine(os); + if (part != null) { + writeBoundary(boundary, os); + HttpEntity entity = getEntity(part); + writePart(name, entity, os); + writeNewLine(os); + } } } } diff --git a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java index 2344269b63..0792d6c6a8 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java @@ -112,6 +112,7 @@ public class FormHttpMessageConverterTests { parts.add("name 1", "value 1"); parts.add("name 2", "value 2+1"); parts.add("name 2", "value 2+2"); + parts.add("name 3", null); Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg"); parts.add("logo", logo); From 902a136b6e7accf4aa4c8f6be1988e2cecb000ef Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 21 Jan 2013 14:41:31 -0500 Subject: [PATCH 105/311] Add helpful error message to DispServlet initializer Issue: SPR-10168 --- .../support/AbstractDispatcherServletInitializer.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java index ae16bdb994..d6e6d01053 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/support/AbstractDispatcherServletInitializer.java @@ -94,6 +94,11 @@ public abstract class AbstractDispatcherServletInitializer ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet); + + Assert.notNull(registration, + "Failed to register servlet with name '" + servletName + "'." + + "Check if there is another servlet registered under the same name."); + registration.setLoadOnStartup(1); registration.addMapping(getServletMappings()); registration.setAsyncSupported(isAsyncSupported()); From 660458a649e6158a9d772bba06326887995b60c4 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Mon, 21 Jan 2013 14:52:41 -0500 Subject: [PATCH 106/311] Fix init order issue in RequestMappingHandlerMapping Issue: SPR-10173 --- .../RequestMappingHandlerMapping.java | 2 +- .../RequestMappingHandlerMappingTests.java | 50 ++++++++++++++++++- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java index 5700b8def7..bb9ddd72b1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping.java @@ -157,10 +157,10 @@ public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMappi @Override public void afterPropertiesSet() { - super.afterPropertiesSet(); if (this.useRegisteredSuffixPatternMatch) { this.fileExtensions.addAll(contentNegotiationManager.getAllFileExtensions()); } + super.afterPropertiesSet(); } /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java index 5c4d0776a4..63fce21fa7 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMappingTests.java @@ -15,20 +15,28 @@ */ package org.springframework.web.servlet.mvc.method.annotation; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import org.junit.Before; import org.junit.Test; import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; import org.springframework.util.StringValueResolver; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.accept.PathExtensionContentNegotiationStrategy; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.context.support.StaticWebApplicationContext; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; /** * Tests for {@link RequestMappingHandlerMapping}. @@ -63,6 +71,35 @@ public class RequestMappingHandlerMappingTests { assertEquals(Arrays.asList("json"), this.handlerMapping.getFileExtensions()); } + @Test + public void useRegsiteredSuffixPatternMatchInitialization() { + + Map fileExtensions = Collections.singletonMap("json", MediaType.APPLICATION_JSON); + PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(fileExtensions); + ContentNegotiationManager manager = new ContentNegotiationManager(strategy); + + final Set extensions = new HashSet(); + + RequestMappingHandlerMapping hm = new RequestMappingHandlerMapping() { + @Override + protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { + extensions.addAll(getFileExtensions()); + return super.getMappingForMethod(method, handlerType); + } + }; + + StaticWebApplicationContext wac = new StaticWebApplicationContext(); + wac.registerSingleton("testController", TestController.class); + wac.refresh(); + + hm.setContentNegotiationManager(manager); + hm.setUseRegisteredSuffixPatternMatch(true); + hm.setApplicationContext(wac); + hm.afterPropertiesSet(); + + assertEquals(Collections.singleton("json"), extensions); + } + @Test public void useSuffixPatternMatch() { assertTrue(this.handlerMapping.useSuffixPatternMatch()); @@ -93,4 +130,13 @@ public class RequestMappingHandlerMappingTests { assertArrayEquals(new String[] { "/foo", "/foo/bar" }, result); } + + @Controller + static class TestController { + + @RequestMapping + public void handle() { + } + } + } From d9a4fb410d6608260a597b1d72b9153c585caa5d Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 15:56:08 +0100 Subject: [PATCH 107/311] Introduce "dummy" Environment implementation For testing purposes in which an Environment implementation is required but a ConfigurableEnvironment is not desirable. All methods are no-ops and return null, therefore NPEs are likely. --- .../core/env/DummyEnvironment.java | 75 +++++++++++++++++++ .../web/servlet/DispatcherServletTests.java | 17 ++--- 2 files changed, 82 insertions(+), 10 deletions(-) create mode 100644 spring-core/src/test/java/org/springframework/core/env/DummyEnvironment.java diff --git a/spring-core/src/test/java/org/springframework/core/env/DummyEnvironment.java b/spring-core/src/test/java/org/springframework/core/env/DummyEnvironment.java new file mode 100644 index 0000000000..88d9347dfa --- /dev/null +++ b/spring-core/src/test/java/org/springframework/core/env/DummyEnvironment.java @@ -0,0 +1,75 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.core.env; + +public class DummyEnvironment implements Environment { + + public boolean containsProperty(String key) { + return false; + } + + public String getProperty(String key) { + return null; + } + + public String getProperty(String key, String defaultValue) { + return null; + } + + public T getProperty(String key, Class targetType) { + return null; + } + + public T getProperty(String key, Class targetType, T defaultValue) { + return null; + } + + public Class getPropertyAsClass(String key, Class targetType) { + return null; + } + + public String getRequiredProperty(String key) throws IllegalStateException { + return null; + } + + public T getRequiredProperty(String key, Class targetType) + throws IllegalStateException { + return null; + } + + public String resolvePlaceholders(String text) { + return null; + } + + public String resolveRequiredPlaceholders(String text) + throws IllegalArgumentException { + return null; + } + + public String[] getActiveProfiles() { + return null; + } + + public String[] getDefaultProfiles() { + return null; + } + + public boolean acceptsProfiles(String... profiles) { + return false; + } + +} diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index 147875e4ca..bb2d0a089b 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -16,12 +16,6 @@ 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; @@ -36,15 +30,15 @@ import junit.framework.TestCase; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.DefaultMessageSourceResolvable; import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.StandardEnvironment; +import org.springframework.core.env.DummyEnvironment; import org.springframework.mock.web.test.MockHttpServletRequest; import org.springframework.mock.web.test.MockHttpServletResponse; import org.springframework.mock.web.test.MockServletConfig; import org.springframework.mock.web.test.MockServletContext; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.web.bind.EscapedErrors; import org.springframework.web.context.ConfigurableWebEnvironment; import org.springframework.web.context.ServletConfigAwareBean; @@ -65,6 +59,9 @@ import org.springframework.web.servlet.theme.AbstractThemeResolver; 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 @@ -842,8 +839,8 @@ public class DispatcherServletTests extends TestCase { servlet.setEnvironment(env1); // should succeed assertThat(servlet.getEnvironment(), sameInstance(env1)); try { - servlet.setEnvironment(new StandardEnvironment()); - fail("expected exception"); + servlet.setEnvironment(new DummyEnvironment()); + fail("expected IllegalArgumentException for non-configurable Environment"); } catch (IllegalArgumentException ex) { } From 3cdb866bda078a24d3fccb36b08a449a970a524f Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Fri, 4 Jan 2013 15:47:28 +0100 Subject: [PATCH 108/311] Relax ConfigurableWebEnvironment signatures ConfigurableWebEnvironment was introduced in 3.2.0.M1 with SPR-9439 in order to break a cyclic dependency. At the same time, certain signatures such as AbstractRefreshableWebApplicationContext#getEnviroment and GenericWebApplicationContext#getEnvironment were updated to take advantage of covariant return types and return this newer, more narrow type and providing cast-free calls to ConfigurableWebEnvironment methods where necessary. Similar changes were made to HttpServletBean in 3.2.0.M2 with SPR-9763. Narrowing #getEnvironment signatures in this fashion required enforcing at the #setEnvironment level that any Environment instance provided (explicitly or via the EnvironmentAware callback) must be an instance of ConfigurableWebEnvironment. This is a reasonable assertion in typical web application scenarios, but as SPR-10138 demonstrates, there are valid use cases in which one may want or need to inject a non-web ConfigurableEnvironment variant, e.g. during automated unit/integration testing. On review, it was never strictly necessary to narrow #getEnvironment signatures, although doing so did provided convenience and type safety. In order to maintain as flexible and backward-compatible an arrangement as possible, this commit relaxes these #getEnvironment signatures back to their original, pre-3.2 state. Namely, they now return ConfigurableEnvironment as opposed to ConfigurableWebEnvironment, and in accordance, all instanceof assertions have been removed or relaxed to ensure that injected Environment instances are of type ConfigurableEnvironment. These changes have been verified against David Winterfeldt's Spring by Example spring-rest-services project, as described at SPR-10138. Issue: SPR-10138, SPR-9763, SPR-9439 --- .../ConfigurableWebApplicationContext.java | 7 +------ .../web/context/ContextLoader.java | 6 +++++- ...tractRefreshableWebApplicationContext.java | 18 ++++++------------ .../support/GenericWebApplicationContext.java | 17 ++++++----------- .../support/StaticWebApplicationContext.java | 13 +------------ .../web/servlet/FrameworkServlet.java | 9 +++++++-- .../web/servlet/HttpServletBean.java | 19 +++++++++---------- .../web/servlet/DispatcherServletTests.java | 2 +- 8 files changed, 36 insertions(+), 55 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java b/spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java index a6185a81e8..cba5e1dbc3 100644 --- a/spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java +++ b/spring-web/src/main/java/org/springframework/web/context/ConfigurableWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,11 +71,6 @@ public interface ConfigurableWebApplicationContext extends WebApplicationContext */ ServletConfig getServletConfig(); - /** - * Return the {@link ConfigurableWebEnvironment} used by this web application context. - */ - ConfigurableWebEnvironment getEnvironment(); - /** * Set the namespace for this web application context, * to be used for building a default context config location. diff --git a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java index 9880e9875e..69d812da37 100644 --- a/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java +++ b/spring-web/src/main/java/org/springframework/web/context/ContextLoader.java @@ -38,6 +38,7 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.access.ContextSingletonBeanFactoryLocator; import org.springframework.core.GenericTypeResolver; import org.springframework.core.annotation.AnnotationAwareOrderComparator; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PropertiesLoaderUtils; import org.springframework.util.Assert; @@ -490,7 +491,10 @@ public class ContextLoader { initializerInstances.add(BeanUtils.instantiateClass(initializerClass)); } - applicationContext.getEnvironment().initPropertySources(servletContext, null); + ConfigurableEnvironment env = applicationContext.getEnvironment(); + if (env instanceof ConfigurableWebEnvironment) { + ((ConfigurableWebEnvironment)env).initPropertySources(servletContext, null); + } Collections.sort(initializerInstances, new AnnotationAwareOrderComparator()); for (ApplicationContextInitializer initializer : initializerInstances) { diff --git a/spring-web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java b/spring-web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java index f36bddc316..92b1f7907a 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.ui.context.Theme; import org.springframework.ui.context.ThemeSource; import org.springframework.ui.context.support.UiApplicationContextUtils; -import org.springframework.util.Assert; import org.springframework.web.context.ConfigurableWebApplicationContext; import org.springframework.web.context.ConfigurableWebEnvironment; import org.springframework.web.context.ServletConfigAware; @@ -157,15 +156,6 @@ public abstract class AbstractRefreshableWebApplicationContext extends AbstractR return new StandardServletEnvironment(); } - @Override - public ConfigurableWebEnvironment getEnvironment() { - ConfigurableEnvironment env = super.getEnvironment(); - Assert.isInstanceOf(ConfigurableWebEnvironment.class, env, - "ConfigurableWebApplicationContext environment must be of type " + - "ConfigurableWebEnvironment"); - return (ConfigurableWebEnvironment) env; - } - /** * Register request/session scopes, a {@link ServletContextAwareProcessor}, etc. */ @@ -212,7 +202,11 @@ public abstract class AbstractRefreshableWebApplicationContext extends AbstractR @Override protected void initPropertySources() { super.initPropertySources(); - this.getEnvironment().initPropertySources(this.servletContext, this.servletConfig); + ConfigurableEnvironment env = this.getEnvironment(); + if (env instanceof ConfigurableWebEnvironment) { + ((ConfigurableWebEnvironment)env).initPropertySources( + this.servletContext, this.servletConfig); + } } public Theme getTheme(String themeName) { diff --git a/spring-web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java b/spring-web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java index ac87960cd0..d30d3aef84 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -147,15 +147,6 @@ public class GenericWebApplicationContext extends GenericApplicationContext return new StandardServletEnvironment(); } - @Override - public ConfigurableWebEnvironment getEnvironment() { - ConfigurableEnvironment env = super.getEnvironment(); - Assert.isInstanceOf(ConfigurableWebEnvironment.class, env, - "ConfigurableWebApplicationContext environment must be of type " + - "ConfigurableWebEnvironment"); - return (ConfigurableWebEnvironment) env; - } - /** * Register ServletContextAwareProcessor. * @see ServletContextAwareProcessor @@ -202,7 +193,11 @@ public class GenericWebApplicationContext extends GenericApplicationContext @Override protected void initPropertySources() { super.initPropertySources(); - this.getEnvironment().initPropertySources(this.servletContext, null); + ConfigurableEnvironment env = this.getEnvironment(); + if (env instanceof ConfigurableWebEnvironment) { + ((ConfigurableWebEnvironment)env).initPropertySources( + this.servletContext, null); + } } public Theme getTheme(String themeName) { diff --git a/spring-web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java b/spring-web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java index 5de71bda60..5d26a434e3 100644 --- a/spring-web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java +++ b/spring-web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,9 +27,7 @@ import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.ui.context.Theme; import org.springframework.ui.context.ThemeSource; import org.springframework.ui.context.support.UiApplicationContextUtils; -import org.springframework.util.Assert; import org.springframework.web.context.ConfigurableWebApplicationContext; -import org.springframework.web.context.ConfigurableWebEnvironment; import org.springframework.web.context.ServletConfigAware; import org.springframework.web.context.ServletContextAware; @@ -169,15 +167,6 @@ public class StaticWebApplicationContext extends StaticApplicationContext return new StandardServletEnvironment(); } - @Override - public ConfigurableWebEnvironment getEnvironment() { - ConfigurableEnvironment env = super.getEnvironment(); - Assert.isInstanceOf(ConfigurableWebEnvironment.class, env, - "ConfigurableWebApplication environment must be of type " + - "ConfigurableWebEnvironment"); - return (ConfigurableWebEnvironment) env; - } - /** * Initialize the theme capability. */ diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java index ca2a919043..3dca4eda94 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,11 +39,13 @@ import org.springframework.context.i18n.LocaleContext; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.context.i18n.SimpleLocaleContext; import org.springframework.core.annotation.AnnotationAwareOrderComparator; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.context.ConfigurableWebApplicationContext; +import org.springframework.web.context.ConfigurableWebEnvironment; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.context.request.RequestAttributes; @@ -638,7 +640,10 @@ public abstract class FrameworkServlet extends HttpServletBean { // the context is refreshed; do it eagerly here to ensure servlet property sources // are in place for use in any post-processing or initialization that occurs // below prior to #refresh - wac.getEnvironment().initPropertySources(getServletContext(), getServletConfig()); + ConfigurableEnvironment env = wac.getEnvironment(); + if (env instanceof ConfigurableWebEnvironment) { + ((ConfigurableWebEnvironment)env).initPropertySources(getServletContext(), getServletConfig()); + } postProcessWebApplicationContext(wac); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java index 044b56d2ae..bcd3a4d160 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/HttpServletBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import javax.servlet.http.HttpServlet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; @@ -35,6 +34,7 @@ import org.springframework.beans.PropertyAccessorFactory; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; import org.springframework.context.EnvironmentAware; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.core.env.EnvironmentCapable; import org.springframework.core.io.Resource; @@ -42,9 +42,8 @@ import org.springframework.core.io.ResourceEditor; import org.springframework.core.io.ResourceLoader; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import org.springframework.web.context.ConfigurableWebEnvironment; -import org.springframework.web.context.support.StandardServletEnvironment; import org.springframework.web.context.support.ServletContextResourceLoader; +import org.springframework.web.context.support.StandardServletEnvironment; /** * Simple extension of {@link javax.servlet.http.HttpServlet} which treats @@ -91,7 +90,7 @@ public abstract class HttpServletBean extends HttpServlet */ private final Set requiredProperties = new HashSet(); - private ConfigurableWebEnvironment environment; + private ConfigurableEnvironment environment; /** @@ -187,11 +186,11 @@ public abstract class HttpServletBean extends HttpServlet /** * {@inheritDoc} * @throws IllegalArgumentException if environment is not assignable to - * {@code ConfigurableWebEnvironment}. + * {@code ConfigurableEnvironment}. */ public void setEnvironment(Environment environment) { - Assert.isInstanceOf(ConfigurableWebEnvironment.class, environment); - this.environment = (ConfigurableWebEnvironment)environment; + Assert.isInstanceOf(ConfigurableEnvironment.class, environment); + this.environment = (ConfigurableEnvironment) environment; } /** @@ -199,7 +198,7 @@ public abstract class HttpServletBean extends HttpServlet *

    If {@code null}, a new environment will be initialized via * {@link #createEnvironment()}. */ - public ConfigurableWebEnvironment getEnvironment() { + public ConfigurableEnvironment getEnvironment() { if (this.environment == null) { this.environment = this.createEnvironment(); } @@ -210,7 +209,7 @@ public abstract class HttpServletBean extends HttpServlet * Create and return a new {@link StandardServletEnvironment}. Subclasses may override * in order to configure the environment or specialize the environment type returned. */ - protected ConfigurableWebEnvironment createEnvironment() { + protected ConfigurableEnvironment createEnvironment() { return new StandardServletEnvironment(); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index bb2d0a089b..b73e69ae6f 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -833,7 +833,7 @@ public class DispatcherServletTests extends TestCase { public void testEnvironmentOperations() { DispatcherServlet servlet = new DispatcherServlet(); - ConfigurableWebEnvironment defaultEnv = servlet.getEnvironment(); + ConfigurableEnvironment defaultEnv = servlet.getEnvironment(); assertThat(defaultEnv, notNullValue()); ConfigurableEnvironment env1 = new StandardServletEnvironment(); servlet.setEnvironment(env1); // should succeed From 2a41de00e355ce1d4e277111b8c93d6fa2dc0020 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 22 Jan 2013 12:09:00 +0100 Subject: [PATCH 109/311] Polish Javadoc in Spring MVC async support This commit fixes some typographical and grammatical errors in various classes in Spring MVC's async support. --- .../web/context/request/async/DeferredResult.java | 6 +++--- .../web/context/request/async/WebAsyncManager.java | 10 +++++----- .../web/context/request/async/WebAsyncTask.java | 12 ++++++------ .../config/annotation/AsyncSupportConfigurer.java | 12 ++++++------ 4 files changed, 20 insertions(+), 20 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java index 4da20dd40b..22ea83f458 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,13 +32,13 @@ import org.springframework.web.context.request.NativeWebRequest; *

    Subclasses can extend this class to easily associate additional data or * behavior with the {@link DeferredResult}. For example, one might want to * associate the user used to create the {@link DeferredResult} by extending the - * class and adding an addition property for the user. In this way, the user + * class and adding an additional property for the user. In this way, the user * could easily be accessed later without the need to use a data structure to do * the mapping. * *

    An example of associating additional behavior to this class might be * realized by extending the class to implement an additional interface. For - * example, one might want to implement a {@link Comparable} so that when the + * example, one might want to implement {@link Comparable} so that when the * {@link DeferredResult} is added to a {@link PriorityQueue} it is handled in * the correct order. * diff --git a/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java b/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java index 2e104d8e75..8c79b4230f 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,9 +37,9 @@ import org.springframework.web.util.UrlPathHelper; * as an SPI and not typically used directly by application classes. * *

    An async scenario starts with request processing as usual in a thread (T1). - * Concurrent request handling can be innitiated by calling - * {@linkplain #startCallableProcessing(Callable, Object...) startCallableProcessing} or - * {@linkplain #startDeferredResultProcessing(DeferredResult, Object...) startDeferredResultProcessing} + * Concurrent request handling can be initiated by calling + * {@link #startCallableProcessing(Callable, Object...) startCallableProcessing} or + * {@link #startDeferredResultProcessing(DeferredResult, Object...) startDeferredResultProcessing}, * both of which produce a result in a separate thread (T2). The result is saved * and the request dispatched to the container, to resume processing with the saved * result in a third thread (T3). Within the dispatched thread (T3), the saved @@ -263,7 +263,7 @@ public final class WebAsyncManager { * the timeout value of the {@code AsyncWebRequest} before delegating to * {@link #startCallableProcessing(Callable, Object...)}. * - * @param webAsyncTask an WebAsyncTask containing the target {@code Callable} + * @param webAsyncTask a WebAsyncTask containing the target {@code Callable} * @param processingContext additional context to save that can be accessed * via {@link #getConcurrentResultContext()} * @throws Exception If concurrent processing failed to start diff --git a/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncTask.java b/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncTask.java index 15cfdc96ee..59fa985acb 100644 --- a/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncTask.java +++ b/spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,7 +46,7 @@ public class WebAsyncTask { /** - * Create an {@code WebAsyncTask} wrapping the given {@link Callable}. + * Create a {@code WebAsyncTask} wrapping the given {@link Callable}. * @param callable the callable for concurrent handling */ public WebAsyncTask(Callable callable) { @@ -54,7 +54,7 @@ public class WebAsyncTask { } /** - * Create an {@code WebAsyncTask} with a timeout value and a {@link Callable}. + * Create a {@code WebAsyncTask} with a timeout value and a {@link Callable}. * @param timeout timeout value in milliseconds * @param callable the callable for concurrent handling */ @@ -63,7 +63,7 @@ public class WebAsyncTask { } /** - * Create an {@code WebAsyncTask} with a timeout value, an executor name, and a {@link Callable}. + * Create a {@code WebAsyncTask} with a timeout value, an executor name, and a {@link Callable}. * @param timeout timeout value in milliseconds; ignored if {@code null} * @param callable the callable for concurrent handling */ @@ -73,7 +73,7 @@ public class WebAsyncTask { } /** - * Create an {@code WebAsyncTask} with a timeout value, an executor instance, and a Callable. + * Create a {@code WebAsyncTask} with a timeout value, an executor instance, and a Callable. * @param timeout timeout value in milliseconds; ignored if {@code null} * @param callable the callable for concurrent handling */ @@ -113,7 +113,7 @@ public class WebAsyncTask { return this.executor; } else if (this.executorName != null) { - Assert.state(this.beanFactory != null, "A BeanFactory is required to look up an task executor bean"); + Assert.state(this.beanFactory != null, "A BeanFactory is required to look up a task executor bean"); return this.beanFactory.getBean(this.executorName, AsyncTaskExecutor.class); } else { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java index 07d2b1a87e..53e4893f99 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/AsyncSupportConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,7 @@ import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; /** - * Helps with configuring a options for asynchronous request processing. + * Helps with configuring options for asynchronous request processing. * * @author Rossen Stoyanchev * @since 3.2 @@ -50,9 +50,9 @@ public class AsyncSupportConfigurer { /** * Set the default {@link AsyncTaskExecutor} to use when a controller method * returns a {@link Callable}. Controller methods can override this default on - * a per-request basis by returning an {@link WebAsyncTask}. + * a per-request basis by returning a {@link WebAsyncTask}. * - *

    By default a {@link SimpleAsyncTaskExecutor} instance is used and it's + *

    By default a {@link SimpleAsyncTaskExecutor} instance is used, and it's * highly recommended to change that default in production since the simple * executor does not re-use threads. * @@ -79,7 +79,7 @@ public class AsyncSupportConfigurer { } /** - * Configure lifecycle intercepters with callbacks around concurrent request + * Configure lifecycle interceptors with callbacks around concurrent request * execution that starts when a controller returns a * {@link java.util.concurrent.Callable}. * @@ -92,7 +92,7 @@ public class AsyncSupportConfigurer { } /** - * Configure lifecycle intercepters with callbacks around concurrent request + * Configure lifecycle interceptors with callbacks around concurrent request * execution that starts when a controller returns a {@link DeferredResult}. * * @param interceptors the interceptors to register From 3a626f93197d7f0fd4266d9877550a8d330017e5 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 22 Jan 2013 14:14:15 +0100 Subject: [PATCH 110/311] Support XML properties in ResourcePropertySource JDK 5 introduced an XML-based properties file syntax. This commit ensures that when such files are supplied as the underlying resource for a ResourcePropertySource instance, they are routed appropriately to Properties#loadFromXML as opposed to Properties#load. Issue: SPR-9896 --- .../core/io/support/ResourcePropertySource.java | 16 +++++++++++++--- .../java/org/springframework/core/io/example.xml | 6 ++++++ .../io/support/ResourcePropertySourceTests.java | 13 ++++++++++++- 3 files changed, 31 insertions(+), 4 deletions(-) create mode 100644 spring-core/src/test/java/org/springframework/core/io/example.xml diff --git a/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java b/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java index f67a457970..705d8d44e7 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,11 @@ import org.springframework.util.StringUtils; /** * Subclass of {@link PropertiesPropertySource} that loads a {@link Properties} * object from a given {@link org.springframework.core.io.Resource} or resource location such as - * {@code "classpath:/com/myco/foo.properties"} or {@code "file:/path/to/file.properties"}. + * {@code "classpath:/com/myco/foo.properties"} or {@code "file:/path/to/file.xml"}. + * Both traditional and XML-based properties file formats are supported, however in order + * for XML processing to take effect, the underlying {@code Resource}'s + * {@link org.springframework.core.io.Resource#getFilename() getFilename()} method must + * return non-{@code null} and end in ".xml". * * @author Chris Beams * @since 3.1 @@ -99,7 +103,13 @@ public class ResourcePropertySource extends PropertiesPropertySource { private static Properties loadPropertiesForResource(Resource resource) throws IOException { Properties props = new Properties(); InputStream is = resource.getInputStream(); - props.load(is); + String filename = resource.getFilename(); + if (filename != null && filename.endsWith(".xml")) { + props.loadFromXML(is); + } + else { + props.load(is); + } try { is.close(); } catch (IOException ex) { diff --git a/spring-core/src/test/java/org/springframework/core/io/example.xml b/spring-core/src/test/java/org/springframework/core/io/example.xml new file mode 100644 index 0000000000..1d638537e1 --- /dev/null +++ b/spring-core/src/test/java/org/springframework/core/io/example.xml @@ -0,0 +1,6 @@ + + + + bar + + diff --git a/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java b/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java index 1b77a9f542..1bbc3cb2a1 100644 --- a/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java +++ b/spring-core/src/test/java/org/springframework/core/io/support/ResourcePropertySourceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,6 +39,10 @@ public class ResourcePropertySourceTests { private static final String PROPERTIES_LOCATION = "classpath:" + PROPERTIES_PATH; private static final String PROPERTIES_RESOURCE_DESCRIPTION = "class path resource [" + PROPERTIES_PATH + "]"; + private static final String XML_PROPERTIES_PATH = "org/springframework/core/io/example.xml"; + private static final String XML_PROPERTIES_LOCATION = "classpath:" + XML_PROPERTIES_PATH; + private static final String XML_PROPERTIES_RESOURCE_DESCRIPTION = "class path resource [" + XML_PROPERTIES_PATH + "]"; + @Test public void withLocationAndGeneratedName() throws IOException { PropertySource ps = new ResourcePropertySource(PROPERTIES_LOCATION); @@ -46,6 +50,13 @@ public class ResourcePropertySourceTests { assertThat(ps.getName(), is(PROPERTIES_RESOURCE_DESCRIPTION)); } + @Test + public void xmlWithLocationAndGeneratedName() throws IOException { + PropertySource ps = new ResourcePropertySource(XML_PROPERTIES_LOCATION); + assertEquals(ps.getProperty("foo"), "bar"); + assertThat(ps.getName(), is(XML_PROPERTIES_RESOURCE_DESCRIPTION)); + } + @Test public void withLocationAndExplicitName() throws IOException { PropertySource ps = new ResourcePropertySource("ps1", PROPERTIES_LOCATION); From d3f4528905b2c6277d1b169f8570591418c57350 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 22 Jan 2013 16:02:31 +0100 Subject: [PATCH 111/311] Remove additional xsd versions from reference docs A few versioned xsd references still existed in xsd-configuration.xml; this commit removes them, completing the work for SPR-10010 Issue: SPR-10010 --- src/reference/docbook/xsd-configuration.xml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/reference/docbook/xsd-configuration.xml b/src/reference/docbook/xsd-configuration.xml index f57e766e06..a78556a27c 100644 --- a/src/reference/docbook/xsd-configuration.xml +++ b/src/reference/docbook/xsd-configuration.xml @@ -679,7 +679,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem covered in the chapter entitled . You are strongly encouraged to look at the - 'spring-tx-3.0.xsd' file that ships with the Spring + 'spring-tx.xsd' file that ships with the Spring distribution. This file is (of course), the XML Schema for Spring's transaction configuration, and covers all of the various tags in the tx namespace, including attribute defaults and @@ -812,7 +812,7 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem Spring as they are currently undergoing review. If you are a third party tool vendor and you would like to contribute to this review process, then do mail the Spring mailing list. The currently supported tool - tags can be found in the file 'spring-tool-3.0.xsd' in the + tags can be found in the file 'spring-tool.xsd' in the 'src/org/springframework/beans/factory/xml' directory of the Spring source distribution.

@@ -931,8 +931,8 @@ http://www.springframework.org/schema/beans http://www.springframework.org/schem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" -http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd -http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> +http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd +http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> ]]> @@ -1053,8 +1053,8 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" - http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd - http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> ]]> @@ -1138,7 +1138,7 @@ http://www.springframework.org/schema/util http://www.springframework.org/schema relevant XSD file. As can be seen in the following screenshot, the 'http://www.springframework.org/schema/util' namespace is being associated with the file resource - 'C:\bench\spring\src\org\springframework\beans\factory\xml\spring-util-3.0.xsd'. + 'C:\bench\spring\src\org\springframework\beans\factory\xml\spring-util.xsd'. From 40ed4e78bee40dbf2afc12b0ac2fa8d12bb60b35 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 22 Jan 2013 11:54:31 -0500 Subject: [PATCH 112/311] Make UriComponents Serializable Issue: SPR-10186 --- .../java/org/springframework/web/util/UriComponents.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponents.java b/spring-web/src/main/java/org/springframework/web/util/UriComponents.java index f04c5f695b..2a2b300bfa 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponents.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,7 @@ package org.springframework.web.util; +import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.Arrays; @@ -38,7 +39,7 @@ import org.springframework.util.MultiValueMap; * @since 3.1 * @see UriComponentsBuilder */ -public abstract class UriComponents { +public abstract class UriComponents implements Serializable { private static final String DEFAULT_ENCODING = "UTF-8"; From 692ced8046f40facaa15fe9ad5a8d2cf56852794 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 22 Jan 2013 14:15:22 -0500 Subject: [PATCH 113/311] Fix typo in reference docs Issue: SPR-10204 --- src/reference/docbook/mvc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index f4d3e3e802..c8aebb4f8a 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -5110,7 +5110,7 @@ public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { - configurer.setFavorPathExtension(false).setFavorParameter(true); + configurer.favorPathExtension(false).favorParameter(true); } } From c1a4f5c0fe5bf9defb252b30197c08d138be42da Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 21 Jan 2013 11:31:28 +0100 Subject: [PATCH 114/311] MockHttpServletRequest's getParameter(Values) returns null for null parameter name Issue: SPR-10192 --- .../mock/web/MockHttpServletRequest.java | 43 ++++++++++-------- .../mock/web/MockHttpServletRequestTests.java | 12 +++-- .../mock/web/test/MockHttpServletRequest.java | 44 +++++++++---------- 3 files changed, 54 insertions(+), 45 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java index 441a53e4ce..d609f39e8f 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,7 +35,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; - import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -97,8 +96,10 @@ public class MockHttpServletRequest implements HttpServletRequest { private static final String CHARSET_PREFIX = "charset="; + private boolean active = true; + // --------------------------------------------------------------------- // ServletRequest properties // --------------------------------------------------------------------- @@ -140,6 +141,7 @@ public class MockHttpServletRequest implements HttpServletRequest { private int localPort = DEFAULT_SERVER_PORT; + // --------------------------------------------------------------------- // HttpServletRequest properties // --------------------------------------------------------------------- @@ -235,6 +237,7 @@ public class MockHttpServletRequest implements HttpServletRequest { this.locales.add(Locale.ENGLISH); } + // --------------------------------------------------------------------- // Lifecycle methods // --------------------------------------------------------------------- @@ -279,6 +282,7 @@ public class MockHttpServletRequest implements HttpServletRequest { } } + // --------------------------------------------------------------------- // ServletRequest interface // --------------------------------------------------------------------- @@ -351,7 +355,7 @@ public class MockHttpServletRequest implements HttpServletRequest { * parameter name, they will be replaced. */ public void setParameter(String name, String value) { - setParameter(name, new String[] { value }); + setParameter(name, new String[] {value}); } /** @@ -373,7 +377,8 @@ public class MockHttpServletRequest implements HttpServletRequest { public void setParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); for (Object key : params.keySet()) { - Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); + Assert.isInstanceOf(String.class, key, + "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); if (value instanceof String) { this.setParameter((String) key, (String) value); @@ -382,8 +387,8 @@ public class MockHttpServletRequest implements HttpServletRequest { this.setParameter((String) key, (String[]) value); } else { - throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type [" - + String.class.getName() + "]"); + throw new IllegalArgumentException( + "Parameter map value must be single value " + " or array of type [" + String.class.getName() + "]"); } } } @@ -394,7 +399,7 @@ public class MockHttpServletRequest implements HttpServletRequest { * parameter name, the given value will be added to the end of the list. */ public void addParameter(String name, String value) { - addParameter(name, new String[] { value }); + addParameter(name, new String[] {value}); } /** @@ -425,7 +430,8 @@ public class MockHttpServletRequest implements HttpServletRequest { public void addParameters(Map params) { Assert.notNull(params, "Parameter map must not be null"); for (Object key : params.keySet()) { - Assert.isInstanceOf(String.class, key, "Parameter map key must be of type [" + String.class.getName() + "]"); + Assert.isInstanceOf(String.class, key, + "Parameter map key must be of type [" + String.class.getName() + "]"); Object value = params.get(key); if (value instanceof String) { this.addParameter((String) key, (String) value); @@ -434,8 +440,8 @@ public class MockHttpServletRequest implements HttpServletRequest { this.addParameter((String) key, (String[]) value); } else { - throw new IllegalArgumentException("Parameter map value must be single value " + " or array of type [" - + String.class.getName() + "]"); + throw new IllegalArgumentException("Parameter map value must be single value " + + " or array of type [" + String.class.getName() + "]"); } } } @@ -456,8 +462,7 @@ public class MockHttpServletRequest implements HttpServletRequest { } public String getParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - String[] arr = this.parameters.get(name); + String[] arr = (name != null ? this.parameters.get(name) : null); return (arr != null && arr.length > 0 ? arr[0] : null); } @@ -466,8 +471,7 @@ public class MockHttpServletRequest implements HttpServletRequest { } public String[] getParameterValues(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.parameters.get(name); + return (name != null ? this.parameters.get(name) : null); } public Map getParameterMap() { @@ -509,8 +513,8 @@ public class MockHttpServletRequest implements HttpServletRequest { public BufferedReader getReader() throws UnsupportedEncodingException { if (this.content != null) { InputStream sourceStream = new ByteArrayInputStream(this.content); - Reader sourceReader = (this.characterEncoding != null) ? new InputStreamReader(sourceStream, - this.characterEncoding) : new InputStreamReader(sourceStream); + Reader sourceReader = (this.characterEncoding != null) ? + new InputStreamReader(sourceStream, this.characterEncoding) : new InputStreamReader(sourceStream); return new BufferedReader(sourceReader); } else { @@ -574,7 +578,7 @@ public class MockHttpServletRequest implements HttpServletRequest { * @since 3.2 */ public void setPreferredLocales(List locales) { - Assert.notEmpty(locales, "preferred locales list must not be empty"); + Assert.notEmpty(locales, "Locale list must not be empty"); this.locales.clear(); this.locales.addAll(locales); } @@ -635,6 +639,7 @@ public class MockHttpServletRequest implements HttpServletRequest { return this.localPort; } + // --------------------------------------------------------------------- // HttpServletRequest interface // --------------------------------------------------------------------- @@ -797,8 +802,8 @@ public class MockHttpServletRequest implements HttpServletRequest { } public boolean isUserInRole(String role) { - return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && ((MockServletContext) this.servletContext).getDeclaredRoles().contains( - role))); + return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && + ((MockServletContext) this.servletContext).getDeclaredRoles().contains(role))); } public void setUserPrincipal(Principal userPrincipal) { diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java index 085bbb8b7d..a237bb00d1 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletRequestTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,6 @@ package org.springframework.mock.web; -import static org.junit.Assert.*; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -29,6 +27,8 @@ import java.util.Map; import org.junit.Test; +import static org.junit.Assert.*; + /** * Unit tests for {@link MockHttpServletRequest}. * @@ -105,6 +105,12 @@ public class MockHttpServletRequestTests { assertEquals("HTTP header casing not being preserved", headerName, requestHeaders.nextElement()); } + @Test + public void nullParameterName() { + assertNull(request.getParameter(null)); + assertNull(request.getParameterValues(null)); + } + @Test public void setMultipleParameters() { request.setParameter("key1", "value1"); diff --git a/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletRequest.java b/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletRequest.java index 5694b66610..c5dc6d7601 100644 --- a/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletRequest.java +++ b/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,7 +36,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; - import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; @@ -110,9 +109,9 @@ public class MockHttpServletRequest implements HttpServletRequest { private boolean active = true; - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- // ServletRequest properties - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- private final Map attributes = new LinkedHashMap(); @@ -151,11 +150,12 @@ public class MockHttpServletRequest implements HttpServletRequest { private int localPort = DEFAULT_SERVER_PORT; - private Map parts = new HashMap(); + private final Map parts = new HashMap(); - //--------------------------------------------------------------------- + + // --------------------------------------------------------------------- // HttpServletRequest properties - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- private String authType; @@ -200,9 +200,9 @@ public class MockHttpServletRequest implements HttpServletRequest { private DispatcherType dispatcherType = DispatcherType.REQUEST; - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- // Constructors - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- /** * Create a new {@code MockHttpServletRequest} with a default @@ -256,9 +256,10 @@ public class MockHttpServletRequest implements HttpServletRequest { this.locales.add(Locale.ENGLISH); } - //--------------------------------------------------------------------- + + // --------------------------------------------------------------------- // Lifecycle methods - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- /** * Return the ServletContext that this request is associated with. (Not @@ -302,9 +303,9 @@ public class MockHttpServletRequest implements HttpServletRequest { } - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- // ServletRequest interface - //--------------------------------------------------------------------- + // --------------------------------------------------------------------- @Override public Object getAttribute(String name) { @@ -414,8 +415,7 @@ public class MockHttpServletRequest implements HttpServletRequest { } else { throw new IllegalArgumentException( - "Parameter map value must be single value " + " or array of type [" + String.class.getName() + - "]"); + "Parameter map value must be single value " + " or array of type [" + String.class.getName() + "]"); } } } @@ -490,8 +490,7 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public String getParameter(String name) { - Assert.notNull(name, "Parameter name must not be null"); - String[] arr = this.parameters.get(name); + String[] arr = (name != null ? this.parameters.get(name) : null); return (arr != null && arr.length > 0 ? arr[0] : null); } @@ -502,8 +501,7 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public String[] getParameterValues(String name) { - Assert.notNull(name, "Parameter name must not be null"); - return this.parameters.get(name); + return (name != null ? this.parameters.get(name) : null); } @Override @@ -620,7 +618,7 @@ public class MockHttpServletRequest implements HttpServletRequest { * @since 3.2 */ public void setPreferredLocales(List locales) { - Assert.notEmpty(locales, "preferred locales list must not be empty"); + Assert.notEmpty(locales, "Locale list must not be empty"); this.locales.clear(); this.locales.addAll(locales); } @@ -779,7 +777,7 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public String getHeader(String name) { HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name); - return (header != null ? header.getValue().toString() : null); + return (header != null ? header.getStringValue() : null); } @Override @@ -867,8 +865,8 @@ public class MockHttpServletRequest implements HttpServletRequest { @Override public boolean isUserInRole(String role) { - return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && ((MockServletContext) this.servletContext).getDeclaredRoles().contains( - role))); + return (this.userRoles.contains(role) || (this.servletContext instanceof MockServletContext && + ((MockServletContext) this.servletContext).getDeclaredRoles().contains(role))); } public void setUserPrincipal(Principal userPrincipal) { From 5a773b771d2b300888df33128f6c3993e2bd50b9 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 21 Jan 2013 11:33:13 +0100 Subject: [PATCH 115/311] MockHttpServletResponse's getHeaderNames declares Collection instead of Set for Servlet 3.0 compatibility Issue: SPR-9885 --- .../mock/web/MockHttpServletResponse.java | 9 +++++---- .../mock/web/MockHttpServletResponseTests.java | 11 +++++------ .../mock/web/test/MockHttpServletResponse.java | 15 +++++++-------- 3 files changed, 17 insertions(+), 18 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java index c86e95a93a..75a7a1fc3b 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +24,11 @@ import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Set; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; @@ -56,6 +56,7 @@ public class MockHttpServletResponse implements HttpServletResponse { private static final String LOCATION_HEADER = "Location"; + //--------------------------------------------------------------------- // ServletResponse properties //--------------------------------------------------------------------- @@ -145,7 +146,7 @@ public class MockHttpServletResponse implements HttpServletResponse { private void updateContentTypeHeader() { if (this.contentType != null) { StringBuilder sb = new StringBuilder(this.contentType); - if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.charset) { + if (!this.contentType.toLowerCase().contains(CHARSET_PREFIX) && this.charset) { sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding); } doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true); @@ -299,7 +300,7 @@ public class MockHttpServletResponse implements HttpServletResponse { *

As of Servlet 3.0, this method is also defined HttpServletResponse. * @return the {@code Set} of header name {@code Strings}, or an empty {@code Set} if none */ - public Set getHeaderNames() { + public Collection getHeaderNames() { return this.headers.keySet(); } diff --git a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java index c16f7cab9e..867b86ad90 100644 --- a/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java +++ b/spring-test/src/test/java/org/springframework/mock/web/MockHttpServletResponseTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,18 +16,17 @@ package org.springframework.mock.web; -import static org.junit.Assert.*; - import java.io.IOException; import java.util.Arrays; -import java.util.Set; - +import java.util.Collection; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.springframework.web.util.WebUtils; +import static org.junit.Assert.*; + /** * Unit tests for {@link MockHttpServletResponse}. * @@ -127,7 +126,7 @@ public class MockHttpServletResponseTests { public void httpHeaderNameCasingIsPreserved() throws Exception { final String headerName = "Header1"; response.addHeader(headerName, "value1"); - Set responseHeaders = response.getHeaderNames(); + Collection responseHeaders = response.getHeaderNames(); assertNotNull(responseHeaders); assertEquals(1, responseHeaders.size()); assertEquals("HTTP header casing not being preserved", headerName, responseHeaders.iterator().next()); diff --git a/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletResponse.java b/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletResponse.java index 6f52ab8e3e..990026770d 100644 --- a/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletResponse.java +++ b/spring-web/src/test/java/org/springframework/mock/web/test/MockHttpServletResponse.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +24,11 @@ import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Set; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; @@ -38,11 +38,9 @@ import org.springframework.util.LinkedCaseInsensitiveMap; import org.springframework.web.util.WebUtils; /** - * Mock implementation of the {@link javax.servlet.http.HttpServletResponse} - * interface. Supports the Servlet 3.0 API level + * Mock implementation of the {@link javax.servlet.http.HttpServletResponse} interface. * - *

Used for testing the web framework; also useful for testing - * application controllers. + *

Compatible with Servlet 2.5 as well as Servlet 3.0. * * @author Juergen Hoeller * @author Rod Johnson @@ -58,6 +56,7 @@ public class MockHttpServletResponse implements HttpServletResponse { private static final String LOCATION_HEADER = "Location"; + //--------------------------------------------------------------------- // ServletResponse properties //--------------------------------------------------------------------- @@ -148,7 +147,7 @@ public class MockHttpServletResponse implements HttpServletResponse { private void updateContentTypeHeader() { if (this.contentType != null) { StringBuilder sb = new StringBuilder(this.contentType); - if (this.contentType.toLowerCase().indexOf(CHARSET_PREFIX) == -1 && this.charset) { + if (!this.contentType.toLowerCase().contains(CHARSET_PREFIX) && this.charset) { sb.append(";").append(CHARSET_PREFIX).append(this.characterEncoding); } doAddHeaderValue(CONTENT_TYPE_HEADER, sb.toString(), true); @@ -319,7 +318,7 @@ public class MockHttpServletResponse implements HttpServletResponse { * @return the {@code Set} of header name {@code Strings}, or an empty {@code Set} if none */ @Override - public Set getHeaderNames() { + public Collection getHeaderNames() { return this.headers.keySet(); } From 8e75eee9b2b35f807fefe9575e59be5e2f4768eb Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 22 Jan 2013 16:46:01 +0100 Subject: [PATCH 116/311] SpringValidationAdapter properly detects invalid value for JSR-303 field-level bean constraints Issue: SPR-9332 --- .../SpringValidatorAdapter.java | 17 +++-- .../beanvalidation/ValidatorFactoryTests.java | 68 +++++++++++++++++-- 2 files changed, 74 insertions(+), 11 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java b/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java index 1a51c37bb9..7565e82099 100644 --- a/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java +++ b/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -99,7 +99,8 @@ public class SpringValidatorAdapter implements SmartValidator, javax.validation. } } } - processConstraintViolations(this.targetValidator.validate(target, groups.toArray(new Class[groups.size()])), errors); + processConstraintViolations( + this.targetValidator.validate(target, groups.toArray(new Class[groups.size()])), errors); } /** @@ -114,10 +115,11 @@ public class SpringValidatorAdapter implements SmartValidator, javax.validation. FieldError fieldError = errors.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { - String errorCode = violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(); - Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, violation.getConstraintDescriptor()); + ConstraintDescriptor cd = violation.getConstraintDescriptor(); + String errorCode = cd.getAnnotation().annotationType().getSimpleName(); + Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd); if (errors instanceof BindingResult) { - // can do custom FieldError registration with invalid value from ConstraintViolation, + // Can do custom FieldError registration with invalid value from ConstraintViolation, // as necessary for Hibernate Validator compatibility (non-indexed set path in field) BindingResult bindingResult = (BindingResult) errors; String nestedField = bindingResult.getNestedPath() + field; @@ -128,8 +130,9 @@ public class SpringValidatorAdapter implements SmartValidator, javax.validation. } else { Object invalidValue = violation.getInvalidValue(); - if (!"".equals(field) && invalidValue == violation.getLeafBean()) { - // bean constraint with property path: retrieve the actual property value + if (field.contains(".") && !field.contains("[]")) { + // Possibly a bean constraint with property path: retrieve the actual property value. + // However, explicitly avoid this for "address[]" style paths that we can't handle. invalidValue = bindingResult.getRawFieldValue(field); } String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field); diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java index 5c2dad22a4..3e6cac5759 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import javax.validation.Constraint; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import javax.validation.ConstraintViolation; +import javax.validation.Payload; import javax.validation.Valid; import javax.validation.constraints.NotNull; @@ -37,6 +38,7 @@ import org.hibernate.validator.HibernateValidator; import org.junit.Test; import org.springframework.validation.BeanPropertyBindingResult; +import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; @@ -193,6 +195,18 @@ public class ValidatorFactoryTests { System.out.println(fieldError.getDefaultMessage()); } + @Test + public void testInnerBeanValidation() throws Exception { + LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); + validator.afterPropertiesSet(); + + MainBean mainBean = new MainBean(); + Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean"); + validator.validate(mainBean, errors); + Object rejected = errors.getFieldValue("inner.value"); + assertNull(rejected); + } + @NameAddressValid public static class ValidPerson { @@ -242,7 +256,6 @@ public class ValidatorFactoryTests { } } - public static class ValidAddress { @NotNull @@ -257,7 +270,6 @@ public class ValidatorFactoryTests { } } - @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = NameAddressValidator.class) @@ -270,7 +282,6 @@ public class ValidatorFactoryTests { Class[] payload() default {}; } - public static class NameAddressValidator implements ConstraintValidator { @Override @@ -283,4 +294,53 @@ public class ValidatorFactoryTests { } } + + public static class MainBean { + + @InnerValid + private InnerBean inner = new InnerBean(); + + public InnerBean getInner() { + return inner; + } + } + + public static class InnerBean { + + private String value; + + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + } + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.FIELD) + @Constraint(validatedBy=InnerValidator.class) + public static @interface InnerValid { + String message() default "NOT VALID"; + Class[] groups() default { }; + Class[] payload() default {}; + } + + public static class InnerValidator implements ConstraintValidator { + + @Override + public void initialize(InnerValid constraintAnnotation) { + } + + @Override + public boolean isValid(InnerBean bean, ConstraintValidatorContext context) { + context.disableDefaultConstraintViolation(); + if (bean.getValue() == null) { + context.buildConstraintViolationWithTemplate("NULL"). addNode("value").addConstraintViolation(); + return false; + } + return true; + } + } + } From 1a929f22e0e8d136a11605efccf211a19ec63894 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 22 Jan 2013 20:38:03 +0100 Subject: [PATCH 117/311] EntityManagerFactoryUtils finds default EntityManagerFactory in parent contexts as well Also introduces consistent use of getBean(Class) for similar use cases across the framework, accepting a locally unique target bean even if further matching beans would be available in parent contexts (in contrast to BeanFactoryUtils.beanOfType's behavior). Issue: SPR-10160 --- .../factory/config/ServiceLocatorFactoryBean.java | 9 ++++----- .../orm/jpa/EntityManagerFactoryUtils.java | 9 ++++++--- .../interceptor/TransactionAspectSupport.java | 10 ++-------- .../interceptor/TransactionProxyFactoryBean.java | 6 +++--- 4 files changed, 15 insertions(+), 19 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java index e8f2b72b6c..1ded4154aa 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/ServiceLocatorFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,6 @@ import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.ListableBeanFactory; @@ -364,12 +363,12 @@ public class ServiceLocatorFactoryBean implements FactoryBean, BeanFacto try { String beanName = tryGetBeanName(args); if (StringUtils.hasLength(beanName)) { - // Service locator for a specific bean name. + // Service locator for a specific bean name return beanFactory.getBean(beanName, serviceLocatorMethodReturnType); } else { - // Service locator for a bean type. - return BeanFactoryUtils.beanOfTypeIncludingAncestors(beanFactory, serviceLocatorMethodReturnType); + // Service locator for a bean type + return beanFactory.getBean(serviceLocatorMethodReturnType); } } catch (BeansException ex) { diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java b/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java index 9419950001..044cb72be3 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/EntityManagerFactoryUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,10 +76,12 @@ public abstract class EntityManagerFactoryUtils { * Find an EntityManagerFactory with the given name in the given * Spring application context (represented as ListableBeanFactory). *

The specified unit name will be matched against the configured - * peristence unit, provided that a discovered EntityManagerFactory + * persistence unit, provided that a discovered EntityManagerFactory * implements the {@link EntityManagerFactoryInfo} interface. If not, * the persistence unit name will be matched against the Spring bean name, * assuming that the EntityManagerFactory bean names follow that convention. + *

If no unit name has been given, this method will search for a default + * EntityManagerFactory through {@link ListableBeanFactory#getBean(Class)}. * @param beanFactory the ListableBeanFactory to search * @param unitName the name of the persistence unit (may be {@code null} or empty, * in which case a single bean of type EntityManagerFactory will be searched for) @@ -108,7 +110,8 @@ public abstract class EntityManagerFactoryUtils { return beanFactory.getBean(unitName, EntityManagerFactory.class); } else { - return BeanFactoryUtils.beanOfType(beanFactory, EntityManagerFactory.class); + // Find unique EntityManagerFactory bean in the context, falling back to parent contexts. + return beanFactory.getBean(EntityManagerFactory.class); } } diff --git a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java index 8d15342c02..9f9b9503dd 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java +++ b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,9 +24,7 @@ import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils; import org.springframework.core.NamedThreadLocal; import org.springframework.transaction.NoTransactionException; @@ -247,12 +245,8 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init else if (this.transactionManagerBeanName != null) { return this.beanFactory.getBean(this.transactionManagerBeanName, PlatformTransactionManager.class); } - else if (this.beanFactory instanceof ListableBeanFactory) { - return BeanFactoryUtils.beanOfTypeIncludingAncestors(((ListableBeanFactory) this.beanFactory), PlatformTransactionManager.class); - } else { - throw new IllegalStateException( - "Cannot retrieve PlatformTransactionManager beans from non-listable BeanFactory: " + this.beanFactory); + return this.beanFactory.getBean(PlatformTransactionManager.class); } } diff --git a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.java b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.java index eaf963cc39..62b408e155 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.java +++ b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionProxyFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -176,8 +176,8 @@ public class TransactionProxyFactoryBean extends AbstractSingletonProxyFactoryBe /** * This callback is optional: If running in a BeanFactory and no transaction * manager has been set explicitly, a single matching bean of type - * PlatformTransactionManager will be fetched from the BeanFactory. - * @see org.springframework.beans.factory.BeanFactoryUtils#beanOfTypeIncludingAncestors + * {@link PlatformTransactionManager} will be fetched from the BeanFactory. + * @see org.springframework.beans.factory.BeanFactory#getBean(Class) * @see org.springframework.transaction.PlatformTransactionManager */ public void setBeanFactory(BeanFactory beanFactory) { From 8f103c2ea195210ac84cfc9fd56b9e21f32ecc85 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 22 Jan 2013 21:10:08 +0100 Subject: [PATCH 118/311] Introduced NoUniqueBeanDefinitionException as a dedicated subclass of NoSuchBeanDefinitionException Issue: SPR-10194 --- .../beans/factory/BeanFactory.java | 9 ++- .../beans/factory/BeanFactoryUtils.java | 61 +++++++------- .../NoSuchBeanDefinitionException.java | 29 ++++--- .../NoUniqueBeanDefinitionException.java | 79 +++++++++++++++++++ .../support/DefaultListableBeanFactory.java | 16 ++-- .../support/StaticListableBeanFactory.java | 8 +- .../DefaultListableBeanFactoryTests.java | 9 ++- ...ersistenceAnnotationBeanPostProcessor.java | 11 +-- 8 files changed, 163 insertions(+), 59 deletions(-) create mode 100644 spring-beans/src/main/java/org/springframework/beans/factory/NoUniqueBeanDefinitionException.java diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java index 2d18e67b1a..8c73a16fd7 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -143,7 +143,7 @@ public interface BeanFactory { * is {@code Object.class}, this method will succeed whatever the class of the * returned instance. * @return an instance of the bean - * @throws NoSuchBeanDefinitionException if there's no such bean definition + * @throws NoSuchBeanDefinitionException if there is no such bean definition * @throws BeanNotOfRequiredTypeException if the bean is not of the required type * @throws BeansException if the bean could not be created */ @@ -158,7 +158,8 @@ public interface BeanFactory { * of the given type. For more extensive retrieval operations across sets of beans, * use {@link ListableBeanFactory} and/or {@link BeanFactoryUtils}. * @return an instance of the single bean matching the required type - * @throws NoSuchBeanDefinitionException if there is not exactly one matching bean found + * @throws NoSuchBeanDefinitionException if no bean of the given type was found + * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found * @since 3.0 * @see ListableBeanFactory */ @@ -172,7 +173,7 @@ public interface BeanFactory { * @param args arguments to use if creating a prototype using explicit arguments to a * static factory method. It is invalid to use a non-null args value in any other case. * @return an instance of the bean - * @throws NoSuchBeanDefinitionException if there's no such bean definition + * @throws NoSuchBeanDefinitionException if there is no such bean definition * @throws BeanDefinitionStoreException if arguments have been given but * the affected bean isn't a prototype * @throws BeansException if the bean could not be created diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java b/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java index 2a4f577a1c..657bb1ebd1 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/BeanFactoryUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -310,20 +310,15 @@ public abstract class BeanFactoryUtils { * @param lbf the bean factory * @param type type of bean to match * @return the matching bean instance - * @throws NoSuchBeanDefinitionException - * if 0 or more than 1 beans of the given type were found + * @throws NoSuchBeanDefinitionException if no bean of the given type was found + * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found * @throws BeansException if the bean could not be created */ public static T beanOfTypeIncludingAncestors(ListableBeanFactory lbf, Class type) throws BeansException { Map beansOfType = beansOfTypeIncludingAncestors(lbf, type); - if (beansOfType.size() == 1) { - return beansOfType.values().iterator().next(); - } - else { - throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); - } + return uniqueBean(type, beansOfType); } /** @@ -351,8 +346,8 @@ public abstract class BeanFactoryUtils { * eagerly initialized to determine their type: So be aware that passing in "true" * for this flag will initialize FactoryBeans and "factory-bean" references. * @return the matching bean instance - * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException - * if 0 or more than 1 beans of the given type were found + * @throws NoSuchBeanDefinitionException if no bean of the given type was found + * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found * @throws BeansException if the bean could not be created */ public static T beanOfTypeIncludingAncestors( @@ -360,12 +355,7 @@ public abstract class BeanFactoryUtils { throws BeansException { Map beansOfType = beansOfTypeIncludingAncestors(lbf, type, includeNonSingletons, allowEagerInit); - if (beansOfType.size() == 1) { - return beansOfType.values().iterator().next(); - } - else { - throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); - } + return uniqueBean(type, beansOfType); } /** @@ -380,19 +370,14 @@ public abstract class BeanFactoryUtils { * @param lbf the bean factory * @param type type of bean to match * @return the matching bean instance - * @throws NoSuchBeanDefinitionException - * if 0 or more than 1 beans of the given type were found + * @throws NoSuchBeanDefinitionException if no bean of the given type was found + * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found * @throws BeansException if the bean could not be created */ public static T beanOfType(ListableBeanFactory lbf, Class type) throws BeansException { Assert.notNull(lbf, "ListableBeanFactory must not be null"); Map beansOfType = lbf.getBeansOfType(type); - if (beansOfType.size() == 1) { - return beansOfType.values().iterator().next(); - } - else { - throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); - } + return uniqueBean(type, beansOfType); } /** @@ -415,8 +400,8 @@ public abstract class BeanFactoryUtils { * eagerly initialized to determine their type: So be aware that passing in "true" * for this flag will initialize FactoryBeans and "factory-bean" references. * @return the matching bean instance - * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException - * if 0 or more than 1 beans of the given type were found + * @throws NoSuchBeanDefinitionException if no bean of the given type was found + * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found * @throws BeansException if the bean could not be created */ public static T beanOfType( @@ -425,11 +410,27 @@ public abstract class BeanFactoryUtils { Assert.notNull(lbf, "ListableBeanFactory must not be null"); Map beansOfType = lbf.getBeansOfType(type, includeNonSingletons, allowEagerInit); - if (beansOfType.size() == 1) { - return beansOfType.values().iterator().next(); + return uniqueBean(type, beansOfType); + } + + /** + * Extract a unique bean for the given type from the given Map of matching beans. + * @param type type of bean to match + * @param matchingBeans all matching beans found + * @return the unique bean instance + * @throws NoSuchBeanDefinitionException if no bean of the given type was found + * @throws NoUniqueBeanDefinitionException if more than one bean of the given type was found + */ + private static T uniqueBean(Class type, Map matchingBeans) { + int nrFound = matchingBeans.size(); + if (nrFound == 1) { + return matchingBeans.values().iterator().next(); + } + else if (nrFound > 1) { + throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet()); } else { - throw new NoSuchBeanDefinitionException(type, "expected single bean but found " + beansOfType.size()); + throw new NoSuchBeanDefinitionException(type); } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/NoSuchBeanDefinitionException.java b/spring-beans/src/main/java/org/springframework/beans/factory/NoSuchBeanDefinitionException.java index 0157d08650..5bd8ea7a9f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/NoSuchBeanDefinitionException.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/NoSuchBeanDefinitionException.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,11 +20,13 @@ import org.springframework.beans.BeansException; import org.springframework.util.StringUtils; /** - * Exception thrown when a {@code BeanFactory} is asked for a bean - * instance for which it cannot find a definition. + * Exception thrown when a {@code BeanFactory} is asked for a bean instance + * for which it cannot find a definition. * * @author Rod Johnson * @author Juergen Hoeller + * @see BeanFactory#getBean(String) + * @see BeanFactory#getBean(Class) */ @SuppressWarnings("serial") public class NoSuchBeanDefinitionException extends BeansException { @@ -60,7 +62,7 @@ public class NoSuchBeanDefinitionException extends BeansException { * @param type required type of the missing bean */ public NoSuchBeanDefinitionException(Class type) { - super("No unique bean of type [" + type.getName() + "] is defined"); + super("No qualifying bean of type [" + type.getName() + "] is defined"); this.beanType = type; } @@ -70,7 +72,7 @@ public class NoSuchBeanDefinitionException extends BeansException { * @param message detailed message describing the problem */ public NoSuchBeanDefinitionException(Class type, String message) { - super("No unique bean of type [" + type.getName() + "] is defined: " + message); + super("No qualifying bean of type [" + type.getName() + "] is defined: " + message); this.beanType = type; } @@ -81,7 +83,7 @@ public class NoSuchBeanDefinitionException extends BeansException { * @param message detailed message describing the problem */ public NoSuchBeanDefinitionException(Class type, String dependencyDescription, String message) { - super("No matching bean of type [" + type.getName() + "] found for dependency" + + super("No qualifying bean of type [" + type.getName() + "] found for dependency" + (StringUtils.hasLength(dependencyDescription) ? " [" + dependencyDescription + "]" : "") + ": " + message); this.beanType = type; @@ -89,19 +91,26 @@ public class NoSuchBeanDefinitionException extends BeansException { /** - * Return the name of the missing bean, if it was a lookup by name - * that failed. + * Return the name of the missing bean, if it was a lookup by name that failed. */ public String getBeanName() { return this.beanName; } /** - * Return the required type of the missing bean, if it was a lookup - * by type that failed. + * Return the required type of the missing bean, if it was a lookup by type that failed. */ public Class getBeanType() { return this.beanType; } + /** + * Return the number of beans found when only one matching bean was expected. + * For a regular NoSuchBeanDefinitionException, this will always be 0. + * @see NoUniqueBeanDefinitionException + */ + public int getNumberOfBeansFound() { + return 0; + } + } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/NoUniqueBeanDefinitionException.java b/spring-beans/src/main/java/org/springframework/beans/factory/NoUniqueBeanDefinitionException.java new file mode 100644 index 0000000000..7db0bae6e1 --- /dev/null +++ b/spring-beans/src/main/java/org/springframework/beans/factory/NoUniqueBeanDefinitionException.java @@ -0,0 +1,79 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.beans.factory; + +import java.util.Arrays; +import java.util.Collection; + +import org.springframework.util.StringUtils; + +/** + * Exception thrown when a {@code BeanFactory} is asked for a bean instance for which + * multiple matching candidates have been found when only one matching bean was expected. + * + * @author Juergen Hoeller + * @since 3.2.1 + * @see BeanFactory#getBean(Class) + */ +@SuppressWarnings("serial") +public class NoUniqueBeanDefinitionException extends NoSuchBeanDefinitionException { + + private int numberOfBeansFound; + + + /** + * Create a new {@code NoUniqueBeanDefinitionException}. + * @param type required type of the non-unique bean + * @param numberOfBeansFound the number of matching beans + * @param message detailed message describing the problem + */ + public NoUniqueBeanDefinitionException(Class type, int numberOfBeansFound, String message) { + super(type, message); + this.numberOfBeansFound = numberOfBeansFound; + } + + /** + * Create a new {@code NoUniqueBeanDefinitionException}. + * @param type required type of the non-unique bean + * @param beanNamesFound the names of all matching beans (as a Collection) + */ + public NoUniqueBeanDefinitionException(Class type, Collection beanNamesFound) { + this(type, beanNamesFound.size(), "expected single matching bean but found " + beanNamesFound.size() + ": " + + StringUtils.collectionToCommaDelimitedString(beanNamesFound)); + } + + /** + * Create a new {@code NoUniqueBeanDefinitionException}. + * @param type required type of the non-unique bean + * @param beanNamesFound the names of all matching beans (as an array) + */ + public NoUniqueBeanDefinitionException(Class type, String... beanNamesFound) { + this(type, Arrays.asList(beanNamesFound)); + } + + + /** + * Return the number of beans found when only one matching bean was expected. + * For a NoUniqueBeanDefinitionException, this will usually be higher than 1. + * @see #getBeanType() + */ + @Override + public int getNumberOfBeansFound() { + return this.numberOfBeansFound; + } + +} diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index 824caaaec5..432663ab79 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,6 +50,7 @@ import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.CannotLoadBeanClassException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.SmartFactoryBean; import org.springframework.beans.factory.config.BeanDefinition; @@ -270,12 +271,14 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto if (beanNames.length == 1) { return getBean(beanNames[0], requiredType); } - else if (beanNames.length == 0 && getParentBeanFactory() != null) { + else if (beanNames.length > 1) { + throw new NoUniqueBeanDefinitionException(requiredType, beanNames); + } + else if (getParentBeanFactory() != null) { return getParentBeanFactory().getBean(requiredType); } else { - throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found " + - beanNames.length + ": " + StringUtils.arrayToCommaDelimitedString(beanNames)); + throw new NoSuchBeanDefinitionException(requiredType); } } @@ -823,8 +826,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto if (matchingBeans.size() > 1) { String primaryBeanName = determinePrimaryCandidate(matchingBeans, descriptor); if (primaryBeanName == null) { - throw new NoSuchBeanDefinitionException(type, "expected single matching bean but found " + - matchingBeans.size() + ": " + matchingBeans.keySet()); + throw new NoUniqueBeanDefinitionException(type, matchingBeans.keySet()); } if (autowiredBeanNames != null) { autowiredBeanNames.add(primaryBeanName); @@ -895,7 +897,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto boolean candidateLocal = containsBeanDefinition(candidateBeanName); boolean primaryLocal = containsBeanDefinition(primaryBeanName); if (candidateLocal == primaryLocal) { - throw new NoSuchBeanDefinitionException(descriptor.getDependencyType(), + throw new NoUniqueBeanDefinitionException(descriptor.getDependencyType(), candidateBeans.size(), "more than one 'primary' bean found among candidates: " + candidateBeans.keySet()); } else if (candidateLocal && !primaryLocal) { diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java index 3e8784b181..4eef1b4751 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/StaticListableBeanFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import org.springframework.beans.factory.BeanNotOfRequiredTypeException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.SmartFactoryBean; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.StringUtils; @@ -117,8 +118,11 @@ public class StaticListableBeanFactory implements ListableBeanFactory { if (beanNames.length == 1) { return getBean(beanNames[0], requiredType); } + else if (beanNames.length > 1) { + throw new NoUniqueBeanDefinitionException(requiredType, beanNames); + } else { - throw new NoSuchBeanDefinitionException(requiredType, "expected single bean but found " + beanNames.length); + throw new NoSuchBeanDefinitionException(requiredType); } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index acf9f65a05..e93e95973d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -1270,6 +1270,12 @@ public class DefaultListableBeanFactoryTests { } @Test(expected=NoSuchBeanDefinitionException.class) + public void testGetBeanByTypeWithNoneFound() { + DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); + lbf.getBean(TestBean.class); + } + + @Test(expected=NoUniqueBeanDefinitionException.class) public void testGetBeanByTypeWithAmbiguity() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class); @@ -1296,7 +1302,8 @@ public class DefaultListableBeanFactoryTests { try { lbf.getBean(TestBean.class); fail("Should have thrown NoSuchBeanDefinitionException"); - } catch (NoSuchBeanDefinitionException ex) { + } + catch (NoSuchBeanDefinitionException ex) { // expected } } diff --git a/spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java b/spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java index ac9c408f02..39c437e8cd 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java +++ b/spring-orm/src/main/java/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,6 +43,7 @@ import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.NoUniqueBeanDefinitionException; import org.springframework.beans.factory.annotation.InjectionMetadata; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; @@ -60,7 +61,6 @@ import org.springframework.orm.jpa.ExtendedEntityManagerCreator; import org.springframework.orm.jpa.SharedEntityManagerCreator; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; /** * BeanPostProcessor that processes {@link javax.persistence.PersistenceUnit} @@ -534,10 +534,11 @@ public class PersistenceAnnotationBeanPostProcessor } return emf; } + else if (beanNames.length > 1) { + throw new NoUniqueBeanDefinitionException(EntityManagerFactory.class, beanNames); + } else { - throw new NoSuchBeanDefinitionException( - EntityManagerFactory.class, "expected single bean but found " + beanNames.length + ": " + - StringUtils.arrayToCommaDelimitedString(beanNames)); + throw new NoSuchBeanDefinitionException(EntityManagerFactory.class); } } From 0a09da7534395acc53dcb423a7b42f64d8403dec Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 22 Jan 2013 21:10:47 +0100 Subject: [PATCH 119/311] Final preparations for 3.2.1 --- src/dist/changelog.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 8c0d7fbfab..771470cc1d 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -12,25 +12,30 @@ Changes in version 3.2.1 (2013-01-24) * BridgeMethodResolver properly handles bridge methods in interfaces (SPR-9330) * LocalVariableTableParameterNameDiscoverer works for bridge methods as well (SPR-9429) * CachedIntrospectionResults.clearClassLoader(null) removes cached classes for the system class loader (SPR-9189) +* introduced NoUniqueBeanDefinitionException as a dedicated subclass of NoSuchBeanDefinitionException (SPR-10194) * fixed QualifierAnnotationAutowireCandidateResolver's detection of custom qualifier annotations (SPR-10107) * fixed AbstractAutoProxyCreator to accept null bean names again (SPR-10108) * AbstractAdvisingBeanPostProcessor caches per bean target class, working for null bean names as well (SPR-10144) * MessageSourceResourceBundle overrides JDK 1.6 containsKey method, avoiding NPE in getKeys (SPR-10136) +* SpringValidationAdapter properly detects invalid value for JSR-303 field-level bean constraints (SPR-9332) * SpringBeanAutowiringInterceptor eagerly releases BeanFactory if post-construction fails (SPR-10013) * added "exposeAccessContext" flag JndiRmiClientInterceptor/ProxyFactoryBean (for WebLogic; SPR-9428) * MBeanExporter does not log warnings for manually unregistered MBeans (SPR-9451) * AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup (SPR-7955) * EhCacheManagerFactoryBean applies cacheManagerName ahead of creation (for EHCache 2.5 compatibility; SPR-9171) -* JDBC parameter binding uses JDBC 3.0 ParameterMetaData (if available) for type determination (SPR-10084) * reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd (SPR-10177) * spring-task-3.2.xsd allows for SpEL expressions in initial-delay attribute (SPR-10102) * spring-jms-3.2.xsd allows for SpEL expressions in prefetch and receive-timeout attributes (SPR-9553) * JmsTemplate uses configured receiveTimeout if shorter than remaining transaction timeout (SPR-10109) * added MappingJackson2MessageConverter for JMS (SPR-10099) +* JDBC parameter binding uses JDBC 3.0 ParameterMetaData (if available) for type determination (SPR-10084) +* JpaTransactionManager etc finds default EntityManagerFactory in parent context as well (SPR-10160) * MimeMessageHelper encodes attachment filename if not ASCII compliant (SPR-9258) * FreeMarkerConfigurationFactory properly supports TemplateLoaders when recreating Configurations (SPR-9389) * SpringContextResourceAdapter implements equals/hashCode according to the JCA 1.5 contract (SPR-9162) * ContextLoader properly detects pre-refreshed WebApplicationContext (SPR-9996) +* MockHttpServletRequest's getParameter(Values) returns null for null parameter name (SPR-10192) +* MockHttpServletResponse's getHeaderNames declares Collection instead of Set for Servlet 3.0 compatibility (SPR-9885) Changes in version 3.2 GA (2012-12-13) From a3e190e1bf80b88ce049f540a05bdf9706e140a4 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 22 Jan 2013 17:20:24 -0500 Subject: [PATCH 120/311] Support sub-types of ResponseEntity Issue: SPR-10207 --- .../mvc/method/annotation/HttpEntityMethodProcessor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java index e93029aa64..edb113e607 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,7 @@ public class HttpEntityMethodProcessor extends AbstractMessageConverterMethodPro public boolean supportsReturnType(MethodParameter returnType) { Class parameterType = returnType.getParameterType(); - return HttpEntity.class.equals(parameterType) || ResponseEntity.class.equals(parameterType); + return HttpEntity.class.isAssignableFrom(parameterType) || ResponseEntity.class.isAssignableFrom(parameterType); } public Object resolveArgument( From 0efdd3d5668115b5463c119392e93dc830c9de60 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 22 Jan 2013 22:10:29 +0100 Subject: [PATCH 121/311] Aligned XML scheduled-task elements with @Scheduled in terms of kicking in after context refresh Issue: SPR-9231 --- ...ontextLifecycleScheduledTaskRegistrar.java | 65 +++++++++++++++++++ .../config/ScheduledTaskRegistrar.java | 12 +++- .../ScheduledTasksBeanDefinitionParser.java | 6 +- 3 files changed, 79 insertions(+), 4 deletions(-) create mode 100644 spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java b/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java new file mode 100644 index 0000000000..eacf7ed25c --- /dev/null +++ b/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java @@ -0,0 +1,65 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.scheduling.config; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationListener; +import org.springframework.context.event.ContextRefreshedEvent; + +/** + * {@link ScheduledTaskRegistrar} subclass that redirect the actual scheduling + * of tasks to the {@link ContextRefreshedEvent} callback. Falls back to regular + * {@link ScheduledTaskRegistrar} behavior when not running within an ApplicationContext. + * + * @author Juergen Hoeller + * @since 3.2.1 + */ +public class ContextLifecycleScheduledTaskRegistrar extends ScheduledTaskRegistrar + implements ApplicationContextAware, ApplicationListener { + + private ApplicationContext applicationContext; + + + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + + /** + * If we're running within an ApplicationContext, don't schedule the tasks + * right here; wait for this context's ContextRefreshedEvent instead. + */ + @Override + public void afterPropertiesSet() { + if (this.applicationContext == null) { + scheduleTasks(); + } + } + + /** + * Actually schedule the tasks at the right time of the context lifecycle, + * if we're running within an ApplicationContext. + */ + public void onApplicationEvent(ContextRefreshedEvent event) { + if (event.getApplicationContext() != this.applicationContext) { + return; + } + scheduleTasks(); + } + +} diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskRegistrar.java b/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskRegistrar.java index 592fd033c1..2efd26cea9 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskRegistrar.java +++ b/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskRegistrar.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -274,11 +274,19 @@ public class ScheduledTaskRegistrar implements InitializingBean, DisposableBean (this.triggerTasks != null && !this.triggerTasks.isEmpty()); } + + /** + * Calls {@link #scheduleTasks()} at bean construction time. + */ + public void afterPropertiesSet() { + scheduleTasks(); + } + /** * Schedule all registered tasks against the underlying {@linkplain * #setTaskScheduler(TaskScheduler) task scheduler}. */ - public void afterPropertiesSet() { + protected void scheduleTasks() { long now = System.currentTimeMillis(); if (this.taskScheduler == null) { diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParser.java index a892eb414b..8f6963614f 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParser.java +++ b/spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTasksBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -38,8 +38,10 @@ import org.w3c.dom.NodeList; public class ScheduledTasksBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { private static final String ELEMENT_SCHEDULED = "scheduled"; + private static final long ZERO_INITIAL_DELAY = 0; + @Override protected boolean shouldGenerateId() { return true; @@ -47,7 +49,7 @@ public class ScheduledTasksBeanDefinitionParser extends AbstractSingleBeanDefini @Override protected String getBeanClassName(Element element) { - return "org.springframework.scheduling.config.ScheduledTaskRegistrar"; + return "org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar"; } @Override From ece727bf57dac1b764cbdad94a10660c15a41c48 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 22 Jan 2013 23:28:38 +0100 Subject: [PATCH 122/311] Introduced NoUniqueBeanDefinitionException as a dedicated subclass of NoSuchBeanDefinitionException Issue: SPR-10194 --- ...nnotationConfigApplicationContextTests.java | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java index 2397340003..5906ea485d 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,10 @@ package org.springframework.context.annotation; import java.util.Map; +import java.util.regex.Pattern; import org.junit.Test; + import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.annotation.Autowired; @@ -27,7 +29,7 @@ import org.springframework.context.annotation6.ComponentForScanning; import org.springframework.context.annotation6.ConfigForScanning; import org.springframework.context.annotation6.Jsr330NamedForScanning; -import static java.lang.String.*; +import static java.lang.String.format; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.springframework.util.StringUtils.*; @@ -120,13 +122,14 @@ public class AnnotationConfigApplicationContextTests { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); // attempt to retrieve a bean that does not exist - Class targetType = java.util.regex.Pattern.class; + Class targetType = Pattern.class; try { Object bean = context.getBean(targetType); fail("should have thrown NoSuchBeanDefinitionException, instead got: " + bean); - } catch (NoSuchBeanDefinitionException ex) { + } + catch (NoSuchBeanDefinitionException ex) { assertThat(ex.getMessage(), containsString( - format("No unique bean of type [%s] is defined", targetType.getName()))); + format("No qualifying bean of type [%s] is defined", targetType.getName()))); } } @@ -137,10 +140,11 @@ public class AnnotationConfigApplicationContextTests { try { context.getBean(TestBean.class); - } catch (RuntimeException ex) { + } + catch (NoSuchBeanDefinitionException ex) { assertThat(ex.getMessage(), allOf( - containsString("No unique bean of type [" + TestBean.class.getName() + "] is defined"), + containsString("No qualifying bean of type [" + TestBean.class.getName() + "] is defined"), containsString("tb1"), containsString("tb2") ) From 3eec27a7230f65698d9afd04e27ce0db6ac57cab Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 22 Jan 2013 13:47:25 -0800 Subject: [PATCH 123/311] Filter build folder resources in eclipse Apply eclipse project 'filter' to hide generated build artifacts from the workspace. --- gradle/ide.gradle | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/gradle/ide.gradle b/gradle/ide.gradle index af43e6bc9d..bb73f9f456 100644 --- a/gradle/ide.gradle +++ b/gradle/ide.gradle @@ -78,3 +78,21 @@ task cleanEclipseJdtUi(type: Delete) { tasks["eclipseJdt"].dependsOn(eclipseJdtPrepare) tasks["cleanEclipse"].dependsOn(cleanEclipseJdtUi) tasks["eclipse"].dependsOn(eclipseSettings, eclipseWstComponent) + + +// Filter 'build' folder + +eclipse.project.file.withXml { + def node = it.asNode() + + def filteredResources = node.get("filteredResources") + if(filteredResources) { + node.remove(filteredResources) + } + def filterNode = node.appendNode("filteredResources").appendNode("filter") + filterNode.appendNode("name", "build") + filterNode.appendNode("type", "26") + def matcherNode = filterNode.appendNode("matcher") + matcherNode.appendNode("id", "org.eclipse.ui.ide.multiFilter") + matcherNode.appendNode("arguments", "1.0-projectRelativePath-matches-false-true-build\\/((?!eclipse).)*") +} From 05ba366edc4a8c3b426f54aa313466e7954f3b9b Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 22 Jan 2013 13:49:14 -0800 Subject: [PATCH 124/311] Polish AbstractContextLoader Javadoc Fix unnecessary HTML escaping from {@code} Javadoc. --- .../test/context/support/AbstractContextLoader.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java b/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java index 0928ff4c9e..0fc6c6012c 100644 --- a/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java +++ b/spring-test/src/main/java/org/springframework/test/context/support/AbstractContextLoader.java @@ -185,8 +185,8 @@ public abstract class AbstractContextLoader implements SmartContextLoader { * *

For example, if the supplied class is {@code com.example.MyTest}, * the generated locations will contain a single string with a value of - * "classpath:/com/example/MyTest{@code <suffix>}", - * where {@code <suffix>} is the value of the + * "classpath:/com/example/MyTest{@code }", + * where {@code } is the value of the * {@link #getResourceSuffix() resource suffix} string. * *

As of Spring 3.1, the implementation of this method adheres to the From 4d01d43c191564ade610437533e34b4e77ba385f Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 22 Jan 2013 14:11:32 -0800 Subject: [PATCH 125/311] Test String to char[] conversion Issue: SPR-9793 --- .../support/DefaultConversionTests.java | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java index 3dde490705..7b2ff0490a 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,14 @@ package org.springframework.core.convert.support; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import java.awt.Color; import java.math.BigDecimal; @@ -773,6 +780,30 @@ public class DefaultConversionTests { assertEquals(new Long(1), e.getId()); } + @Test + public void convertCharArrayToString() throws Exception { + String converted = conversionService.convert(new char[] { 'a', 'b', 'c' }, String.class); + assertThat(converted, equalTo("a,b,c")); + } + + @Test + public void convertStringToCharArray() throws Exception { + char[] converted = conversionService.convert("a,b,c", char[].class); + assertThat(converted, equalTo(new char[] { 'a', 'b', 'c' })); + } + + @Test + public void convertStringToCustomCharArray() throws Exception { + conversionService.addConverter(new Converter() { + @Override + public char[] convert(String source) { + return source.toCharArray(); + } + }); + char[] converted = conversionService.convert("abc", char[].class); + assertThat(converted, equalTo(new char[] { 'a', 'b', 'c' })); + } + public static class TestEntity { private Long id; From 3c09b07652ed3c7a2e4cee1295a450aee387f99b Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Tue, 22 Jan 2013 18:06:41 -0500 Subject: [PATCH 126/311] Raise exception on missing request parameters Issue: SPR-10193 --- .../RequestMappingInfoHandlerMapping.java | 25 +++++++++++++++++++ ...RequestMappingInfoHandlerMappingTests.java | 19 ++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java index e55ec1a3ca..cc242bf756 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java @@ -28,15 +28,19 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import org.springframework.http.MediaType; +import org.springframework.util.CollectionUtils; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; +import org.springframework.web.servlet.mvc.condition.NameValueExpression; +import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition; import org.springframework.web.util.WebUtils; /** @@ -185,14 +189,17 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe Set consumableMediaTypes; Set producibleMediaTypes; + Set paramConditions; if (patternAndMethodMatches.isEmpty()) { consumableMediaTypes = getConsumableMediaTypes(request, patternMatches); producibleMediaTypes = getProdicubleMediaTypes(request, patternMatches); + paramConditions = getRequestParams(request, patternMatches); } else { consumableMediaTypes = getConsumableMediaTypes(request, patternAndMethodMatches); producibleMediaTypes = getProdicubleMediaTypes(request, patternAndMethodMatches); + paramConditions = getRequestParams(request, patternAndMethodMatches); } if (!consumableMediaTypes.isEmpty()) { @@ -205,6 +212,10 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe else if (!producibleMediaTypes.isEmpty()) { throw new HttpMediaTypeNotAcceptableException(new ArrayList(producibleMediaTypes)); } + else if (!CollectionUtils.isEmpty(paramConditions)) { + String[] params = paramConditions.toArray(new String[paramConditions.size()]); + throw new UnsatisfiedServletRequestParameterException(params, request.getParameterMap()); + } else { return null; } @@ -230,4 +241,18 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe return result; } + private Set getRequestParams(HttpServletRequest request, Set partialMatches) { + for (RequestMappingInfo partialMatch : partialMatches) { + ParamsRequestCondition condition = partialMatch.getParamsCondition(); + if (!CollectionUtils.isEmpty(condition.getExpressions()) && (condition.getMatchingCondition(request) == null)) { + Set expressions = new HashSet(); + for (NameValueExpression expr : condition.getExpressions()) { + expressions.add(expr.toString()); + } + return expressions; + } + } + return null; + } + } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index 1d9168926b..2db8412a82 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -42,6 +42,7 @@ import org.springframework.util.MultiValueMap; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.HttpMediaTypeNotSupportedException; import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -202,6 +203,19 @@ public class RequestMappingInfoHandlerMappingTests { } } + @Test + public void testUnsatisfiedServletRequestParameterException() throws Exception { + try { + MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params"); + this.handlerMapping.getHandler(request); + fail("UnsatisfiedServletRequestParameterException expected"); + } + catch (UnsatisfiedServletRequestParameterException ex) { + assertArrayEquals("Invalid request parameter conditions", + new String[] { "foo=bar" }, ex.getParamConditions()); + } + } + @Test public void uriTemplateVariables() { PatternsRequestCondition patterns = new PatternsRequestCondition("/{path1}/{path2}"); @@ -414,6 +428,11 @@ public class RequestMappingInfoHandlerMappingTests { return ""; } + @RequestMapping(value = "/params", params="foo=bar") + public String param() { + return ""; + } + @RequestMapping(value = "/content", produces="application/xml") public String xmlContent() { return ""; From 9c032d52d40b232c4e12ff94a5edb7d4851d7251 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 22 Jan 2013 15:32:09 -0800 Subject: [PATCH 127/311] Allow TypeDescriptor array construction Add a static factory method that can be used to create an array TypeDescriptor with a specific element type. Allows array types with generic elements to be constructed. Issue: SPR-9792 --- .../core/convert/TypeDescriptor.java | 20 +++++++++++++++- .../core/convert/TypeDescriptorTests.java | 23 ++++++++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java b/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java index f320400e6a..59a7d09ace 100644 --- a/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java +++ b/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.core.convert; import java.lang.annotation.Annotation; +import java.lang.reflect.Array; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashMap; @@ -33,6 +34,7 @@ import org.springframework.util.ObjectUtils; * @author Keith Donald * @author Andy Clement * @author Juergen Hoeller + * @author Phillip Webb * @since 3.0 */ public class TypeDescriptor { @@ -146,6 +148,22 @@ public class TypeDescriptor { return new TypeDescriptor(mapType, keyTypeDescriptor, valueTypeDescriptor); } + /** + * Create a new type descriptor as an array of the specified type. For example to + * create a {@code Map[]} use + * {@code TypeDescriptor.array(TypeDescriptor.map(Map.class, TypeDescriptor.value(String.class), TypeDescriptor.value(String.class)))}. + * @param elementTypeDescriptor the {@link TypeDescriptor} of the array element or {@code null} + * @return an array {@link TypeDescriptor} or {@code null} if {@code elementTypeDescriptor} is {@code null} + * @since 3.2 + */ + public static TypeDescriptor array(TypeDescriptor elementTypeDescriptor) { + if(elementTypeDescriptor == null) { + return null; + } + Class type = Array.newInstance(elementTypeDescriptor.getType(), 0).getClass(); + return new TypeDescriptor(type, elementTypeDescriptor, null, null, elementTypeDescriptor.getAnnotations()); + } + /** * Creates a type descriptor for a nested type declared within the method parameter. * For example, if the methodParameter is a List<String> and the nestingLevel is 1, the nested type descriptor will be String.class. diff --git a/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java b/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java index 90e2bf893b..6597ab46a7 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/TypeDescriptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -36,6 +37,7 @@ import static org.junit.Assert.*; /** * @author Keith Donald * @author Andy Clement + * @author Phillip Webb */ @SuppressWarnings("rawtypes") public class TypeDescriptorTests { @@ -849,4 +851,23 @@ public class TypeDescriptorTests { assertEquals(TypeDescriptor.forObject(new CustomMap()).getMapValueTypeDescriptor(), TypeDescriptor.valueOf(Integer.class)); } + @Test + public void createMapArray() throws Exception { + TypeDescriptor mapType = TypeDescriptor.map(LinkedHashMap.class, TypeDescriptor.valueOf(String.class), TypeDescriptor.valueOf(Integer.class)); + TypeDescriptor arrayType = TypeDescriptor.array(mapType); + assertEquals(arrayType.getType(), LinkedHashMap[].class); + assertEquals(arrayType.getElementTypeDescriptor(), mapType); + } + + + @Test + public void createStringArray() throws Exception { + TypeDescriptor arrayType = TypeDescriptor.array(TypeDescriptor.valueOf(String.class)); + assertEquals(arrayType, TypeDescriptor.valueOf(String[].class)); + } + + @Test + public void createNullArray() throws Exception { + assertNull(TypeDescriptor.array(null)); + } } From 89db04ec75225834dee988769a339ba2a5ee52b3 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 01:29:02 +0100 Subject: [PATCH 128/311] Added "awaitTerminationSeconds" property to ThreadPoolTaskExecutor/ThreadPoolTaskScheduler Issue: SPR-5387 --- .../ExecutorConfigurationSupport.java | 73 ++++++++++++++++++- 1 file changed, 69 insertions(+), 4 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java index 964872e1d6..91764b3328 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java +++ b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -54,6 +55,8 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac private boolean waitForTasksToCompleteOnShutdown = false; + private int awaitTerminationSeconds = 0; + private String beanName; private ExecutorService executor; @@ -85,9 +88,17 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac } /** - * Set whether to wait for scheduled tasks to complete on shutdown. - *

Default is "false". Switch this to "true" if you prefer - * fully completed tasks at the expense of a longer shutdown phase. + * Set whether to wait for scheduled tasks to complete on shutdown, + * not interrupting running tasks and executing all tasks in the queue. + *

Default is "false", shutting down immediately through interrupting + * ongoing tasks and clearing the queue. Switch this flag to "true" if you + * prefer fully completed tasks at the expense of a longer shutdown phase. + *

Note that Spring's container shutdown continues while ongoing tasks + * are being completed. If you want this executor to block and wait for the + * termination of tasks before the rest of the container continues to shut + * down - e.g. in order to keep up other resources that your tasks may need -, + * set the {@link #setAwaitTerminationSeconds "awaitTerminationSeconds"} + * property instead of or in addition to this property. * @see java.util.concurrent.ExecutorService#shutdown() * @see java.util.concurrent.ExecutorService#shutdownNow() */ @@ -95,6 +106,33 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac this.waitForTasksToCompleteOnShutdown = waitForJobsToCompleteOnShutdown; } + /** + * Set the maximum number of seconds that this executor is supposed to block + * on shutdown in order to wait for remaining tasks to complete their execution + * before the rest of the container continues to shut down. This is particularly + * useful if your remaining tasks are likely to need access to other resources + * that are also managed by the container. + *

By default, this executor won't wait for the termination of tasks at all. + * It will either shut down immediately, interrupting ongoing tasks and clearing + * the remaining task queue - or, if the + * {@link #setWaitForTasksToCompleteOnShutdown "waitForTasksToCompleteOnShutdown"} + * flag has been set to {@code true}, it will continue to fully execute all + * ongoing tasks as well as all remaining tasks in the queue, in parallel to + * the rest of the container shutting down. + *

In either case, if you specify an await-termination period using this property, + * this executor will wait for the given time (max) for the termination of tasks. + * As a rule of thumb, specify a significantly higher timeout here if you set + * "waitForTasksToCompleteOnShutdown" to {@code true} at the same time, + * since all remaining tasks in the queue will still get executed - in contrast + * to the default shutdown behavior where it's just about waiting for currently + * executing tasks that aren't reacting to thread interruption. + * @see java.util.concurrent.ExecutorService#shutdown() + * @see java.util.concurrent.ExecutorService#awaitTermination + */ + public void setAwaitTerminationSeconds(int awaitTerminationSeconds) { + this.awaitTerminationSeconds = awaitTerminationSeconds; + } + public void setBeanName(String name) { this.beanName = name; } @@ -145,6 +183,8 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac /** * Perform a shutdown on the ThreadPoolExecutor. * @see java.util.concurrent.ExecutorService#shutdown() + * @see java.util.concurrent.ExecutorService#shutdownNow() + * @see #awaitTerminationIfNecessary() */ public void shutdown() { if (logger.isInfoEnabled()) { @@ -156,6 +196,31 @@ public abstract class ExecutorConfigurationSupport extends CustomizableThreadFac else { this.executor.shutdownNow(); } + awaitTerminationIfNecessary(); + } + + /** + * Wait for the executor to terminate, according to the value of the + * {@link #setAwaitTerminationSeconds "awaitTerminationSeconds"} property. + */ + private void awaitTerminationIfNecessary() { + if (this.awaitTerminationSeconds > 0) { + try { + if (!this.executor.awaitTermination(this.awaitTerminationSeconds, TimeUnit.SECONDS)) { + if (logger.isWarnEnabled()) { + logger.warn("Timed out while waiting for executor" + + (this.beanName != null ? " '" + this.beanName + "'" : "") + " to terminate"); + } + } + } + catch (InterruptedException ex) { + if (logger.isWarnEnabled()) { + logger.warn("Interrupted while waiting for executor" + + (this.beanName != null ? " '" + this.beanName + "'" : "") + " to terminate"); + } + Thread.currentThread().interrupt(); + } + } } } From d5af9dc0a56214aa006c37190ba0110a7b4a5d89 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 01:29:56 +0100 Subject: [PATCH 129/311] Polishing --- .../scheduling/support/PeriodicTrigger.java | 18 ++++++++---------- .../ThreadPoolTaskSchedulerTests.java | 16 +++++++++------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java b/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java index b494e4c5ff..e25fdd3f25 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/PeriodicTrigger.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,8 +31,8 @@ import org.springframework.util.Assert; * completion time). To measure the interval between the * scheduled start time of each execution instead, set the * 'fixedRate' property to {@code true}. - *

- * Note that the TaskScheduler interface already defines methods for scheduling + * + *

Note that the TaskScheduler interface already defines methods for scheduling * tasks at fixed-rate or with fixed-delay. Both also support an optional value * for the initial delay. Those methods should be used directly whenever * possible. The value of this Trigger implementation is that it can be used @@ -68,7 +68,7 @@ public class PeriodicTrigger implements Trigger { */ public PeriodicTrigger(long period, TimeUnit timeUnit) { Assert.isTrue(period >= 0, "period must not be negative"); - this.timeUnit = (timeUnit != null) ? timeUnit : TimeUnit.MILLISECONDS; + this.timeUnit = (timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS); this.period = this.timeUnit.toMillis(period); } @@ -91,6 +91,7 @@ public class PeriodicTrigger implements Trigger { this.fixedRate = fixedRate; } + /** * Returns the time after which a task should run again. */ @@ -104,6 +105,7 @@ public class PeriodicTrigger implements Trigger { return new Date(triggerContext.lastCompletionTime().getTime() + this.period); } + @Override public boolean equals(Object obj) { if (this == obj) { @@ -113,16 +115,12 @@ public class PeriodicTrigger implements Trigger { return false; } PeriodicTrigger other = (PeriodicTrigger) obj; - return this.fixedRate == other.fixedRate - && this.initialDelay == other.initialDelay - && this.period == other.period; + return (this.fixedRate == other.fixedRate && this.initialDelay == other.initialDelay && this.period == other.period); } @Override public int hashCode() { - return (this.fixedRate ? 17 : 29) + - (int) (37 * this.period) + - (int) (41 * this.initialDelay); + return (this.fixedRate ? 17 : 29) + (int) (37 * this.period) + (int) (41 * this.initialDelay); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java index 7320cea1d1..ddaa2b0fce 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/concurrent/ThreadPoolTaskSchedulerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,6 @@ package org.springframework.scheduling.concurrent; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - import java.util.Date; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; @@ -29,6 +24,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -36,6 +32,8 @@ import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; import org.springframework.util.ErrorHandler; +import static org.junit.Assert.*; + /** * @author Mark Fisher * @since 3.0 @@ -44,7 +42,6 @@ public class ThreadPoolTaskSchedulerTests { private static final String THREAD_NAME_PREFIX = "test-"; - private final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); @@ -54,6 +51,11 @@ public class ThreadPoolTaskSchedulerTests { scheduler.afterPropertiesSet(); } + @After + public void shutdownScheduler() { + scheduler.destroy(); + } + // test methods From 5fb75304eb6571bcf838e6af4814ac09449e9e1c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 01:31:28 +0100 Subject: [PATCH 130/311] Final preparations for 3.2.1 --- src/dist/changelog.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 771470cc1d..af25c8c883 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -23,6 +23,8 @@ Changes in version 3.2.1 (2013-01-24) * MBeanExporter does not log warnings for manually unregistered MBeans (SPR-9451) * AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup (SPR-7955) * EhCacheManagerFactoryBean applies cacheManagerName ahead of creation (for EHCache 2.5 compatibility; SPR-9171) +* added "awaitTerminationSeconds" property to ThreadPoolTaskExecutor/ThreadPoolTaskScheduler (SPR-5387) +* aligned XML scheduled-task elements with @Scheduled in terms of kicking in after context refresh (SPR-9231) * reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd (SPR-10177) * spring-task-3.2.xsd allows for SpEL expressions in initial-delay attribute (SPR-10102) * spring-jms-3.2.xsd allows for SpEL expressions in prefetch and receive-timeout attributes (SPR-9553) From 7e74fd2b7fb30e6206d40bb7235d82433682386a Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 22 Jan 2013 17:53:30 -0800 Subject: [PATCH 131/311] Consider primary attribute with getBean(Class) Update DefaultListableBeanFactory.getBean(Class beanClass) to consider the 'primary' attribute of bean definitions. This makes getBean() behave in the same way as autowiring. Issue: SPR-7854 --- .../support/DefaultListableBeanFactory.java | 15 +++++++++ .../DefaultListableBeanFactoryTests.java | 33 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index 432663ab79..23512f9e23 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -90,6 +90,7 @@ import org.springframework.util.StringUtils; * @author Sam Brannen * @author Costin Leau * @author Chris Beams + * @author Phillip Webb * @since 16 April 2001 * @see StaticListableBeanFactory * @see PropertiesBeanDefinitionReader @@ -272,6 +273,20 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto return getBean(beanNames[0], requiredType); } else if (beanNames.length > 1) { + T primaryBean = null; + for (String beanName : beanNames) { + T beanInstance = getBean(beanName, requiredType); + if (isPrimary(beanName, beanInstance)) { + if(primaryBean != null) { + throw new NoUniqueBeanDefinitionException(requiredType, beanNames.length, + "more than one 'primary' bean found of required type: " + Arrays.asList(beanNames)); + } + primaryBean = beanInstance; + } + } + if(primaryBean != null) { + return primaryBean; + } throw new NoUniqueBeanDefinitionException(requiredType, beanNames); } else if (getParentBeanFactory() != null) { diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index e93e95973d..fd134fcc3d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -17,6 +17,8 @@ package org.springframework.beans.factory; import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; @@ -49,7 +51,9 @@ import javax.security.auth.Subject; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Ignore; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.beans.BeansException; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.NotWritablePropertyException; @@ -102,11 +106,14 @@ import org.springframework.util.StopWatch; * @author Rick Evans * @author Sam Brannen * @author Chris Beams + * @author Phillip Webb */ public class DefaultListableBeanFactoryTests { private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class); + @Rule + public ExpectedException thrown = ExpectedException.none(); @Test public void testUnreferencedSingletonWasInstantiated() { @@ -1285,6 +1292,32 @@ public class DefaultListableBeanFactoryTests { lbf.getBean(TestBean.class); } + @Test + public void testGetBeanByTypeWithPrimary() throws Exception { + DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); + RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class); + RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); + bd2.setPrimary(true); + lbf.registerBeanDefinition("bd1", bd1); + lbf.registerBeanDefinition("bd2", bd2); + TestBean bean = lbf.getBean(TestBean.class); + assertThat(bean.getBeanName(), equalTo("bd2")); + } + + @Test + public void testGetBeanByTypeWithMultiplePrimary() throws Exception { + DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); + RootBeanDefinition bd1 = new RootBeanDefinition(TestBean.class); + bd1.setPrimary(true); + RootBeanDefinition bd2 = new RootBeanDefinition(TestBean.class); + bd2.setPrimary(true); + lbf.registerBeanDefinition("bd1", bd1); + lbf.registerBeanDefinition("bd2", bd2); + thrown.expect(NoUniqueBeanDefinitionException.class); + thrown.expectMessage(containsString("more than one 'primary'")); + lbf.getBean(TestBean.class); + } + @Test public void testGetBeanByTypeFiltersOutNonAutowireCandidates() { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); From a1aba23aa96595d1795db1ddc3ce7ef35fb4ec19 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 23 Jan 2013 16:47:23 +0100 Subject: [PATCH 132/311] Polish Javadoc in TypeDescriptor - fix @since version in array() - format method-level Javadoc - unescape HTML-escaped angle brackets with {@code} blocks --- .../core/convert/TypeDescriptor.java | 148 +++++++++++------- 1 file changed, 90 insertions(+), 58 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java b/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java index 59a7d09ace..79c134e7cf 100644 --- a/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java +++ b/spring-core/src/main/java/org/springframework/core/convert/TypeDescriptor.java @@ -35,6 +35,7 @@ import org.springframework.util.ObjectUtils; * @author Andy Clement * @author Juergen Hoeller * @author Phillip Webb + * @author Sam Brannen * @since 3.0 */ public class TypeDescriptor { @@ -77,7 +78,8 @@ public class TypeDescriptor { /** * Create a new type descriptor from a {@link MethodParameter}. - * Use this constructor when a source or target conversion point is a constructor parameter, method parameter, or method return value. + *

Use this constructor when a source or target conversion point is a + * constructor parameter, method parameter, or method return value. * @param methodParameter the method parameter */ public TypeDescriptor(MethodParameter methodParameter) { @@ -86,7 +88,7 @@ public class TypeDescriptor { /** * Create a new type descriptor from a {@link Field}. - * Use this constructor when source or target conversion point is a field. + *

Use this constructor when a source or target conversion point is a field. * @param field the field */ public TypeDescriptor(Field field) { @@ -95,7 +97,8 @@ public class TypeDescriptor { /** * Create a new type descriptor from a {@link Property}. - * Use this constructor when a source or target conversion point is a property on a Java class. + *

Use this constructor when a source or target conversion point is a + * property on a Java class. * @param property the property */ public TypeDescriptor(Property property) { @@ -105,8 +108,11 @@ public class TypeDescriptor { /** * Create a new type descriptor from the given type. - * Use this to instruct the conversion system to convert an object to a specific target type, when no type location such as a method parameter or field is available to provide additional conversion context. - * Generally prefer use of {@link #forObject(Object)} for constructing type descriptors from source objects, as it handles the null object case. + *

Use this to instruct the conversion system to convert an object to a + * specific target type, when no type location such as a method parameter or + * field is available to provide additional conversion context. + *

Generally prefer use of {@link #forObject(Object)} for constructing type + * descriptors from source objects, as it handles the {@code null} object case. * @param type the class * @return the type descriptor */ @@ -116,12 +122,15 @@ public class TypeDescriptor { } /** - * Create a new type descriptor from a java.util.Collection type. - * Useful for converting to typed Collections. - * For example, a List<String> could be converted to a List<EmailAddress> by converting to a targetType built with this method. - * The method call to construct such a TypeDescriptor would look something like: collection(List.class, TypeDescriptor.valueOf(EmailAddress.class)); + * Create a new type descriptor from a {@link java.util.Collection} type. + *

Useful for converting to typed Collections. + *

For example, a {@code List} could be converted to a + * {@code List} by converting to a targetType built with this method. + * The method call to construct such a {@code TypeDescriptor} would look something + * like: {@code collection(List.class, TypeDescriptor.valueOf(EmailAddress.class));} * @param collectionType the collection type, which must implement {@link Collection}. - * @param elementTypeDescriptor a descriptor for the collection's element type, used to convert collection elements + * @param elementTypeDescriptor a descriptor for the collection's element type, + * used to convert collection elements * @return the collection type descriptor */ public static TypeDescriptor collection(Class collectionType, TypeDescriptor elementTypeDescriptor) { @@ -132,9 +141,9 @@ public class TypeDescriptor { } /** - * Create a new type descriptor from a java.util.Map type. - * Useful for Converting to typed Maps. - * For example, a Map<String, String> could be converted to a Map<Id, EmailAddress> by converting to a targetType built with this method: + * Create a new type descriptor from a {@link java.util.Map} type. + *

Useful for converting to typed Maps. + *

For example, a Map<String, String> could be converted to a Map<Id, EmailAddress> by converting to a targetType built with this method: * The method call to construct such a TypeDescriptor would look something like: map(Map.class, TypeDescriptor.valueOf(Id.class), TypeDescriptor.valueOf(EmailAddress.class)); * @param mapType the map type, which must implement {@link Map} * @param keyTypeDescriptor a descriptor for the map's key type, used to convert map keys @@ -149,12 +158,12 @@ public class TypeDescriptor { } /** - * Create a new type descriptor as an array of the specified type. For example to - * create a {@code Map[]} use + * Create a new type descriptor as an array of the specified type. + *

For example to create a {@code Map[]} use * {@code TypeDescriptor.array(TypeDescriptor.map(Map.class, TypeDescriptor.value(String.class), TypeDescriptor.value(String.class)))}. * @param elementTypeDescriptor the {@link TypeDescriptor} of the array element or {@code null} * @return an array {@link TypeDescriptor} or {@code null} if {@code elementTypeDescriptor} is {@code null} - * @since 3.2 + * @since 3.2.1 */ public static TypeDescriptor array(TypeDescriptor elementTypeDescriptor) { if(elementTypeDescriptor == null) { @@ -166,17 +175,26 @@ public class TypeDescriptor { /** * Creates a type descriptor for a nested type declared within the method parameter. - * For example, if the methodParameter is a List<String> and the nestingLevel is 1, the nested type descriptor will be String.class. - * If the methodParameter is a List> and the nestingLevel is 2, the nested type descriptor will also be a String.class. - * If the methodParameter is a Map and the nesting level is 1, the nested type descriptor will be String, derived from the map value. - * If the methodParameter is a List> and the nesting level is 2, the nested type descriptor will be String, derived from the map value. - * Returns null if a nested type cannot be obtained because it was not declared. - * For example, if the method parameter is a List<?>, the nested type descriptor returned will be null. + *

For example, if the methodParameter is a {@code List} and the + * nesting level is 1, the nested type descriptor will be String.class. + *

If the methodParameter is a {@code List>} and the nesting + * level is 2, the nested type descriptor will also be a String.class. + *

If the methodParameter is a {@code Map} and the nesting + * level is 1, the nested type descriptor will be String, derived from the map value. + *

If the methodParameter is a {@code List>} and the + * nesting level is 2, the nested type descriptor will be String, derived from the map value. + *

Returns {@code null} if a nested type cannot be obtained because it was not declared. + * For example, if the method parameter is a {@code List}, the nested type + * descriptor returned will be {@code null}. * @param methodParameter the method parameter with a nestingLevel of 1 - * @param nestingLevel the nesting level of the collection/array element or map key/value declaration within the method parameter - * @return the nested type descriptor at the specified nesting level, or null if it could not be obtained - * @throws IllegalArgumentException if the nesting level of the input {@link MethodParameter} argument is not 1 - * @throws IllegalArgumentException if the types up to the specified nesting level are not of collection, array, or map types + * @param nestingLevel the nesting level of the collection/array element or + * map key/value declaration within the method parameter + * @return the nested type descriptor at the specified nesting level, or null + * if it could not be obtained + * @throws IllegalArgumentException if the nesting level of the input + * {@link MethodParameter} argument is not 1 + * @throws IllegalArgumentException if the types up to the specified nesting + * level are not of collection, array, or map types */ public static TypeDescriptor nested(MethodParameter methodParameter, int nestingLevel) { if (methodParameter.getNestingLevel() != 1) { @@ -187,16 +205,23 @@ public class TypeDescriptor { /** * Creates a type descriptor for a nested type declared within the field. - *

For example, if the field is a {@code List<String>} and the nestingLevel is 1, the nested type descriptor will be {@code String.class}. - * If the field is a {@code List<List<String>>} and the nestingLevel is 2, the nested type descriptor will also be a {@code String.class}. - * If the field is a {@code Map<Integer, String>} and the nestingLevel is 1, the nested type descriptor will be String, derived from the map value. - * If the field is a {@code List<Map<Integer, String>>} and the nestingLevel is 2, the nested type descriptor will be String, derived from the map value. - * Returns {@code null} if a nested type cannot be obtained because it was not declared. - * For example, if the field is a {@code List<?>}, the nested type descriptor returned will be {@code null}. + *

For example, if the field is a {@code List} and the nesting + * level is 1, the nested type descriptor will be {@code String.class}. + *

If the field is a {@code List>} and the nesting level is + * 2, the nested type descriptor will also be a {@code String.class}. + *

If the field is a {@code Map} and the nesting level + * is 1, the nested type descriptor will be String, derived from the map value. + *

If the field is a {@code List>} and the nesting + * level is 2, the nested type descriptor will be String, derived from the map value. + *

Returns {@code null} if a nested type cannot be obtained because it was not declared. + * For example, if the field is a {@code List}, the nested type descriptor returned will be {@code null}. * @param field the field - * @param nestingLevel the nesting level of the collection/array element or map key/value declaration within the field - * @return the nested type descriptor at the specified nestingLevel, or null if it could not be obtained - * @throws IllegalArgumentException if the types up to the specified nesting level are not of collection, array, or map types + * @param nestingLevel the nesting level of the collection/array element or + * map key/value declaration within the field + * @return the nested type descriptor at the specified nesting level, or null + * if it could not be obtained + * @throws IllegalArgumentException if the types up to the specified nesting + * level are not of collection, array, or map types */ public static TypeDescriptor nested(Field field, int nestingLevel) { return nested(new FieldDescriptor(field), nestingLevel); @@ -204,16 +229,24 @@ public class TypeDescriptor { /** * Creates a type descriptor for a nested type declared within the property. - *

For example, if the property is a {@code List<String>} and the nestingLevel is 1, the nested type descriptor will be {@code String.class}. - * If the property is a {@code List<List<String>>} and the nestingLevel is 2, the nested type descriptor will also be a {@code String.class}. - * If the property is a {@code Map<Integer, String>} and the nestingLevel is 1, the nested type descriptor will be String, derived from the map value. - * If the property is a {@code List<Map<Integer, String>>} and the nestingLevel is 2, the nested type descriptor will be String, derived from the map value. - * Returns {@code null} if a nested type cannot be obtained because it was not declared. - * For example, if the property is a {@code List<?>}, the nested type descriptor returned will be {@code null}. + *

For example, if the property is a {@code List} and the nesting + * level is 1, the nested type descriptor will be {@code String.class}. + *

If the property is a {@code List>} and the nesting level + * is 2, the nested type descriptor will also be a {@code String.class}. + *

If the property is a {@code Map} and the nesting level + * is 1, the nested type descriptor will be String, derived from the map value. + *

If the property is a {@code List>} and the nesting + * level is 2, the nested type descriptor will be String, derived from the map value. + *

Returns {@code null} if a nested type cannot be obtained because it was not declared. + * For example, if the property is a {@code List}, the nested type descriptor + * returned will be {@code null}. * @param property the property - * @param nestingLevel the nesting level of the collection/array element or map key/value declaration within the property - * @return the nested type descriptor at the specified nestingLevel, or {@code null} if it could not be obtained - * @throws IllegalArgumentException if the types up to the specified nesting level are not of collection, array, or map types + * @param nestingLevel the nesting level of the collection/array element or + * map key/value declaration within the property + * @return the nested type descriptor at the specified nesting level, or + * {@code null} if it could not be obtained + * @throws IllegalArgumentException if the types up to the specified nesting + * level are not of collection, array, or map types */ public static TypeDescriptor nested(Property property, int nestingLevel) { return nested(new BeanPropertyDescriptor(property), nestingLevel); @@ -221,8 +254,8 @@ public class TypeDescriptor { /** * Create a new type descriptor for an object. - * Use this factory method to introspect a source object before asking the conversion system to convert it to some another type. - * If the provided object is null, returns null, else calls {@link #valueOf(Class)} to build a TypeDescriptor from the object's class. + *

Use this factory method to introspect a source object before asking the conversion system to convert it to some another type. + *

If the provided object is null, returns null, else calls {@link #valueOf(Class)} to build a TypeDescriptor from the object's class. * @param source the source object * @return the type descriptor */ @@ -232,7 +265,7 @@ public class TypeDescriptor { /** * The type of the backing class, method parameter, field, or property described by this TypeDescriptor. - * Returns primitive types as-is. + *

Returns primitive types as-is. *

See {@link #getObjectType()} for a variation of this operation that resolves primitive types * to their corresponding Object types if necessary. * @return the type, or {@code null} @@ -253,7 +286,7 @@ public class TypeDescriptor { /** * Narrows this {@link TypeDescriptor} by setting its type to the class of the provided value. - * If the value is {@code null}, no narrowing is performed and this TypeDescriptor is returned unchanged. + *

If the value is {@code null}, no narrowing is performed and this TypeDescriptor is returned unchanged. *

Designed to be called by binding frameworks when they read property, field, or method return values. * Allows such frameworks to narrow a TypeDescriptor built from a declared property, field, or method return value type. * For example, a field declared as {@code java.lang.Object} would be narrowed to {@code java.util.HashMap} @@ -273,7 +306,6 @@ public class TypeDescriptor { /** * Cast this {@link TypeDescriptor} to a superclass or implemented interface * preserving annotations and nested type context. - * * @param superType the super type to cast to (can be {@code null} * @return a new TypeDescriptor for the up-cast type * @throws IllegalArgumentException if this type is not assignable to the super-type @@ -342,7 +374,7 @@ public class TypeDescriptor { /** * Returns true if an object of this type descriptor can be assigned to the location described by the given type descriptor. - * For example, valueOf(String.class).isAssignableTo(valueOf(CharSequence.class)) returns true because a String value can be assigned to a CharSequence variable. + *

For example, valueOf(String.class).isAssignableTo(valueOf(CharSequence.class)) returns true because a String value can be assigned to a CharSequence variable. * On the other hand, valueOf(Number.class).isAssignableTo(valueOf(Integer.class)) returns false because, while all Integers are Numbers, not all Numbers are Integers. *

* For arrays, collections, and maps, element and key/value types are checked if declared. @@ -400,10 +432,10 @@ public class TypeDescriptor { /** * If this type is a {@link Collection} or an Array, creates a element TypeDescriptor from the provided collection or array element. - * Narrows the {@link #getElementTypeDescriptor() elementType} property to the class of the provided collection or array element. + *

Narrows the {@link #getElementTypeDescriptor() elementType} property to the class of the provided collection or array element. * For example, if this describes a java.util.List<java.lang.Number< and the element argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer. * If this describes a java.util.List<?> and the element argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer as well. - * Annotation and nested type context will be preserved in the narrowed TypeDescriptor that is returned. + *

Annotation and nested type context will be preserved in the narrowed TypeDescriptor that is returned. * @param element the collection or array element * @return a element type descriptor, narrowed to the type of the provided element * @throws IllegalStateException if this type is not a java.util.Collection or Array type @@ -435,10 +467,10 @@ public class TypeDescriptor { /** * If this type is a {@link Map}, creates a mapKey {@link TypeDescriptor} from the provided map key. - * Narrows the {@link #getMapKeyTypeDescriptor() mapKeyType} property to the class of the provided map key. + *

Narrows the {@link #getMapKeyTypeDescriptor() mapKeyType} property to the class of the provided map key. * For example, if this describes a java.util.Map<java.lang.Number, java.lang.String< and the key argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer. - * If this describes a java.util.Map<?, ?> and the key argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer as well. - * Annotation and nested type context will be preserved in the narrowed TypeDescriptor that is returned. + *

If this describes a java.util.Map<?, ?> and the key argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer as well. + *

Annotation and nested type context will be preserved in the narrowed TypeDescriptor that is returned. * @param mapKey the map key * @return the map key type descriptor * @throws IllegalStateException if this type is not a java.util.Map @@ -450,7 +482,7 @@ public class TypeDescriptor { /** * If this type is a {@link Map} and its value type is parameterized, returns the map's value type. - * If the Map's value type is not parameterized, returns null indicating the value type is not declared. + *

If the Map's value type is not parameterized, returns null indicating the value type is not declared. * @return the Map value type, or {@code null} if this type is a Map but its value type is not parameterized * @throws IllegalStateException if this type is not a java.util.Map */ @@ -461,10 +493,10 @@ public class TypeDescriptor { /** * If this type is a {@link Map}, creates a mapValue {@link TypeDescriptor} from the provided map value. - * Narrows the {@link #getMapValueTypeDescriptor() mapValueType} property to the class of the provided map value. + *

Narrows the {@link #getMapValueTypeDescriptor() mapValueType} property to the class of the provided map value. * For example, if this describes a java.util.Map<java.lang.String, java.lang.Number< and the value argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer. * If this describes a java.util.Map<?, ?> and the value argument is a java.lang.Integer, the returned TypeDescriptor will be java.lang.Integer as well. - * Annotation and nested type context will be preserved in the narrowed TypeDescriptor that is returned. + *

Annotation and nested type context will be preserved in the narrowed TypeDescriptor that is returned. * @param mapValue the map value * @return the map value type descriptor * @throws IllegalStateException if this type is not a java.util.Map From 3b8aba9ccd0ca0a437a9425471644b1d01a99795 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 23 Jan 2013 16:48:08 +0100 Subject: [PATCH 133/311] Fix typo in ContextLifecycleScheduledTaskRegistrar --- .../config/ContextLifecycleScheduledTaskRegistrar.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java b/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java index eacf7ed25c..8a0fba8c3b 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java +++ b/spring-context/src/main/java/org/springframework/scheduling/config/ContextLifecycleScheduledTaskRegistrar.java @@ -22,9 +22,9 @@ import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; /** - * {@link ScheduledTaskRegistrar} subclass that redirect the actual scheduling + * {@link ScheduledTaskRegistrar} subclass that redirects the actual scheduling * of tasks to the {@link ContextRefreshedEvent} callback. Falls back to regular - * {@link ScheduledTaskRegistrar} behavior when not running within an ApplicationContext. + * {@code ScheduledTaskRegistrar} behavior when not running within an ApplicationContext. * * @author Juergen Hoeller * @since 3.2.1 From e4f1f682e2a7eb8e7589f1281d96132453d01523 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Wed, 23 Jan 2013 17:09:45 +0100 Subject: [PATCH 134/311] Update distribution README regarding paths - Corrected path to 'docs/spring-framework-reference' - Minor formatting changes --- src/dist/readme.txt | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/dist/readme.txt b/src/dist/readme.txt index e55fefae19..c58486a587 100644 --- a/src/dist/readme.txt +++ b/src/dist/readme.txt @@ -1,12 +1,11 @@ Spring Framework version ${version} -=============================================================================== +================================================================================ -To find out what has changed since any earlier releases, see -'docs/changelog.txt'. +To find out what has changed since any earlier releases, see 'docs/changelog.txt'. -Please consult the documentation located within the 'docs/reference' directory -of this release and also visit the official Spring Framework home at -http://www.springsource.org/spring-framework +Please consult the documentation located within the +'docs/spring-framework-reference' directory of this release and also visit +the official Spring Framework home at http://www.springsource.org/spring-framework There you will find links to the forum, issue tracker, and other resources. From 9982b4c01a8c7be0961e58b58ed83731c40449ff Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Wed, 23 Jan 2013 13:35:14 -0500 Subject: [PATCH 135/311] Add BS and VT char escape sequences to JavaScriptUtils Issue: SPR-9983 --- .../web/util/JavaScriptUtils.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java b/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java index b28d398687..0ee697f6d9 100644 --- a/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java +++ b/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,21 +21,21 @@ package org.springframework.web.util; * Escapes based on the JavaScript 1.5 recommendation. * *

Reference: - * - * Core JavaScript 1.5 Guide - * + * + * JavaScript Guide on Mozilla Developer Network. * * @author Juergen Hoeller * @author Rob Harrop + * @author Rossen Stoyanchev * @since 1.1.1 */ public class JavaScriptUtils { /** - * Turn special characters into escaped characters conforming to JavaScript. - * Handles complete character set defined in HTML 4.01 recommendation. + * Turn JavaScript special characters into escaped characters. + * * @param input the input string - * @return the escaped string + * @return the string with escaped characters */ public static String javaScriptEscape(String input) { if (input == null) { @@ -73,6 +73,13 @@ public class JavaScriptUtils { else if (c == '\f') { filtered.append("\\f"); } + else if (c == '\b') { + filtered.append("\\b"); + } + // No '\v' in Java, use octal value for VT ascii char + else if (c == '\013') { + filtered.append("\\v"); + } else { filtered.append(c); } From f3ff98d86275e19e6828f9c3a0c432de0587bbbe Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 23 Jan 2013 11:02:15 -0800 Subject: [PATCH 136/311] Allow nulls with multiple embedded value resolvers Allow an embedded value resolver added to an AbstractBeanFactory to return null without adversely effecting any subsequent resolvers. Issue: SPR-8565 --- .../factory/support/AbstractBeanFactory.java | 2 +- .../DefaultListableBeanFactoryTests.java | 26 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index 8db728ae57..f298c6522f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -746,7 +746,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { - result = resolver.resolveStringValue(result); + result = (result == null ? null : resolver.resolveStringValue(result)); } return result; } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index fd134fcc3d..fc4ac5d55c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -28,6 +28,11 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import java.io.Closeable; import java.lang.reflect.Field; @@ -97,6 +102,7 @@ import org.springframework.tests.sample.beans.SideEffectBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.sample.beans.factory.DummyFactory; import org.springframework.util.StopWatch; +import org.springframework.util.StringValueResolver; /** * Tests properties population and autowire behavior. @@ -2261,6 +2267,26 @@ public class DefaultListableBeanFactoryTests { assertThat(bf.containsBean("bogus"), is(false)); } + @Test + public void resolveEmbeddedValue() throws Exception { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + StringValueResolver r1 = mock(StringValueResolver.class); + StringValueResolver r2 = mock(StringValueResolver.class); + StringValueResolver r3 = mock(StringValueResolver.class); + bf.addEmbeddedValueResolver(r1); + bf.addEmbeddedValueResolver(r2); + bf.addEmbeddedValueResolver(r3); + given(r1.resolveStringValue("A")).willReturn("B"); + given(r2.resolveStringValue("B")).willReturn(null); + given(r3.resolveStringValue(isNull(String.class))).willThrow(new IllegalArgumentException()); + + bf.resolveEmbeddedValue("A"); + + verify(r1).resolveStringValue("A"); + verify(r2).resolveStringValue("B"); + verify(r3, never()).resolveStringValue(isNull(String.class)); + } + static class A { } static class B { } From 2ee70d683da7971ed2fca41ffbc440d61dd61d00 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Wed, 23 Jan 2013 14:59:15 -0500 Subject: [PATCH 137/311] Suppress serialization warning --- .../org/springframework/web/util/HierarchicalUriComponents.java | 1 + .../java/org/springframework/web/util/OpaqueUriComponents.java | 1 + 2 files changed, 2 insertions(+) diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index f3a5ec9013..103784e9c2 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -41,6 +41,7 @@ import org.springframework.util.StringUtils; * @since 3.1.3 * @see Hierarchical URIs */ +@SuppressWarnings("serial") final class HierarchicalUriComponents extends UriComponents { private static final char PATH_DELIMITER = '/'; diff --git a/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java index d896518b29..6e51c77dff 100644 --- a/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java @@ -33,6 +33,7 @@ import org.springframework.util.ObjectUtils; * @since 3.2 * @see Hierarchical vs Opaque URIs */ +@SuppressWarnings("serial") final class OpaqueUriComponents extends UriComponents { private static final MultiValueMap QUERY_PARAMS_NONE = new LinkedMultiValueMap(0); From 4dde7c4c160a5512dc474a230e3093e8d32354c9 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 13:40:22 +0100 Subject: [PATCH 138/311] MBeanInfoAssembler impls expose actual method parameter names if possible Issue: SPR-9985 --- .../AbstractReflectiveMBeanInfoAssembler.java | 46 ++++++++++++++++--- .../assembler/MetadataMBeanInfoAssembler.java | 9 ++-- ...ethodNameBasedMBeanInfoAssemblerTests.java | 11 ++++- 3 files changed, 54 insertions(+), 12 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java index d38e5be948..f953d9465c 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/assembler/AbstractReflectiveMBeanInfoAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,8 @@ import javax.management.modelmbean.ModelMBeanOperationInfo; import org.springframework.aop.framework.AopProxyUtils; import org.springframework.aop.support.AopUtils; import org.springframework.beans.BeanUtils; +import org.springframework.core.LocalVariableTableParameterNameDiscoverer; +import org.springframework.core.ParameterNameDiscoverer; import org.springframework.jmx.support.JmxUtils; /** @@ -49,6 +51,7 @@ import org.springframework.jmx.support.JmxUtils; * * @author Rob Harrop * @author Juergen Hoeller + * @author David Boden * @since 1.2 * @see #includeOperation * @see #includeReadAttribute @@ -177,6 +180,8 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean private boolean exposeClassDescriptor = false; + private ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); + /** * Set the default for the JMX field "currencyTimeLimit". @@ -254,6 +259,23 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean return this.exposeClassDescriptor; } + /** + * Set the ParameterNameDiscoverer to use for resolving method parameter + * names if needed (e.g. for parameter names of MBean operation methods). + *

The default is {@link LocalVariableTableParameterNameDiscoverer}. + */ + public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) { + this.parameterNameDiscoverer = parameterNameDiscoverer; + } + + /** + * Return the ParameterNameDiscoverer to use for resolving method parameter + * names if needed (may be {@code null} in order to skip parameter detection). + */ + protected ParameterNameDiscoverer getParameterNameDiscoverer() { + return this.parameterNameDiscoverer; + } + /** * Iterate through all properties on the MBean class and gives subclasses @@ -381,7 +403,8 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean * Creates an instance of {@code ModelMBeanOperationInfo} for the * given method. Populates the parameter info for the operation. * @param method the {@code Method} to create a {@code ModelMBeanOperationInfo} for - * @param name the name for the operation info + * @param name the logical name for the operation (method name or property name); + * not used by the default implementation but possibly by subclasses * @param beanKey the key associated with the MBean in the beans map * of the {@code MBeanExporter} * @return the {@code ModelMBeanOperationInfo} @@ -392,7 +415,7 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean return new ModelMBeanOperationInfo(getOperationDescription(method, beanKey), method); } else { - return new ModelMBeanOperationInfo(name, + return new ModelMBeanOperationInfo(method.getName(), getOperationDescription(method, beanKey), getOperationParameters(method, beanKey), method.getReturnType().getName(), @@ -476,16 +499,27 @@ public abstract class AbstractReflectiveMBeanInfoAssembler extends AbstractMBean /** * Create parameter info for the given method. - *

The default implementation returns an empty arry of {@code MBeanParameterInfo}. + *

The default implementation returns an empty array of {@code MBeanParameterInfo}. * @param method the {@code Method} to get the parameter information for * @param beanKey the key associated with the MBean in the beans map * of the {@code MBeanExporter} * @return the {@code MBeanParameterInfo} array */ protected MBeanParameterInfo[] getOperationParameters(Method method, String beanKey) { - return new MBeanParameterInfo[0]; - } + ParameterNameDiscoverer paramNameDiscoverer = getParameterNameDiscoverer(); + String[] paramNames = (paramNameDiscoverer != null ? paramNameDiscoverer.getParameterNames(method) : null); + if (paramNames == null) { + return new MBeanParameterInfo[0]; + } + MBeanParameterInfo[] info = new MBeanParameterInfo[paramNames.length]; + Class[] typeParameters = method.getParameterTypes(); + for(int i = 0; i < info.length; i++) { + info[i] = new MBeanParameterInfo(paramNames[i], typeParameters[i].getName(), paramNames[i]); + } + + return info; + } /** * Allows subclasses to add extra fields to the {@code Descriptor} for an MBean. diff --git a/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java b/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java index 320a64790e..b75e956dab 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,6 +36,7 @@ import org.springframework.jmx.export.metadata.ManagedOperationParameter; import org.springframework.jmx.export.metadata.ManagedResource; import org.springframework.jmx.support.MetricType; import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** @@ -255,19 +256,17 @@ public class MetadataMBeanInfoAssembler extends AbstractReflectiveMBeanInfoAssem @Override protected MBeanParameterInfo[] getOperationParameters(Method method, String beanKey) { ManagedOperationParameter[] params = this.attributeSource.getManagedOperationParameters(method); - if (params == null || params.length == 0) { - return new MBeanParameterInfo[0]; + if (ObjectUtils.isEmpty(params)) { + return super.getOperationParameters(method, beanKey); } MBeanParameterInfo[] parameterInfo = new MBeanParameterInfo[params.length]; Class[] methodParameters = method.getParameterTypes(); - for (int i = 0; i < params.length; i++) { ManagedOperationParameter param = params[i]; parameterInfo[i] = new MBeanParameterInfo(param.getName(), methodParameters[i].getName(), param.getDescription()); } - return parameterInfo; } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java index 2b0bbaeefc..72da54f6f3 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -16,11 +16,13 @@ package org.springframework.jmx.export.assembler; +import javax.management.MBeanOperationInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; /** * @author Rob Harrop + * @author David Boden */ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests { @@ -56,6 +58,13 @@ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssembler assertFalse(attr.isWritable()); } + public void testSetNameParameterIsNamed() throws Exception { + ModelMBeanInfo info = getMBeanInfoFromAssembler(); + + MBeanOperationInfo operationSetAge = info.getOperation("setName"); + assertEquals("name", operationSetAge.getSignature()[0].getName()); + } + @Override protected String getApplicationContextPath() { return "org/springframework/jmx/export/assembler/methodNameAssembler.xml"; From a425d717b798356e14dd92ee7c88b13739f6e158 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 15:25:07 +0100 Subject: [PATCH 139/311] ThreadPoolExecutorFactoryBean exposes "createExecutor" method for custom ThreadPoolExecutor subclasses Issue: SPR-9435 --- .../ThreadPoolExecutorFactoryBean.java | 30 +++++++++++++++---- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBean.java b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBean.java index 19cd880bbb..3e04248ea8 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBean.java +++ b/spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolExecutorFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -126,7 +126,7 @@ public class ThreadPoolExecutorFactoryBean extends ExecutorConfigurationSupport *

Default is "false", exposing the raw executor as bean reference. * Switch this flag to "true" to strictly prevent clients from * modifying the executor's configuration. - * @see java.util.concurrent.Executors#unconfigurableScheduledExecutorService + * @see java.util.concurrent.Executors#unconfigurableExecutorService */ public void setExposeUnconfigurableExecutor(boolean exposeUnconfigurableExecutor) { this.exposeUnconfigurableExecutor = exposeUnconfigurableExecutor; @@ -137,9 +137,8 @@ public class ThreadPoolExecutorFactoryBean extends ExecutorConfigurationSupport ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { BlockingQueue queue = createQueue(this.queueCapacity); - ThreadPoolExecutor executor = new ThreadPoolExecutor( - this.corePoolSize, this.maxPoolSize, this.keepAliveSeconds, TimeUnit.SECONDS, - queue, threadFactory, rejectedExecutionHandler); + ThreadPoolExecutor executor = createExecutor(this.corePoolSize, this.maxPoolSize, + this.keepAliveSeconds, queue, threadFactory, rejectedExecutionHandler); if (this.allowCoreThreadTimeOut) { executor.allowCoreThreadTimeOut(true); } @@ -151,6 +150,27 @@ public class ThreadPoolExecutorFactoryBean extends ExecutorConfigurationSupport return executor; } + /** + * Create a new instance of {@link ThreadPoolExecutor} or a subclass thereof. + *

The default implementation creates a standard {@link ThreadPoolExecutor}. + * Can be overridden to provide custom {@link ThreadPoolExecutor} subclasses. + * @param corePoolSize the specified core pool size + * @param maxPoolSize the specified maximum pool size + * @param keepAliveSeconds the specified keep-alive time in seconds + * @param queue the BlockingQueue to use + * @param threadFactory the ThreadFactory to use + * @param rejectedExecutionHandler the RejectedExecutionHandler to use + * @return a new ThreadPoolExecutor instance + * @see #afterPropertiesSet() + */ + protected ThreadPoolExecutor createExecutor( + int corePoolSize, int maxPoolSize, int keepAliveSeconds, BlockingQueue queue, + ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { + + return new ThreadPoolExecutor(corePoolSize, maxPoolSize, + keepAliveSeconds, TimeUnit.SECONDS, queue, threadFactory, rejectedExecutionHandler); + } + /** * Create the BlockingQueue to use for the ThreadPoolExecutor. *

A LinkedBlockingQueue instance will be created for a positive From 0dcc0f2227c2c5442124c7b58d17bcfa993821b5 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 15:26:16 +0100 Subject: [PATCH 140/311] Added further MySQL error code for DataIntegrityViolationException Issue: SPR-9237 --- .../org/springframework/jdbc/support/sql-error-codes.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-jdbc/src/main/resources/org/springframework/jdbc/support/sql-error-codes.xml b/spring-jdbc/src/main/resources/org/springframework/jdbc/support/sql-error-codes.xml index 50a5167aed..8b06d1eb62 100644 --- a/spring-jdbc/src/main/resources/org/springframework/jdbc/support/sql-error-codes.xml +++ b/spring-jdbc/src/main/resources/org/springframework/jdbc/support/sql-error-codes.xml @@ -151,7 +151,7 @@ 1062 - 630,839,840,893,1169,1215,1216,1217,1451,1452,1557 + 630,839,840,893,1169,1215,1216,1217,1364,1451,1452,1557 1 From 4c823a3f9bf9413eea6b61a8c217eb1efff3e853 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 16:02:42 +0100 Subject: [PATCH 141/311] DisposableBeanAdapter detects "shutdown" as a destroy method as well (for EHCache CacheManager setup) Issue: SPR-9713 --- .../support/DisposableBeanAdapter.java | 11 +++++-- .../DestroyMethodInferenceTests.java | 29 ++++++++++++++++--- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java index 990438597f..6a498344a9 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DisposableBeanAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,6 +61,8 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { private static final String CLOSE_METHOD_NAME = "close"; + private static final String SHUTDOWN_METHOD_NAME = "shutdown"; + private static final Log logger = LogFactory.getLog(DisposableBeanAdapter.class); private static Class closeableInterface; @@ -176,7 +178,12 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable { return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName(); } catch (NoSuchMethodException ex) { - // no candidate destroy method found + try { + return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName(); + } + catch (NoSuchMethodException ex2) { + // no candidate destroy method found + } } } return null; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java b/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java index 7baf82681e..87999283a3 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/DestroyMethodInferenceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,21 @@ package org.springframework.context.annotation; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; - import java.io.Closeable; import java.io.IOException; import org.junit.Test; + import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +/** + * @author Chris Beams + * @author Juergen Hoeller + */ public class DestroyMethodInferenceTests { @Test @@ -39,6 +44,7 @@ public class DestroyMethodInferenceTests { WithInheritedCloseMethod c4 = ctx.getBean("c4", WithInheritedCloseMethod.class); WithInheritedCloseMethod c5 = ctx.getBean("c5", WithInheritedCloseMethod.class); WithNoCloseMethod c6 = ctx.getBean("c6", WithNoCloseMethod.class); + WithLocalShutdownMethod c7 = ctx.getBean("c7", WithLocalShutdownMethod.class); assertThat(c0.closed, is(false)); assertThat(c1.closed, is(false)); @@ -47,6 +53,7 @@ public class DestroyMethodInferenceTests { assertThat(c4.closed, is(false)); assertThat(c5.closed, is(false)); assertThat(c6.closed, is(false)); + assertThat(c7.closed, is(false)); ctx.close(); assertThat("c0", c0.closed, is(true)); assertThat("c1", c1.closed, is(true)); @@ -55,6 +62,7 @@ public class DestroyMethodInferenceTests { assertThat("c4", c4.closed, is(true)); assertThat("c5", c5.closed, is(true)); assertThat("c6", c6.closed, is(false)); + assertThat("c7", c7.closed, is(true)); } @Test @@ -121,6 +129,11 @@ public class DestroyMethodInferenceTests { public WithNoCloseMethod c6() { return new WithNoCloseMethod(); } + + @Bean + public WithLocalShutdownMethod c7() { + return new WithLocalShutdownMethod(); + } } @@ -149,4 +162,12 @@ public class DestroyMethodInferenceTests { static class WithNoCloseMethod { boolean closed = false; } + + static class WithLocalShutdownMethod { + boolean closed = false; + public void shutdown() { + closed = true; + } + } + } From ede9d535ea89b15e58efb11dfa4136659e6adf3c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 16:09:37 +0100 Subject: [PATCH 142/311] Updated resolvePath javadoc to reflect Environment-based placeholder resolution Issue: SPR-9455 --- .../AbstractRefreshableConfigApplicationContext.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java b/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java index 138f45526c..66aff5979b 100644 --- a/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java +++ b/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableConfigApplicationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.context.support; import org.springframework.beans.factory.BeanNameAware; - import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.util.Assert; @@ -114,12 +113,13 @@ public abstract class AbstractRefreshableConfigApplicationContext extends Abstra /** * Resolve the given path, replacing placeholders with corresponding - * system property values if necessary. Applied to config locations. + * environment property values if necessary. Applied to config locations. * @param path the original file path * @return the resolved file path + * @see org.springframework.core.env.Environment#resolveRequiredPlaceholders(String) */ protected String resolvePath(String path) { - return this.getEnvironment().resolveRequiredPlaceholders(path); + return getEnvironment().resolveRequiredPlaceholders(path); } From 049169d19fac59887bb4edbe36f85c3c3ab341b3 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 22:16:35 +0100 Subject: [PATCH 143/311] ResourcePropertyResource accepts EncodedResource for properties files with a specific encoding Also added constructor with Charset argument to EncodedResource. Issue: SPR-10096 --- .../core/io/support/EncodedResource.java | 58 +++++++++++++- .../io/support/PropertiesLoaderSupport.java | 30 +------- .../io/support/PropertiesLoaderUtils.java | 56 +++++++++++++- .../io/support/ResourcePropertySource.java | 75 +++++++++---------- 4 files changed, 148 insertions(+), 71 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/io/support/EncodedResource.java b/spring-core/src/main/java/org/springframework/core/io/support/EncodedResource.java index 405a16e2a8..04a173836c 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/EncodedResource.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/EncodedResource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,10 @@ package org.springframework.core.io.support; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; +import java.nio.charset.Charset; import org.springframework.core.io.Resource; import org.springframework.util.Assert; @@ -39,7 +41,9 @@ public class EncodedResource { private final Resource resource; - private final String encoding; + private String encoding; + + private Charset charset; /** @@ -48,7 +52,8 @@ public class EncodedResource { * @param resource the Resource to hold */ public EncodedResource(Resource resource) { - this(resource, null); + Assert.notNull(resource, "Resource must not be null"); + this.resource = resource; } /** @@ -63,6 +68,18 @@ public class EncodedResource { this.encoding = encoding; } + /** + * Create a new EncodedResource for the given Resource, + * using the specified encoding. + * @param resource the Resource to hold + * @param charset the charset to use for reading from the resource + */ + public EncodedResource(Resource resource, Charset charset) { + Assert.notNull(resource, "Resource must not be null"); + this.resource = resource; + this.charset = charset; + } + /** * Return the Resource held. @@ -79,13 +96,36 @@ public class EncodedResource { return this.encoding; } + /** + * Return the charset to use for reading from the resource, + * or {@code null} if none specified. + */ + public final Charset getCharset() { + return this.charset; + } + + + /** + * Determine whether a {@link Reader} is required as opposed to an {@link InputStream}, + * i.e. whether an encoding or a charset has been specified. + * @see #getReader() + * @see #getInputStream() + */ + public boolean requiresReader() { + return (this.encoding != null || this.charset != null); + } + /** * Open a {@code java.io.Reader} for the specified resource, * using the specified encoding (if any). * @throws IOException if opening the Reader failed + * @see #requiresReader() */ public Reader getReader() throws IOException { - if (this.encoding != null) { + if (this.charset != null) { + return new InputStreamReader(this.resource.getInputStream(), this.charset); + } + else if (this.encoding != null) { return new InputStreamReader(this.resource.getInputStream(), this.encoding); } else { @@ -93,6 +133,16 @@ public class EncodedResource { } } + /** + * Open an {@code java.io.InputStream} for the specified resource, + * typically assuming that there is no specific encoding to use. + * @throws IOException if opening the InputStream failed + * @see #requiresReader() + */ + public InputStream getInputStream() throws IOException { + return this.resource.getInputStream(); + } + @Override public boolean equals(Object obj) { diff --git a/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderSupport.java b/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderSupport.java index d99e69806e..1e68ba23d8 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderSupport.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,6 @@ package org.springframework.core.io.support; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.util.Properties; import org.apache.commons.logging.Log; @@ -39,9 +37,6 @@ import org.springframework.util.PropertiesPersister; */ public abstract class PropertiesLoaderSupport { - public static final String XML_FILE_EXTENSION = ".xml"; - - /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); @@ -167,7 +162,7 @@ public abstract class PropertiesLoaderSupport { /** * Load properties into the given instance. * @param props the Properties instance to load into - * @throws java.io.IOException in case of I/O errors + * @throws IOException in case of I/O errors * @see #setLocations */ protected void loadProperties(Properties props) throws IOException { @@ -176,21 +171,9 @@ public abstract class PropertiesLoaderSupport { if (logger.isInfoEnabled()) { logger.info("Loading properties file from " + location); } - InputStream is = null; try { - is = location.getInputStream(); - String filename = location.getFilename(); - if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { - this.propertiesPersister.loadFromXml(props, is); - } - else { - if (this.fileEncoding != null) { - this.propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding)); - } - else { - this.propertiesPersister.load(props, is); - } - } + PropertiesLoaderUtils.fillProperties( + props, new EncodedResource(location, this.fileEncoding), this.propertiesPersister); } catch (IOException ex) { if (this.ignoreResourceNotFound) { @@ -202,11 +185,6 @@ public abstract class PropertiesLoaderSupport { throw ex; } } - finally { - if (is != null) { - is.close(); - } - } } } } diff --git a/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java b/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java index 6f3308d830..6aaa486fd3 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.core.io.support; import java.io.IOException; import java.io.InputStream; +import java.io.Reader; import java.net.URL; import java.net.URLConnection; import java.util.Enumeration; @@ -26,6 +27,8 @@ import java.util.Properties; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; +import org.springframework.util.DefaultPropertiesPersister; +import org.springframework.util.PropertiesPersister; import org.springframework.util.ResourceUtils; /** @@ -42,6 +45,9 @@ import org.springframework.util.ResourceUtils; */ public abstract class PropertiesLoaderUtils { + private static final String XML_FILE_EXTENSION = ".xml"; + + /** * Load properties from the given resource. * @param resource the resource to load from @@ -120,4 +126,52 @@ public abstract class PropertiesLoaderUtils { return properties; } + + /** + * Load the properties from the given encoded resource. + * @see #fillProperties + */ + static Properties loadProperties(EncodedResource resource) throws IOException { + Properties props = new Properties(); + fillProperties(props, resource, new DefaultPropertiesPersister()); + return props; + } + + /** + * Actually load properties from the given EncodedResource into the given Properties instance. + * @param props the Properties instance to load into + * @param resource the resource to load from + * @param persister the PropertiesPersister to use + * @throws IOException in case of I/O errors + */ + static void fillProperties(Properties props, EncodedResource resource, PropertiesPersister persister) + throws IOException { + + InputStream stream = null; + Reader reader = null; + try { + String filename = resource.getResource().getFilename(); + if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { + stream = resource.getInputStream(); + persister.loadFromXml(props, stream); + } + else if (resource.requiresReader()) { + reader = resource.getReader(); + persister.load(props, reader); + } + else { + stream = resource.getInputStream(); + persister.load(props, stream); + } + } + finally { + if (stream != null) { + stream.close(); + } + if (reader != null) { + reader.close(); + } + } + } + } diff --git a/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java b/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java index 705d8d44e7..d07955456c 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/ResourcePropertySource.java @@ -17,12 +17,11 @@ package org.springframework.core.io.support; import java.io.IOException; -import java.io.InputStream; import java.util.Properties; import org.springframework.core.env.PropertiesPropertySource; +import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; -import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; /** @@ -35,16 +34,34 @@ import org.springframework.util.StringUtils; * return non-{@code null} and end in ".xml". * * @author Chris Beams + * @author Juergen Hoeller * @since 3.1 */ public class ResourcePropertySource extends PropertiesPropertySource { /** * Create a PropertySource having the given name based on Properties - * loaded from the given resource. + * loaded from the given encoded resource. + */ + public ResourcePropertySource(String name, EncodedResource resource) throws IOException { + super(name, PropertiesLoaderUtils.loadProperties(resource)); + } + + /** + * Create a PropertySource based on Properties loaded from the given resource. + * The name of the PropertySource will be generated based on the + * {@link Resource#getDescription() description} of the given resource. + */ + public ResourcePropertySource(EncodedResource resource) throws IOException { + this(getNameForResource(resource.getResource()), resource); + } + + /** + * Create a PropertySource having the given name based on Properties + * loaded from the given encoded resource. */ public ResourcePropertySource(String name, Resource resource) throws IOException { - super(name, loadPropertiesForResource(resource)); + super(name, PropertiesLoaderUtils.loadProperties(new EncodedResource(resource))); } /** @@ -62,17 +79,7 @@ public class ResourcePropertySource extends PropertiesPropertySource { * resource (assuming it is prefixed with {@code classpath:}). */ public ResourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException { - this(name, getResourceForLocation(location, classLoader)); - } - - /** - * Create a PropertySource having the given name based on Properties loaded from - * the given resource location. The default thread context class loader will be - * used to load the resource (assuming the location string is prefixed with - * {@code classpath:}. - */ - public ResourcePropertySource(String name, String location) throws IOException { - this(name, location, ClassUtils.getDefaultClassLoader()); + this(name, new DefaultResourceLoader(classLoader).getResource(location)); } /** @@ -83,7 +90,17 @@ public class ResourcePropertySource extends PropertiesPropertySource { * resource. */ public ResourcePropertySource(String location, ClassLoader classLoader) throws IOException { - this(getResourceForLocation(location, classLoader)); + this(new DefaultResourceLoader(classLoader).getResource(location)); + } + + /** + * Create a PropertySource having the given name based on Properties loaded from + * the given resource location. The default thread context class loader will be + * used to load the resource (assuming the location string is prefixed with + * {@code classpath:}. + */ + public ResourcePropertySource(String name, String location) throws IOException { + this(name, new DefaultResourceLoader().getResource(location)); } /** @@ -92,34 +109,12 @@ public class ResourcePropertySource extends PropertiesPropertySource { * {@link Resource#getDescription() description} of the resource. */ public ResourcePropertySource(String location) throws IOException { - this(getResourceForLocation(location, ClassUtils.getDefaultClassLoader())); + this(new DefaultResourceLoader().getResource(location)); } - private static Resource getResourceForLocation(String location, ClassLoader classLoader) { - return new PathMatchingResourcePatternResolver(classLoader).getResource(location); - } - - private static Properties loadPropertiesForResource(Resource resource) throws IOException { - Properties props = new Properties(); - InputStream is = resource.getInputStream(); - String filename = resource.getFilename(); - if (filename != null && filename.endsWith(".xml")) { - props.loadFromXML(is); - } - else { - props.load(is); - } - try { - is.close(); - } catch (IOException ex) { - // ignore - } - return props; - } - /** - * Returns the description string for the resource, and if empty returns + * Return the description string for the resource, and if empty returns * the class name of the resource plus its identity hash code. */ private static String getNameForResource(Resource resource) { From e5d937848296dc30cdad3403c1b04fe09c83b887 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 22:17:38 +0100 Subject: [PATCH 144/311] Removed pre-JDK-1.5 checks --- .../util/DefaultPropertiesPersister.java | 36 ++++--------------- 1 file changed, 6 insertions(+), 30 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java b/spring-core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java index 19f2698c36..1337a5a544 100644 --- a/spring-core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java +++ b/spring-core/src/main/java/org/springframework/util/DefaultPropertiesPersister.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,8 +33,8 @@ import java.util.Properties; * *

Allows for reading from any Reader and writing to any Writer, for example * to specify a charset for a properties file. This is a capability that standard - * {@code java.util.Properties} unfortunately lacks up until JDK 1.5: - * You can only load files using the ISO-8859-1 charset there. + * {@code java.util.Properties} unfortunately lacked up until JDK 1.5: + * You were only able to load files using the ISO-8859-1 charset there. * *

Loading from and storing to a stream delegates to {@code Properties.load} * and {@code Properties.store}, respectively, to be fully compatible with @@ -49,20 +49,11 @@ import java.util.Properties; * an encoding for a Reader/Writer (like ReloadableResourceBundleMessageSource's * "defaultEncoding" and "fileEncodings" properties). * - *

As of Spring 1.2.2, this implementation also supports properties XML files, - * through the {@code loadFromXml} and {@code storeToXml} methods. - * The default implementations delegate to JDK 1.5's corresponding methods, - * throwing an exception if running on an older JDK. Those implementations - * could be subclassed to apply custom XML handling on JDK 1.4, for example. - * * @author Juergen Hoeller * @since 10.03.2004 * @see java.util.Properties * @see java.util.Properties#load * @see java.util.Properties#store - * @see org.springframework.context.support.ReloadableResourceBundleMessageSource#setPropertiesPersister - * @see org.springframework.context.support.ReloadableResourceBundleMessageSource#setDefaultEncoding - * @see org.springframework.context.support.ReloadableResourceBundleMessageSource#setFileEncodings */ public class DefaultPropertiesPersister implements PropertiesPersister { @@ -228,30 +219,15 @@ public class DefaultPropertiesPersister implements PropertiesPersister { public void loadFromXml(Properties props, InputStream is) throws IOException { - try { - props.loadFromXML(is); - } - catch (NoSuchMethodError err) { - throw new IOException("Cannot load properties XML file - not running on JDK 1.5+: " + err.getMessage()); - } + props.loadFromXML(is); } public void storeToXml(Properties props, OutputStream os, String header) throws IOException { - try { - props.storeToXML(os, header); - } - catch (NoSuchMethodError err) { - throw new IOException("Cannot store properties XML file - not running on JDK 1.5+: " + err.getMessage()); - } + props.storeToXML(os, header); } public void storeToXml(Properties props, OutputStream os, String header, String encoding) throws IOException { - try { - props.storeToXML(os, header, encoding); - } - catch (NoSuchMethodError err) { - throw new IOException("Cannot store properties XML file - not running on JDK 1.5+: " + err.getMessage()); - } + props.storeToXML(os, header, encoding); } } From 575926932ddac03afb3e275dbb4a0e6d270803eb Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 22:17:48 +0100 Subject: [PATCH 145/311] Polishing --- .../beans/factory/support/AbstractBeanFactory.java | 5 ++++- .../beans/factory/support/DefaultListableBeanFactory.java | 4 ++-- .../springframework/core/env/PropertiesPropertySource.java | 5 ++--- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index f298c6522f..6ec60e6e61 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -746,7 +746,10 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp public String resolveEmbeddedValue(String value) { String result = value; for (StringValueResolver resolver : this.embeddedValueResolvers) { - result = (result == null ? null : resolver.resolveStringValue(result)); + if (result == null) { + return null; + } + result = resolver.resolveStringValue(result); } return result; } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index 23512f9e23..9e681d0dd6 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -277,14 +277,14 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto for (String beanName : beanNames) { T beanInstance = getBean(beanName, requiredType); if (isPrimary(beanName, beanInstance)) { - if(primaryBean != null) { + if (primaryBean != null) { throw new NoUniqueBeanDefinitionException(requiredType, beanNames.length, "more than one 'primary' bean found of required type: " + Arrays.asList(beanNames)); } primaryBean = beanInstance; } } - if(primaryBean != null) { + if (primaryBean != null) { return primaryBean; } throw new NoUniqueBeanDefinitionException(requiredType, beanNames); diff --git a/spring-core/src/main/java/org/springframework/core/env/PropertiesPropertySource.java b/spring-core/src/main/java/org/springframework/core/env/PropertiesPropertySource.java index 8da8c15d8b..492d142d37 100644 --- a/spring-core/src/main/java/org/springframework/core/env/PropertiesPropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/env/PropertiesPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,13 +31,12 @@ import java.util.Properties; * * @author Chris Beams * @since 3.1 - * @see org.springframework.mock.env.MockPropertySource */ public class PropertiesPropertySource extends MapPropertySource { @SuppressWarnings({ "unchecked", "rawtypes" }) public PropertiesPropertySource(String name, Properties source) { - super(name, (Map)source); + super(name, (Map) source); } } From 919aeb5df9a7b170c30afa6a417507e3bbd75eba Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 23 Jan 2013 23:34:21 +0100 Subject: [PATCH 146/311] Final preparations for 3.2.1 --- src/dist/changelog.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index af25c8c883..82ae86682b 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -11,8 +11,12 @@ Changes in version 3.2.1 (2013-01-24) * added dedicated sort method to AnnotationAwareOrderComparator (SPR-9625) * BridgeMethodResolver properly handles bridge methods in interfaces (SPR-9330) * LocalVariableTableParameterNameDiscoverer works for bridge methods as well (SPR-9429) +* added constructor with Charset argument to EncodedResource (SPR-10096) +* ResourcePropertyResource accepts EncodedResource for properties files with a specific encoding (SPR-10096) * CachedIntrospectionResults.clearClassLoader(null) removes cached classes for the system class loader (SPR-9189) +* DisposableBeanAdapter detects "shutdown" as a destroy method as well (for EHCache CacheManager setup; SPR-9713) * introduced NoUniqueBeanDefinitionException as a dedicated subclass of NoSuchBeanDefinitionException (SPR-10194) +* DefaultListableBeanFactory's getBean(Class) checks primary marker in case of multiple matches (SPR-7854) * fixed QualifierAnnotationAutowireCandidateResolver's detection of custom qualifier annotations (SPR-10107) * fixed AbstractAutoProxyCreator to accept null bean names again (SPR-10108) * AbstractAdvisingBeanPostProcessor caches per bean target class, working for null bean names as well (SPR-10144) @@ -21,8 +25,10 @@ Changes in version 3.2.1 (2013-01-24) * SpringBeanAutowiringInterceptor eagerly releases BeanFactory if post-construction fails (SPR-10013) * added "exposeAccessContext" flag JndiRmiClientInterceptor/ProxyFactoryBean (for WebLogic; SPR-9428) * MBeanExporter does not log warnings for manually unregistered MBeans (SPR-9451) +* MBeanInfoAssembler impls expose actual method parameter names if possible (SPR-9985) * AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup (SPR-7955) * EhCacheManagerFactoryBean applies cacheManagerName ahead of creation (for EHCache 2.5 compatibility; SPR-9171) +* ThreadPoolExecutorFactoryBean exposes "createExecutor" method for custom ThreadPoolExecutor subclasses (SPR-9435) * added "awaitTerminationSeconds" property to ThreadPoolTaskExecutor/ThreadPoolTaskScheduler (SPR-5387) * aligned XML scheduled-task elements with @Scheduled in terms of kicking in after context refresh (SPR-9231) * reintroduced "mode" and "proxy-target-class" attributes in spring-task-3.1/3.2.xsd (SPR-10177) From 7f928e83ffb3abdd62f9a1dc4ed1062bfc3b06f6 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 23 Jan 2013 15:09:47 -0800 Subject: [PATCH 147/311] Change merge.into project dependencies to provided Change 'compile' dependencies to 'provided' for projects that are merged into other projects. This seems to prevent '-sources' and '-javadoc' jars from appearing on the classpath which can break javadoc generation. --- build.gradle | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/build.gradle b/build.gradle index 813816bdfd..19fe164e4d 100644 --- a/build.gradle +++ b/build.gradle @@ -526,8 +526,8 @@ project("spring-orm-hibernate4") { description = "Spring Object/Relational Mapping - Hibernate 4 support" merge.into = project(":spring-orm") dependencies { - compile(project(":spring-tx")) - compile(project(":spring-jdbc")) + provided(project(":spring-tx")) + provided(project(":spring-jdbc")) optional("org.hibernate:hibernate-core:4.1.0.Final") optional("org.hibernate:hibernate-entitymanager:4.1.0.Final") optional(project(":spring-web")) @@ -597,8 +597,8 @@ project("spring-webmvc-tiles3") { description = "Spring Framework Tiles3 Integration" merge.into = project(":spring-webmvc") dependencies { - compile(project(":spring-context")) - compile(project(":spring-web")) + provided(project(":spring-context")) + provided(project(":spring-web")) provided("javax.el:el-api:1.0") provided("javax.servlet:jstl:1.2") provided("javax.servlet.jsp:jsp-api:2.1") @@ -689,8 +689,8 @@ project("spring-test-mvc") { description = "Spring Test MVC Framework" merge.into = project(":spring-test") dependencies { - optional(project(":spring-context")) - compile(project(":spring-webmvc")) + provided(project(":spring-context")) + provided(project(":spring-webmvc")) provided("javax.servlet:javax.servlet-api:3.0.1") optional("org.hamcrest:hamcrest-core:1.3") optional("com.jayway.jsonpath:json-path:0.8.1") From d46a82bbb0156fa6037b2bdd2543a655f474817c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 24 Jan 2013 11:19:06 +0100 Subject: [PATCH 148/311] Added note on thread safety to TypeConverter and SimpleTypeConverter javadoc Issue: SPR-8659 --- .../java/org/springframework/beans/SimpleTypeConverter.java | 5 ++++- .../main/java/org/springframework/beans/TypeConverter.java | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/SimpleTypeConverter.java b/spring-beans/src/main/java/org/springframework/beans/SimpleTypeConverter.java index 1e074dcc33..8ab240836b 100644 --- a/spring-beans/src/main/java/org/springframework/beans/SimpleTypeConverter.java +++ b/spring-beans/src/main/java/org/springframework/beans/SimpleTypeConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,9 @@ package org.springframework.beans; * algorithm (including delegation to {@link java.beans.PropertyEditor} and * {@link org.springframework.core.convert.ConversionService}) underneath. * + *

Note: Due to its reliance on {@link java.beans.PropertyEditor PropertyEditors}, + * SimpleTypeConverter is not thread-safe. Use a separate instance for each thread. + * * @author Juergen Hoeller * @since 2.0 * @see BeanWrapperImpl diff --git a/spring-beans/src/main/java/org/springframework/beans/TypeConverter.java b/spring-beans/src/main/java/org/springframework/beans/TypeConverter.java index 2efc1edf73..6d69a63ce6 100644 --- a/spring-beans/src/main/java/org/springframework/beans/TypeConverter.java +++ b/spring-beans/src/main/java/org/springframework/beans/TypeConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,10 @@ import org.springframework.core.MethodParameter; * Interface that defines type conversion methods. Typically (but not necessarily) * implemented in conjunction with the {@link PropertyEditorRegistry} interface. * + *

Note: Since TypeConverter implementations are typically based on + * {@link java.beans.PropertyEditor PropertyEditors} which aren't thread-safe, + * TypeConverters themselves are not to be considered as thread-safe either. + * * @author Juergen Hoeller * @since 2.0 * @see SimpleTypeConverter From 078a1c5db84467a52e9de4078d139ee6fded08c7 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 24 Jan 2013 14:56:45 +0100 Subject: [PATCH 149/311] Made EncodedResource based variant public; consistently detect XML properties across all variants Issue: SPR-9078 --- .../io/support/PropertiesLoaderUtils.java | 172 ++++++++++-------- 1 file changed, 97 insertions(+), 75 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java b/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java index 6aaa486fd3..503f2bb1bb 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/PropertiesLoaderUtils.java @@ -49,92 +49,27 @@ public abstract class PropertiesLoaderUtils { /** - * Load properties from the given resource. - * @param resource the resource to load from - * @return the populated Properties instance - * @throws IOException if loading failed + * Load properties from the given EncodedResource, + * potentially defining a specific encoding for the properties file. + * @see #fillProperties(java.util.Properties, EncodedResource) */ - public static Properties loadProperties(Resource resource) throws IOException { + public static Properties loadProperties(EncodedResource resource) throws IOException { Properties props = new Properties(); fillProperties(props, resource); return props; } /** - * Fill the given properties from the given resource. - * @param props the Properties instance to fill + * Fill the given properties from the given EncodedResource, + * potentially defining a specific encoding for the properties file. + * @param props the Properties instance to load into * @param resource the resource to load from - * @throws IOException if loading failed + * @throws IOException in case of I/O errors */ - public static void fillProperties(Properties props, Resource resource) throws IOException { - InputStream is = resource.getInputStream(); - try { - props.load(is); - } - finally { - is.close(); - } - } + public static void fillProperties(Properties props, EncodedResource resource) + throws IOException { - /** - * Load all properties from the given class path resource, - * using the default class loader. - *

Merges properties if more than one resource of the same name - * found in the class path. - * @param resourceName the name of the class path resource - * @return the populated Properties instance - * @throws IOException if loading failed - */ - public static Properties loadAllProperties(String resourceName) throws IOException { - return loadAllProperties(resourceName, null); - } - - /** - * Load all properties from the given class path resource, - * using the given class loader. - *

Merges properties if more than one resource of the same name - * found in the class path. - * @param resourceName the name of the class path resource - * @param classLoader the ClassLoader to use for loading - * (or {@code null} to use the default class loader) - * @return the populated Properties instance - * @throws IOException if loading failed - */ - public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException { - Assert.notNull(resourceName, "Resource name must not be null"); - ClassLoader clToUse = classLoader; - if (clToUse == null) { - clToUse = ClassUtils.getDefaultClassLoader(); - } - Properties properties = new Properties(); - Enumeration urls = clToUse.getResources(resourceName); - while (urls.hasMoreElements()) { - URL url = (URL) urls.nextElement(); - InputStream is = null; - try { - URLConnection con = url.openConnection(); - ResourceUtils.useCachesIfNecessary(con); - is = con.getInputStream(); - properties.load(is); - } - finally { - if (is != null) { - is.close(); - } - } - } - return properties; - } - - - /** - * Load the properties from the given encoded resource. - * @see #fillProperties - */ - static Properties loadProperties(EncodedResource resource) throws IOException { - Properties props = new Properties(); fillProperties(props, resource, new DefaultPropertiesPersister()); - return props; } /** @@ -174,4 +109,91 @@ public abstract class PropertiesLoaderUtils { } } + /** + * Load properties from the given resource (in ISO-8859-1 encoding). + * @param resource the resource to load from + * @return the populated Properties instance + * @throws IOException if loading failed + * @see #fillProperties(java.util.Properties, Resource) + */ + public static Properties loadProperties(Resource resource) throws IOException { + Properties props = new Properties(); + fillProperties(props, resource); + return props; + } + + /** + * Fill the given properties from the given resource (in ISO-8859-1 encoding). + * @param props the Properties instance to fill + * @param resource the resource to load from + * @throws IOException if loading failed + */ + public static void fillProperties(Properties props, Resource resource) throws IOException { + InputStream is = resource.getInputStream(); + try { + String filename = resource.getFilename(); + if (filename != null && filename.endsWith(XML_FILE_EXTENSION)) { + props.loadFromXML(is); + } + else { + props.load(is); + } + } + finally { + is.close(); + } + } + + /** + * Load all properties from the specified class path resource + * (in ISO-8859-1 encoding), using the default class loader. + *

Merges properties if more than one resource of the same name + * found in the class path. + * @param resourceName the name of the class path resource + * @return the populated Properties instance + * @throws IOException if loading failed + */ + public static Properties loadAllProperties(String resourceName) throws IOException { + return loadAllProperties(resourceName, null); + } + + /** + * Load all properties from the specified class path resource + * (in ISO-8859-1 encoding), using the given class loader. + *

Merges properties if more than one resource of the same name + * found in the class path. + * @param resourceName the name of the class path resource + * @param classLoader the ClassLoader to use for loading + * (or {@code null} to use the default class loader) + * @return the populated Properties instance + * @throws IOException if loading failed + */ + public static Properties loadAllProperties(String resourceName, ClassLoader classLoader) throws IOException { + Assert.notNull(resourceName, "Resource name must not be null"); + ClassLoader clToUse = classLoader; + if (clToUse == null) { + clToUse = ClassUtils.getDefaultClassLoader(); + } + Properties props = new Properties(); + Enumeration urls = clToUse.getResources(resourceName); + while (urls.hasMoreElements()) { + URL url = (URL) urls.nextElement(); + URLConnection con = url.openConnection(); + ResourceUtils.useCachesIfNecessary(con); + InputStream is = con.getInputStream(); + try { + if (resourceName != null && resourceName.endsWith(XML_FILE_EXTENSION)) { + props.loadFromXML(is); + } + else { + props.load(is); + } + } + finally { + is.close(); + } + } + return props; + } + } From 39c00c489e47c2737cea45df3157e719900699c1 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Thu, 24 Jan 2013 14:15:53 +0100 Subject: [PATCH 150/311] Avoid UnsupportedOperationEx. with active SecurityManager Issue: SPR-9970 --- ...onmentSecurityManagerIntegrationTests.java | 118 ++++++++++++++++++ .../core/env/ReadOnlySystemAttributesMap.java | 20 +-- .../env/SystemEnvironmentPropertySource.java | 10 +- .../core/env/StandardEnvironmentTests.java | 4 +- 4 files changed, 137 insertions(+), 15 deletions(-) create mode 100644 spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java diff --git a/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java b/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java new file mode 100644 index 0000000000..4264739283 --- /dev/null +++ b/spring-context/src/test/java/org/springframework/context/support/EnvironmentSecurityManagerIntegrationTests.java @@ -0,0 +1,118 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.support; + +import static java.lang.String.format; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + +import java.security.AccessControlException; +import java.security.Permission; +import java.util.Map; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.annotation.AnnotatedBeanDefinitionReader; +import org.springframework.context.annotation.Profile; +import org.springframework.core.env.AbstractEnvironment; +import org.springframework.core.env.StandardEnvironmentTests; +import org.springframework.stereotype.Component; + + +/** + * Tests integration between Environment and SecurityManagers. See SPR-9970. + * + * @author Chris Beams + */ +public class EnvironmentSecurityManagerIntegrationTests { + + private SecurityManager originalSecurityManager; + private Map env; + + @Before + public void setUp() { + originalSecurityManager = System.getSecurityManager(); + env = StandardEnvironmentTests.getModifiableSystemEnvironment(); + env.put(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "p1"); + } + + @After + public void tearDown() { + env.remove(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME); + System.setSecurityManager(originalSecurityManager); + } + + @Test + public void securityManagerDisallowsAccessToSystemEnvironmentButAllowsAccessToIndividualKeys() { + SecurityManager securityManager = new SecurityManager() { + @Override + public void checkPermission(Permission perm) { + // disallowing access to System#getenv means that our + // ReadOnlySystemAttributesMap will come into play. + if ("getenv.*".equals(perm.getName())) { + throw new AccessControlException( + "Accessing the system environment is disallowed"); + } + } + }; + System.setSecurityManager(securityManager); + + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); + reader.register(C1.class); + assertThat(bf.containsBean("c1"), is(true)); + } + + @Test + public void securityManagerDisallowsAccessToSystemEnvironmentAndDisallowsAccessToIndividualKey() { + SecurityManager securityManager = new SecurityManager() { + @Override + public void checkPermission(Permission perm) { + // disallowing access to System#getenv means that our + // ReadOnlySystemAttributesMap will come into play. + if ("getenv.*".equals(perm.getName())) { + throw new AccessControlException( + "Accessing the system environment is disallowed"); + } + // disallowing access to the spring.profiles.active property means that + // the BeanDefinitionReader won't be able to determine which profiles are + // active. We should see an INFO-level message in the console about this + // and as a result, any components marked with a non-default profile will + // be ignored. + if (("getenv."+AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME).equals(perm.getName())) { + throw new AccessControlException( + format("Accessing system environment variable [%s] is disallowed", + AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME)); + } + } + }; + System.setSecurityManager(securityManager); + + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(bf); + reader.register(C1.class); + assertThat(bf.containsBean("c1"), is(false)); + } + + @Component("c1") + @Profile("p1") + static class C1 { + } +} diff --git a/spring-core/src/main/java/org/springframework/core/env/ReadOnlySystemAttributesMap.java b/spring-core/src/main/java/org/springframework/core/env/ReadOnlySystemAttributesMap.java index df310c6002..5ded8cbbc5 100644 --- a/spring-core/src/main/java/org/springframework/core/env/ReadOnlySystemAttributesMap.java +++ b/spring-core/src/main/java/org/springframework/core/env/ReadOnlySystemAttributesMap.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,17 +17,21 @@ package org.springframework.core.env; import java.util.Collection; +import java.util.Collections; import java.util.Map; import java.util.Set; import org.springframework.util.Assert; /** - * Read-only {@code Map} implementation that is backed by system properties or environment - * variables. + * Read-only {@code Map} implementation that is backed by system + * properties or environment variables. * - *

Used by {@link AbstractApplicationContext} when a {@link SecurityManager} prohibits access to {@link - * System#getProperties()} or {@link System#getenv()}. + *

Used by {@link AbstractApplicationContext} when a {@link SecurityManager} prohibits + * access to {@link System#getProperties()} or {@link System#getenv()}. It is for this + * reason that the implementations of {@link #keySet()}, {@link #entrySet()}, and + * {@link #values()} always return empty even though {@link #get(Object)} may in fact + * return non-null if the current security manager allows access to individual keys. * * @author Arjen Poutsma * @author Chris Beams @@ -85,7 +89,7 @@ abstract class ReadOnlySystemAttributesMap implements Map { } public Set keySet() { - throw new UnsupportedOperationException(); + return Collections.emptySet(); } public void putAll(Map m) { @@ -93,11 +97,11 @@ abstract class ReadOnlySystemAttributesMap implements Map { } public Collection values() { - throw new UnsupportedOperationException(); + return Collections.emptySet(); } public Set> entrySet() { - throw new UnsupportedOperationException(); + return Collections.emptySet(); } } diff --git a/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java b/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java index 66eeb1e5bb..09082aad5c 100644 --- a/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,7 +76,7 @@ public class SystemEnvironmentPropertySource extends MapPropertySource { */ @Override public boolean containsProperty(String name) { - return resolvePropertyName(name) != null; + return getProperty(name) != null; } /** @@ -102,8 +102,8 @@ public class SystemEnvironmentPropertySource extends MapPropertySource { /** * Check to see if this property source contains a property with the given name, or - * any underscore / uppercase variation thereof. Return the resolved name or - * {@code null} if none found. + * any underscore / uppercase variation thereof. Return the resolved name if one is + * found or otherwise the original name. Never returns {@code null}. */ private String resolvePropertyName(String name) { if (super.containsProperty(name)) { @@ -127,6 +127,6 @@ public class SystemEnvironmentPropertySource extends MapPropertySource { } } - return null; + return name; } } diff --git a/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java b/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java index 8cec8f813d..131917c8cc 100644 --- a/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java +++ b/spring-core/src/test/java/org/springframework/core/env/StandardEnvironmentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -456,7 +456,7 @@ public class StandardEnvironmentTests { } @SuppressWarnings("unchecked") - private static Map getModifiableSystemEnvironment() { + public static Map getModifiableSystemEnvironment() { // for os x / linux Class[] classes = Collections.class.getDeclaredClasses(); Map env = System.getenv(); From 8625504711223c8cce42dc8706c53b064a52b0d3 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 24 Jan 2013 16:45:06 +0100 Subject: [PATCH 151/311] Completed changelog entries for 3.2.1 --- src/dist/changelog.txt | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 82ae86682b..25b90985b9 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -13,6 +13,7 @@ Changes in version 3.2.1 (2013-01-24) * LocalVariableTableParameterNameDiscoverer works for bridge methods as well (SPR-9429) * added constructor with Charset argument to EncodedResource (SPR-10096) * ResourcePropertyResource accepts EncodedResource for properties files with a specific encoding (SPR-10096) +* SystemEnvironmentPropertySource properly works with an active JVM SecurityManager (SPR-9970) * CachedIntrospectionResults.clearClassLoader(null) removes cached classes for the system class loader (SPR-9189) * DisposableBeanAdapter detects "shutdown" as a destroy method as well (for EHCache CacheManager setup; SPR-9713) * introduced NoUniqueBeanDefinitionException as a dedicated subclass of NoSuchBeanDefinitionException (SPR-10194) @@ -42,6 +43,11 @@ Changes in version 3.2.1 (2013-01-24) * FreeMarkerConfigurationFactory properly supports TemplateLoaders when recreating Configurations (SPR-9389) * SpringContextResourceAdapter implements equals/hashCode according to the JCA 1.5 contract (SPR-9162) * ContextLoader properly detects pre-refreshed WebApplicationContext (SPR-9996) +* added support for placeholders in @RequestMapping annotation value (SPR-9935) +* added support for specifying a message code as @ResponseStatus reason (SPR-6044) +* HttpEntityMethodProcessor supports HttpEntity/ResponseEntity subclasses as well (SPR-10207) +* Tiles 3 TilesConfigurer properly works in combination with "completeAutoload" (SPR-10195) +* Spring MVC Test framework supports HTTP OPTIONS method as well (SPR-10093) * MockHttpServletRequest's getParameter(Values) returns null for null parameter name (SPR-10192) * MockHttpServletResponse's getHeaderNames declares Collection instead of Set for Servlet 3.0 compatibility (SPR-9885) From a99a4ed9b5597ef437bfbaff809f4d7e4ae48a20 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 24 Jan 2013 09:44:25 -0800 Subject: [PATCH 152/311] Tweak gradle generated eclipse meta-data - Change output folders to /bin/main and /bin/test. This prevents 'gradle clean' from breaking eclipse. - Update copyright header for new files to '2002-2013' --- gradle/ide.gradle | 13 +++++++------ src/eclipse/org.eclipse.jdt.ui.prefs | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/gradle/ide.gradle b/gradle/ide.gradle index bb73f9f456..3f73282254 100644 --- a/gradle/ide.gradle +++ b/gradle/ide.gradle @@ -27,17 +27,17 @@ eclipse.classpath.file.whenMerged { classpath -> // Use separate main/test outputs (prevents WTP from packaging test classes) -eclipse.classpath.defaultOutputDir = file(project.name+"/eclipse/bin") +eclipse.classpath.defaultOutputDir = file(project.name+"/bin/eclipse") eclipse.classpath.file.beforeMerged { classpath -> classpath.entries.findAll{ it instanceof SourceFolder }.each { - if(it.output.startsWith("build/eclipse")) { + if(it.output.startsWith("bin/")) { it.output = null } } } eclipse.classpath.file.whenMerged { classpath -> classpath.entries.findAll{ it instanceof SourceFolder }.each { - it.output = "build/eclipse/" + it.path.split("/")[1] + it.output = "bin/" + it.path.split("/")[1] } } @@ -90,9 +90,10 @@ eclipse.project.file.withXml { node.remove(filteredResources) } def filterNode = node.appendNode("filteredResources").appendNode("filter") - filterNode.appendNode("name", "build") - filterNode.appendNode("type", "26") + filterNode.appendNode("id", "1359048889071") + filterNode.appendNode("name", "") + filterNode.appendNode("type", "30") def matcherNode = filterNode.appendNode("matcher") matcherNode.appendNode("id", "org.eclipse.ui.ide.multiFilter") - matcherNode.appendNode("arguments", "1.0-projectRelativePath-matches-false-true-build\\/((?!eclipse).)*") + matcherNode.appendNode("arguments", "1.0-projectRelativePath-matches-false-false-build") } diff --git a/src/eclipse/org.eclipse.jdt.ui.prefs b/src/eclipse/org.eclipse.jdt.ui.prefs index 47eb08906b..4aa12d7db5 100644 --- a/src/eclipse/org.eclipse.jdt.ui.prefs +++ b/src/eclipse/org.eclipse.jdt.ui.prefs @@ -59,4 +59,4 @@ org.eclipse.jdt.ui.importorder=java;javax;org;com; org.eclipse.jdt.ui.javadoc=true org.eclipse.jdt.ui.ondemandthreshold=9999 org.eclipse.jdt.ui.staticondemandthreshold=9999 -org.eclipse.jdt.ui.text.custom_code_templates= +org.eclipse.jdt.ui.text.custom_code_templates= From 234cb84e832da30b6f53ccca4ef28043aacfcecc Mon Sep 17 00:00:00 2001 From: Spring Buildmaster Date: Thu, 24 Jan 2013 10:44:42 -0800 Subject: [PATCH 153/311] Release version 3.2.1.RELEASE --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index 89015ba3ec..e91e1373ca 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1 @@ -version=3.2.1.BUILD-SNAPSHOT +version=3.2.1.RELEASE From 08ba5a0d4a579f29a67bcaeba0f23be610583500 Mon Sep 17 00:00:00 2001 From: Spring Buildmaster Date: Thu, 24 Jan 2013 20:49:04 +0100 Subject: [PATCH 154/311] Increment version to 3.2.2.BUILD-SNAPSHOT --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index e91e1373ca..e69ccb3080 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1 @@ -version=3.2.1.RELEASE +version=3.2.2.BUILD-SNAPSHOT From 1065d82f089eeeace3795992a50e79e387841de6 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 25 Jan 2013 10:58:24 -0800 Subject: [PATCH 155/311] Remove eclipse project specific Javadoc settings Remove Javadoc settings from generated eclipse meta-data. Unfortunately eclipse provides too many false warnings due to the fact that @Link and @See tags in Spring often refer modules to which they cannot directly depend. --- src/eclipse/org.eclipse.jdt.core.prefs | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/eclipse/org.eclipse.jdt.core.prefs b/src/eclipse/org.eclipse.jdt.core.prefs index 2286420ffe..80a095b1a1 100644 --- a/src/eclipse/org.eclipse.jdt.core.prefs +++ b/src/eclipse/org.eclipse.jdt.core.prefs @@ -23,7 +23,6 @@ org.eclipse.jdt.core.compiler.compliance=1.7 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.doc.comment.support=enabled org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.autoboxing=ignore @@ -47,25 +46,12 @@ org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=ignore org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore -org.eclipse.jdt.core.compiler.problem.invalidJavadoc=warning -org.eclipse.jdt.core.compiler.problem.invalidJavadocTags=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsDeprecatedRef=disabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsNotVisibleRef=enabled -org.eclipse.jdt.core.compiler.problem.invalidJavadocTagsVisibility=default org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocComments=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocCommentsVisibility=public -org.eclipse.jdt.core.compiler.problem.missingJavadocTagDescription=return_tag -org.eclipse.jdt.core.compiler.problem.missingJavadocTags=ignore -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsMethodTypeParameters=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsOverriding=disabled -org.eclipse.jdt.core.compiler.problem.missingJavadocTagsVisibility=public org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore From 88f5dd6ce1a176eb17fc2f65890e2f3f2b603a03 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 25 Jan 2013 11:27:51 -0800 Subject: [PATCH 156/311] Fix 'is already an instance of type' warnings --- .../AbstractAspectJAdvisorFactoryTests.java | 19 ++++++---- ...elegatingIntroductionInterceptorTests.java | 4 ++- .../beans/BeanWrapperAutoGrowingTests.java | 35 ++++++++++--------- .../ConversionServiceFactoryBeanTests.java | 5 +-- .../scheduling/timer/TimerSupportTests.java | 5 ++- .../ServletAnnotationControllerTests.java | 24 ++++++++----- .../web/servlet/tags/UrlTagTests.java | 7 ++-- .../freemarker/FreeMarkerConfigurerTests.java | 7 ++-- .../velocity/VelocityConfigurerTests.java | 19 +++++----- 9 files changed, 77 insertions(+), 48 deletions(-) diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java index 273869e8a0..3faf43c07c 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java @@ -15,7 +15,14 @@ */ package org.springframework.aop.aspectj.annotation; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import java.io.FileNotFoundException; import java.lang.annotation.Retention; @@ -39,9 +46,7 @@ import org.aspectj.lang.annotation.DeclareParents; import org.aspectj.lang.annotation.DeclarePrecedence; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; - import org.junit.Test; - import org.springframework.aop.Advisor; import org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor; import org.springframework.aop.framework.Advised; @@ -52,14 +57,14 @@ import org.springframework.aop.support.AopUtils; import org.springframework.core.OrderComparator; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ObjectUtils; import test.aop.DefaultLockable; import test.aop.Lockable; import test.aop.PerTargetAspect; import test.aop.TwoAdviceAspect; -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; /** * Abstract tests for AspectJAdvisorFactory. @@ -385,7 +390,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { CannotBeUnlocked.class ), CannotBeUnlocked.class); - assertTrue(proxy instanceof Lockable); + assertThat(proxy, instanceOf(Lockable.class)); Lockable lockable = proxy; assertTrue("Already locked", lockable.locked()); lockable.lock(); @@ -442,7 +447,7 @@ public abstract class AbstractAspectJAdvisorFactoryTests { Modifiable modifiable = (Modifiable) createProxy(target, advisors, ITestBean.class); - assertTrue(modifiable instanceof Modifiable); + assertThat(modifiable, instanceOf(Modifiable.class)); Lockable lockable = (Lockable) modifiable; assertFalse(lockable.locked()); diff --git a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java index 1872a457f9..7a7257ea2f 100644 --- a/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java @@ -16,8 +16,10 @@ package org.springframework.aop.support; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -157,7 +159,7 @@ public final class DelegatingIntroductionInterceptorTests { //assertTrue(Arrays.binarySearch(pf.getProxiedInterfaces(), TimeStamped.class) != -1); TimeStamped ts = (TimeStamped) pf.getProxy(); - assertTrue(ts instanceof TimeStamped); + assertThat(ts, instanceOf(TimeStamped.class)); // Shoulnd't proxy framework interfaces assertTrue(!(ts instanceof MethodInterceptor)); assertTrue(!(ts instanceof IntroductionInterceptor)); diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java index 73bdeaee1c..06a7eb86ac 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperAutoGrowingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import java.util.Map; import org.junit.Before; import org.junit.Test; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.*; /** @@ -59,7 +60,7 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowArray() { assertNotNull(wrapper.getPropertyValue("array[0]")); assertEquals(1, bean.getArray().length); - assertTrue(bean.getArray()[0] instanceof Bean); + assertThat(bean.getArray()[0], instanceOf(Bean.class)); } @Test @@ -72,11 +73,11 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowArrayBySeveralElements() { assertNotNull(wrapper.getPropertyValue("array[4]")); assertEquals(5, bean.getArray().length); - assertTrue(bean.getArray()[0] instanceof Bean); - assertTrue(bean.getArray()[1] instanceof Bean); - assertTrue(bean.getArray()[2] instanceof Bean); - assertTrue(bean.getArray()[3] instanceof Bean); - assertTrue(bean.getArray()[4] instanceof Bean); + assertThat(bean.getArray()[0], instanceOf(Bean.class)); + assertThat(bean.getArray()[1], instanceOf(Bean.class)); + assertThat(bean.getArray()[2], instanceOf(Bean.class)); + assertThat(bean.getArray()[3], instanceOf(Bean.class)); + assertThat(bean.getArray()[4], instanceOf(Bean.class)); assertNotNull(wrapper.getPropertyValue("array[0]")); assertNotNull(wrapper.getPropertyValue("array[1]")); assertNotNull(wrapper.getPropertyValue("array[2]")); @@ -87,14 +88,14 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowMultiDimensionalArray() { assertNotNull(wrapper.getPropertyValue("multiArray[0][0]")); assertEquals(1, bean.getMultiArray()[0].length); - assertTrue(bean.getMultiArray()[0][0] instanceof Bean); + assertThat(bean.getMultiArray()[0][0], instanceOf(Bean.class)); } @Test public void getPropertyValueAutoGrowList() { assertNotNull(wrapper.getPropertyValue("list[0]")); assertEquals(1, bean.getList().size()); - assertTrue(bean.getList().get(0) instanceof Bean); + assertThat(bean.getList().get(0), instanceOf(Bean.class)); } @Test @@ -107,11 +108,11 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowListBySeveralElements() { assertNotNull(wrapper.getPropertyValue("list[4]")); assertEquals(5, bean.getList().size()); - assertTrue(bean.getList().get(0) instanceof Bean); - assertTrue(bean.getList().get(1) instanceof Bean); - assertTrue(bean.getList().get(2) instanceof Bean); - assertTrue(bean.getList().get(3) instanceof Bean); - assertTrue(bean.getList().get(4) instanceof Bean); + assertThat(bean.getList().get(0), instanceOf(Bean.class)); + assertThat(bean.getList().get(1), instanceOf(Bean.class)); + assertThat(bean.getList().get(2), instanceOf(Bean.class)); + assertThat(bean.getList().get(3), instanceOf(Bean.class)); + assertThat(bean.getList().get(4), instanceOf(Bean.class)); assertNotNull(wrapper.getPropertyValue("list[0]")); assertNotNull(wrapper.getPropertyValue("list[1]")); assertNotNull(wrapper.getPropertyValue("list[2]")); @@ -135,7 +136,7 @@ public class BeanWrapperAutoGrowingTests { public void getPropertyValueAutoGrowMultiDimensionalList() { assertNotNull(wrapper.getPropertyValue("multiList[0][0]")); assertEquals(1, bean.getMultiList().get(0).size()); - assertTrue(bean.getMultiList().get(0).get(0) instanceof Bean); + assertThat(bean.getMultiList().get(0).get(0), instanceOf(Bean.class)); } @Test(expected=InvalidPropertyException.class) @@ -146,13 +147,13 @@ public class BeanWrapperAutoGrowingTests { @Test public void setPropertyValueAutoGrowMap() { wrapper.setPropertyValue("map[A]", new Bean()); - assertTrue(bean.getMap().get("A") instanceof Bean); + assertThat(bean.getMap().get("A"), instanceOf(Bean.class)); } @Test public void setNestedPropertyValueAutoGrowMap() { wrapper.setPropertyValue("map[A].nested", new Bean()); - assertTrue(bean.getMap().get("A").getNested() instanceof Bean); + assertThat(bean.getMap().get("A").getNested(), instanceOf(Bean.class)); } diff --git a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java index 676ff05a30..396e4a1bb0 100644 --- a/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/context/support/ConversionServiceFactoryBeanTests.java @@ -33,6 +33,7 @@ import org.springframework.core.convert.converter.GenericConverter; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.*; /** @@ -136,8 +137,8 @@ public class ConversionServiceFactoryBeanTests { public ComplexConstructorArgument(Map> map) { assertTrue(!map.isEmpty()); - assertTrue(map.keySet().iterator().next() instanceof String); - assertTrue(map.values().iterator().next() instanceof Class); + assertThat(map.keySet().iterator().next(), instanceOf(String.class)); + assertThat(map.values().iterator().next(), instanceOf(Class.class)); } } diff --git a/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java b/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java index 3beaf36b84..283ee0acf3 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/timer/TimerSupportTests.java @@ -16,6 +16,9 @@ package org.springframework.scheduling.timer; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThat; + import java.util.ArrayList; import java.util.List; import java.util.Timer; @@ -84,7 +87,7 @@ public class TimerSupportTests extends TestCase { try { timerFactoryBean.setScheduledTimerTasks(tasks); timerFactoryBean.afterPropertiesSet(); - assertTrue(timerFactoryBean.getObject() instanceof Timer); + assertThat(timerFactoryBean.getObject(), instanceOf(Timer.class)); timerTask0.run(); timerTask1.run(); timerTask2.run(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java index bbfa7e2990..722099df3e 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ServletAnnotationControllerTests.java @@ -16,6 +16,16 @@ package org.springframework.web.servlet.mvc.annotation; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + import java.beans.PropertyEditorSupport; import java.io.IOException; import java.io.Serializable; @@ -43,6 +53,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; + import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -54,17 +65,12 @@ import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlRootElement; import org.junit.Test; - import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator; import org.springframework.aop.interceptor.SimpleTraceInterceptor; import org.springframework.aop.support.DefaultPointcutAdvisor; import org.springframework.beans.BeansException; -import org.springframework.tests.sample.beans.DerivedTestBean; -import org.springframework.tests.sample.beans.GenericBean; -import org.springframework.tests.sample.beans.ITestBean; import org.springframework.beans.PropertyEditorRegistrar; import org.springframework.beans.PropertyEditorRegistry; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -96,6 +102,10 @@ import org.springframework.mock.web.test.MockServletConfig; import org.springframework.mock.web.test.MockServletContext; import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.stereotype.Controller; +import org.springframework.tests.sample.beans.DerivedTestBean; +import org.springframework.tests.sample.beans.GenericBean; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; @@ -140,8 +150,6 @@ import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.util.NestedServletException; -import static org.junit.Assert.*; - /** * @author Juergen Hoeller * @author Sam Brannen @@ -3291,7 +3299,7 @@ public class ServletAnnotationControllerTests { @RequestMapping("/integerSet") public void processCsv(@RequestParam("content") Set content, HttpServletResponse response) throws IOException { - assertTrue(content.iterator().next() instanceof Integer); + assertThat(content.iterator().next(), instanceOf(Integer.class)); response.getWriter().write(StringUtils.collectionToDelimitedString(content, "-")); } } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java index edabd11d4f..f66a8c2b50 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/tags/UrlTagTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.web.servlet.tags; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThat; + import java.lang.reflect.Method; import java.util.HashSet; import java.util.LinkedList; @@ -49,7 +52,7 @@ public class UrlTagTests extends AbstractTagTests { } public void testParamSupport() { - assertTrue(tag instanceof ParamAware); + assertThat(tag, instanceOf(ParamAware.class)); } public void testDoStartTag() throws JspException { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java index 962b3fa33c..077c5b3a73 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.web.servlet.view.freemarker; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThat; + import java.io.IOException; import java.util.HashMap; import java.util.Properties; @@ -98,7 +101,7 @@ public class FreeMarkerConfigurerTests extends TestCase { } }); fcfb.afterPropertiesSet(); - assertTrue(fcfb.getObject() instanceof Configuration); + assertThat(fcfb.getObject(), instanceOf(Configuration.class)); Configuration fc = fcfb.getObject(); Template ft = fc.getTemplate("test"); assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap())); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java index 69f8ea613a..6475050597 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/velocity/VelocityConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.web.servlet.view.velocity; +import static org.hamcrest.Matchers.instanceOf; +import static org.junit.Assert.assertThat; + import java.io.File; import java.io.IOException; import java.net.MalformedURLException; @@ -25,9 +28,9 @@ import java.util.Properties; import java.util.Vector; import junit.framework.TestCase; + import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.VelocityException; - import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.DescriptiveResource; import org.springframework.core.io.FileSystemResource; @@ -68,7 +71,7 @@ public class VelocityConfigurerTests extends TestCase { map.put("myentry", value); vefb.setVelocityPropertiesMap(map); vefb.afterPropertiesSet(); - assertTrue(vefb.getObject() instanceof VelocityEngine); + assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals("/mydir", ve.getProperty("myprop")); assertEquals(value, ve.getProperty("myentry")); @@ -78,7 +81,7 @@ public class VelocityConfigurerTests extends TestCase { VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean(); vefb.setResourceLoaderPath("file:/mydir"); vefb.afterPropertiesSet(); - assertTrue(vefb.getObject() instanceof VelocityEngine); + assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); } @@ -105,7 +108,7 @@ public class VelocityConfigurerTests extends TestCase { } }); vefb.afterPropertiesSet(); - assertTrue(vefb.getObject() instanceof VelocityEngine); + assertThat(vefb.getObject(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vefb.getObject(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap())); } @@ -114,7 +117,7 @@ public class VelocityConfigurerTests extends TestCase { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir"); vc.afterPropertiesSet(); - assertTrue(vc.createVelocityEngine() instanceof VelocityEngine); + assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH)); } @@ -123,7 +126,7 @@ public class VelocityConfigurerTests extends TestCase { VelocityConfigurer vc = new VelocityConfigurer(); vc.setResourceLoaderPath("file:/mydir,file:/yourdir"); vc.afterPropertiesSet(); - assertTrue(vc.createVelocityEngine() instanceof VelocityEngine); + assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); Vector paths = new Vector(); paths.add(new File("/mydir").getAbsolutePath()); @@ -149,7 +152,7 @@ public class VelocityConfigurerTests extends TestCase { }); vc.setPreferFileSystemAccess(false); vc.afterPropertiesSet(); - assertTrue(vc.createVelocityEngine() instanceof VelocityEngine); + assertThat(vc.createVelocityEngine(), instanceOf(VelocityEngine.class)); VelocityEngine ve = vc.createVelocityEngine(); assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap())); } From 6a1e8419529ce908edc298639fa1691b4fbb2f11 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 25 Jan 2013 12:08:55 -0800 Subject: [PATCH 157/311] Fix unused type compiler warnings --- .../aop/aspectj/AspectJExpressionPointcutTests.java | 4 ---- .../TigerAspectJExpressionPointcutTests.java | 2 ++ .../adapter/ThrowsAdviceInterceptorTests.java | 2 +- .../aspectj/AbstractBeanConfigurerTests.java | 13 ++++++++++--- .../org/springframework/beans/BeanUtilsTests.java | 4 ++++ .../beans/BeanWrapperGenericsTests.java | 2 ++ .../org/springframework/beans/BeanWrapperTests.java | 10 ++++++++++ .../beans/ConcurrentBeanWrapperTests.java | 3 ++- .../factory/DefaultListableBeanFactoryTests.java | 4 ++++ .../factory/parsing/CustomProblemReporterTests.java | 4 ---- ...QualifierAnnotationAutowireBeanFactoryTests.java | 4 +++- .../support/security/CallbacksSecurityTests.java | 6 +++++- .../beans/factory/xml/FactoryMethods.java | 2 ++ .../CustomCollectionEditorTests.java | 4 ++-- .../beans/propertyeditors/CustomEditorTests.java | 3 +++ .../beans/support/PropertyComparatorTests.java | 3 ++- .../aop/framework/CglibProxyTests.java | 3 +++ .../InjectAnnotationAutowireContextTests.java | 3 ++- .../beans/factory/xml/QualifierAnnotationTests.java | 5 ++++- .../beans/factory/xml/XmlBeanFactoryTestTypes.java | 3 ++- .../CommonAnnotationBeanPostProcessorTests.java | 1 + ...ponentScanParserBeanDefinitionDefaultsTests.java | 5 ++++- .../ConfigurationClassProcessingTests.java | 6 ++++++ .../java/org/springframework/jmx/JmxTestBean.java | 4 +++- .../springframework/validation/DataBinderTests.java | 3 +++ .../PathMatchingResourcePatternResolver.java | 3 ++- .../core/BridgeMethodResolverTests.java | 3 +++ .../core/type/AnnotationTypeFilterTests.java | 6 +++++- .../core/type/AssignableTypeFilterTests.java | 4 +++- .../org/springframework/util/ClassUtilsTests.java | 8 +++++++- .../springframework/util/MethodInvokerTests.java | 3 ++- .../core/metadata/GenericTableMetaDataProvider.java | 12 +----------- .../datasource/DataSourceTransactionManager.java | 6 +----- .../BeanPropertySqlParameterSourceTests.java | 2 ++ .../DefaultJmsActivationSpecFactoryTests.java | 6 ++++-- .../orm/jdo/JdoInterceptorTests.java | 1 + .../orm/jpa/JpaInterceptorTests.java | 1 + .../oxm/jaxb/Jaxb2MarshallerTests.java | 4 +++- .../springframework/test/jpa/AbstractJpaTests.java | 4 +++- .../commons/CommonsMultipartResolverTests.java | 10 +--------- 40 files changed, 119 insertions(+), 57 deletions(-) diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java index 429350b00d..b042d8155a 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/AspectJExpressionPointcutTests.java @@ -309,10 +309,6 @@ public final class AspectJExpressionPointcutTests { assertTrue("Expression should match TestBean class", classFilter.matches(TestBean.class)); } - private void assertDoesNotMatchStringClass(ClassFilter classFilter) { - assertFalse("Expression should not match String class", classFilter.matches(String.class)); - } - @Test public void testWithUnsupportedPointcutPrimitive() throws Exception { String expression = "call(int org.springframework.tests.sample.beans.TestBean.getAge())"; diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java index 13635c2c6d..bc9f1b4f62 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/TigerAspectJExpressionPointcutTests.java @@ -89,6 +89,8 @@ public final class TigerAspectJExpressionPointcutTests { @Test public void testMatchVarargs() throws SecurityException, NoSuchMethodException { + + @SuppressWarnings("unused") class MyTemplate { public int queryForInt(String sql, Object... params) { return 0; diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java index 633705f068..e13097c4b6 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/adapter/ThrowsAdviceInterceptorTests.java @@ -144,7 +144,7 @@ public final class ThrowsAdviceInterceptorTests { } @SuppressWarnings("serial") - private static class MyThrowsHandler extends MethodCounter implements ThrowsAdvice { + static class MyThrowsHandler extends MethodCounter implements ThrowsAdvice { // Full method signature public void afterThrowing(Method m, Object[] args, Object target, IOException ex) { count("ioException"); diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java index 6ff04cf7b8..054c99f3e3 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java @@ -304,7 +304,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { // } // } - + @SuppressWarnings("unused") private static class ShouldNotBeConfiguredBySpring { private String name; @@ -335,6 +335,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable + @SuppressWarnings("unused") private static class ShouldBeConfiguredBySpringUsingTypeNameAsBeanName { private String name; @@ -350,6 +351,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable(autowire=Autowire.BY_TYPE) + @SuppressWarnings("unused") private static class ShouldBeConfiguredBySpringUsingAutowireByType { private TestBean friend = null; @@ -365,6 +367,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable(autowire=Autowire.BY_NAME) + @SuppressWarnings("unused") private static class ValidAutowireByName { private TestBean friend = null; @@ -380,6 +383,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable(autowire=Autowire.BY_NAME, dependencyCheck=true) + @SuppressWarnings("unused") private static class InvalidAutowireByName { private TestBean friend; @@ -393,7 +397,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { } } - + @SuppressWarnings("unused") private static class ArbitraryExistingPojo { private TestBean friend; @@ -426,6 +430,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Configurable + @SuppressWarnings("unused") private static class BaseBean { public int setterCount; @@ -447,7 +452,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { } @Configurable - @SuppressWarnings("serial") + @SuppressWarnings({"serial", "unused"}) private static class BaseSerializableBean implements Serializable { public int setterCount; @@ -467,6 +472,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Aspect + @SuppressWarnings("unused") private static class WireArbitraryExistingPojo extends AbstractBeanConfigurerAspect { @Pointcut("initialization(ArbitraryExistingPojo.new(..)) && this(beanInstance)") @@ -477,6 +483,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { @Aspect + @SuppressWarnings("unused") private static class AspectThatWillNotBeUsed extends AbstractBeanConfigurerAspect { @Pointcut("initialization(ClassThatWillNotActuallyBeWired.new(..)) && this(beanInstance)") diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java index 9d53409e73..b35e6aabf7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanUtilsTests.java @@ -267,6 +267,7 @@ public final class BeanUtilsTests { } + @SuppressWarnings("unused") private static class NameAndSpecialProperty { private String name; @@ -291,6 +292,7 @@ public final class BeanUtilsTests { } + @SuppressWarnings("unused") private static class ContainerBean { private ContainedBean[] containedBeans; @@ -305,6 +307,7 @@ public final class BeanUtilsTests { } + @SuppressWarnings("unused") private static class ContainedBean { private String name; @@ -319,6 +322,7 @@ public final class BeanUtilsTests { } + @SuppressWarnings("unused") private static class MethodSignatureBean { public void doSomething() { diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java index 3d310bdc68..88f647850d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -497,6 +497,7 @@ public class BeanWrapperGenericsTests { } + @SuppressWarnings("unused") private static class NestedGenericCollectionBean extends BaseGenericCollectionBean { private Map mapOfInteger; @@ -544,6 +545,7 @@ public class BeanWrapperGenericsTests { } + @SuppressWarnings("unused") private static class ComplexMapHolder { private Map, List> genericMap; diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java index 9d4e022a64..9ec9af033b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperTests.java @@ -1569,6 +1569,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class Foo { private List list; @@ -1598,6 +1599,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class NoRead { public void setAge(int age) { @@ -1605,6 +1607,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class EnumTester { private Autowire autowire; @@ -1619,6 +1622,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class PropsTester { private Properties props; @@ -1647,6 +1651,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class GetterBean { private String name; @@ -1664,6 +1669,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class ThrowsException { public void doSomething(Throwable t) throws Throwable { @@ -1672,6 +1678,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class PrimitiveArrayBean { private int[] array; @@ -1686,6 +1693,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class NumberPropertyBean { private byte myPrimitiveByte; @@ -1804,6 +1812,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class IntelliBean { public void setName(String name) {} @@ -1818,6 +1827,7 @@ public final class BeanWrapperTests { } + @SuppressWarnings("unused") private static class Employee extends TestBean { private String co; diff --git a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java index 95c3fbb8cc..2d98f138ba 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ConcurrentBeanWrapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -135,6 +135,7 @@ public final class ConcurrentBeanWrapperTests { } + @SuppressWarnings("unused") private static class TestBean { private Properties properties; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index fc4ac5d55c..59141704b7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -2334,6 +2334,7 @@ public class DefaultListableBeanFactoryTests { this.spouse = spouse; } + @SuppressWarnings("unused") private ConstructorDependency(TestBean spouse, TestBean otherSpouse) { throw new IllegalArgumentException("Should never be called"); } @@ -2560,6 +2561,7 @@ public class DefaultListableBeanFactoryTests { /** * Bean with a dependency on a {@link FactoryBean}. */ + @SuppressWarnings("unused") private static class FactoryBeanDependentBean { private FactoryBean factoryBean; @@ -2646,6 +2648,7 @@ public class DefaultListableBeanFactoryTests { } + @SuppressWarnings("unused") private static class TestSecuredBean { private String userName; @@ -2675,6 +2678,7 @@ public class DefaultListableBeanFactoryTests { } } + @SuppressWarnings("unused") private static class KnowsIfInstantiated { private static boolean instantiated; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java index 20bdd50654..cc009917fd 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java @@ -91,10 +91,6 @@ public final class CustomProblemReporterTests { System.out.println(problem); this.warnings.add(problem); } - - public Problem[] getWarnings() { - return this.warnings.toArray(new Problem[this.warnings.size()]); - } } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java index 195ad77529..cb7cf5580b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/QualifierAnnotationAutowireBeanFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -208,6 +208,7 @@ public class QualifierAnnotationAutowireBeanFactoryTests { } + @SuppressWarnings("unused") private static class QualifiedTestBean { @TestQualifier @@ -226,6 +227,7 @@ public class QualifierAnnotationAutowireBeanFactoryTests { } + @SuppressWarnings("unused") private static class Person { private String name; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java index 65e380d3e2..249c5bac02 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -75,6 +75,7 @@ public class CallbacksSecurityTests { private DefaultListableBeanFactory beanFactory; private SecurityContextProvider provider; + @SuppressWarnings("unused") private static class NonPrivilegedBean { private String expectedName; @@ -117,6 +118,7 @@ public class CallbacksSecurityTests { } } + @SuppressWarnings("unused") private static class NonPrivilegedSpringCallbacksBean implements InitializingBean, DisposableBean, BeanClassLoaderAware, BeanFactoryAware, BeanNameAware { @@ -161,6 +163,7 @@ public class CallbacksSecurityTests { } } + @SuppressWarnings("unused") private static class NonPrivilegedFactoryBean implements SmartFactoryBean { private String expectedName; @@ -204,6 +207,7 @@ public class CallbacksSecurityTests { } } + @SuppressWarnings("unused") private static class NonPrivilegedFactory { private final String expectedName; diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java index a5ef87cb1f..ba8c74bfe9 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethods.java @@ -62,6 +62,7 @@ public class FactoryMethods { return new FactoryMethods(tb, null, num); } + @SuppressWarnings("unused") private static List listInstance() { return Collections.EMPTY_LIST; } @@ -99,6 +100,7 @@ public class FactoryMethods { return this.tb; } + @SuppressWarnings("unused") private TestBean privateGetTestBean() { return this.tb; } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java index 14b3f4d48d..4f9463a5c7 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomCollectionEditorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2006 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -85,7 +85,7 @@ public final class CustomCollectionEditorTests { } - @SuppressWarnings("serial") + @SuppressWarnings({ "serial", "unused" }) private static final class CollectionTypeWithNoNoArgCtor extends ArrayList { public CollectionTypeWithNoNoArgCtor(String anArg) { } diff --git a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java index d205291620..af590e3936 100644 --- a/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/propertyeditors/CustomEditorTests.java @@ -1506,6 +1506,7 @@ public class CustomEditorTests { } + @SuppressWarnings("unused") private static class PrimitiveArrayBean { private byte[] byteArray; @@ -1530,6 +1531,7 @@ public class CustomEditorTests { } + @SuppressWarnings("unused") private static class CharBean { private char myChar; @@ -1554,6 +1556,7 @@ public class CustomEditorTests { } + @SuppressWarnings("unused") private static class OldCollectionsBean { private Vector vector; diff --git a/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java b/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java index 320759d1b8..ad1666fcd1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/support/PropertyComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -96,6 +96,7 @@ public class PropertyComparatorTests { } + @SuppressWarnings("unused") private static class Dog implements Comparable { private String nickName; diff --git a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java index 9b423759f7..2330909eec 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/CglibProxyTests.java @@ -137,10 +137,13 @@ public final class CglibProxyTests extends AbstractAopProxyTests implements Seri @Test public void testCglibProxyingGivesMeaningfulExceptionIfAskedToProxyNonvisibleClass() { + + @SuppressWarnings("unused") class YouCantSeeThis { void hidden() { } } + YouCantSeeThis mine = new YouCantSeeThis(); try { ProxyFactory pf = new ProxyFactory(mine); diff --git a/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java index d7cf863def..3544595d9d 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/support/InjectAnnotationAutowireContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -608,6 +608,7 @@ public class InjectAnnotationAutowireContextTests { } + @SuppressWarnings("unused") private static class QualifiedFieldWithBaseQualifierDefaultValueTestBean { @Inject diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java index 91d1d7565a..5271e47915 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/QualifierAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -199,6 +199,7 @@ public final class QualifierAnnotationTests { } + @SuppressWarnings("unused") private static class NonQualifiedTestBean { @Autowired @@ -305,6 +306,7 @@ public final class QualifierAnnotationTests { } + @SuppressWarnings("unused") private static class QualifiedByAttributesTestBean { @Autowired @MultipleAttributeQualifier(name="moe", age=42) @@ -323,6 +325,7 @@ public final class QualifierAnnotationTests { } + @SuppressWarnings("unused") private static class Person { private String name; diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java index 6f68b6bf60..a5bc212ced 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTestTypes.java @@ -198,7 +198,7 @@ abstract class ConstructorInjectedOverrides { * @author Juergen Hoeller * @since 09.11.2003 */ -@SuppressWarnings("serial") +@SuppressWarnings({ "serial", "unused" }) class DerivedConstructorDependenciesBean extends ConstructorDependenciesBean { boolean initialized; @@ -332,6 +332,7 @@ class DummyReferencer { * @author Rod Johnson * @author Juergen Hoeller */ +@SuppressWarnings("unused") class FactoryMethods { public static FactoryMethods nullInstance() { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java index 331a2f0af2..e2c1cc3b57 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessorTests.java @@ -700,6 +700,7 @@ public class CommonAnnotationBeanPostProcessorTests { } + @SuppressWarnings("unused") private static class NullFactory { public static Object create() { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java index 28fdcccca0..bf0baeaa53 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/ComponentScanParserBeanDefinitionDefaultsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -214,6 +214,7 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { } + @SuppressWarnings("unused") private static class DefaultsTestBean { static int INIT_COUNT; @@ -276,6 +277,7 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { } + @SuppressWarnings("unused") private static class PropertyDependencyTestBean { private String name; @@ -290,6 +292,7 @@ public class ComponentScanParserBeanDefinitionDefaultsTests { } + @SuppressWarnings("unused") private static class ConstructorDependencyTestBean { private String name; diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java index 54846f4133..7e11066fe8 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/ConfigurationClassProcessingTests.java @@ -272,6 +272,7 @@ public class ConfigurationClassProcessingTests { } + @SuppressWarnings("unused") static class ConfigWithPostProcessor extends ConfigWithPrototypeBean { @Value("${myProp}") @@ -280,10 +281,13 @@ public class ConfigurationClassProcessingTests { @Bean public POBPP beanPostProcessor() { return new POBPP() { + String nameSuffix = "-processed-" + myProp; + public void setNameSuffix(String nameSuffix) { this.nameSuffix = nameSuffix; } + @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { if (bean instanceof ITestBean) { @@ -291,10 +295,12 @@ public class ConfigurationClassProcessingTests { } return bean; } + @Override public Object postProcessAfterInitialization(Object bean, String beanName) { return bean; } + public int getOrder() { return 0; } diff --git a/spring-context/src/test/java/org/springframework/jmx/JmxTestBean.java b/spring-context/src/test/java/org/springframework/jmx/JmxTestBean.java index d42fbf201b..b1a773128d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/JmxTestBean.java +++ b/spring-context/src/test/java/org/springframework/jmx/JmxTestBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -138,12 +138,14 @@ public class JmxTestBean implements IJmxTestBean { protected void someProtectedMethod() { } + @SuppressWarnings("unused") private void somePrivateMethod() { } protected void getSomething() { } + @SuppressWarnings("unused") private void getSomethingElse() { } diff --git a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java index 515a1013b0..77fc0dee24 100644 --- a/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java +++ b/spring-context/src/test/java/org/springframework/validation/DataBinderTests.java @@ -1630,6 +1630,7 @@ public class DataBinderTests extends TestCase { } + @SuppressWarnings("unused") private static class BeanWithIntegerList { private List integerList; @@ -1644,6 +1645,7 @@ public class DataBinderTests extends TestCase { } + @SuppressWarnings("unused") private static class Book { private String Title; @@ -1728,6 +1730,7 @@ public class DataBinderTests extends TestCase { } + @SuppressWarnings("unused") private static class GrowingList extends AbstractList { private List list; diff --git a/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java b/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java index 9b2f8493b6..89e8b69be4 100644 --- a/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java +++ b/spring-core/src/main/java/org/springframework/core/io/support/PathMatchingResourcePatternResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -658,6 +658,7 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol /** * VFS visitor for path matching purposes. */ + @SuppressWarnings("unused") private static class PatternVirtualFileVisitor implements InvocationHandler { private final String subPattern; diff --git a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java index c013f3d3db..dbca8b7b5b 100644 --- a/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java +++ b/spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java @@ -560,6 +560,7 @@ public class BridgeMethodResolverTests { } + @SuppressWarnings("unused") private static class StringGenericParameter implements GenericParameter { @Override @@ -1163,6 +1164,7 @@ public class BridgeMethodResolverTests { } + @SuppressWarnings("unused") private static class MegaMessageProducerImpl extends Other implements MegaMessageProducer { public void receive(NewMegaMessageEvent event) { @@ -1198,6 +1200,7 @@ public class BridgeMethodResolverTests { } + @SuppressWarnings("unused") private static abstract class AbstractImplementsInterface implements IGenericInterface { @Override diff --git a/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java index e9d8c1e19d..b316d1749e 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AnnotationTypeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -122,10 +122,12 @@ public class AnnotationTypeFilterTests { } + @SuppressWarnings("unused") private static class SomeSubClassOfSomeComponentInterface implements SomeComponentInterface { } + @SuppressWarnings("unused") private static class SomeSubClassOfSomeComponent extends SomeComponent { } @@ -139,10 +141,12 @@ public class AnnotationTypeFilterTests { } + @SuppressWarnings("unused") private static class SomeSubclassOfSomeClassMarkedWithNonInheritedAnnotation extends SomeClassMarkedWithNonInheritedAnnotation { } + @SuppressWarnings("unused") private static class SomeNonCandidateClass { } diff --git a/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java b/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java index 0ca007ea2e..cc624af1b8 100644 --- a/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java +++ b/spring-core/src/test/java/org/springframework/core/type/AssignableTypeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,6 +81,7 @@ public class AssignableTypeFilterTests extends TestCase { } + @SuppressWarnings("unused") private static class TestInterfaceImpl implements TestInterface { } @@ -89,6 +90,7 @@ public class AssignableTypeFilterTests extends TestCase { } + @SuppressWarnings("unused") private static class SomeDaoLikeImpl extends SimpleJdbcDaoSupport implements SomeDaoLikeInterface { } diff --git a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java index f4078360de..ce187d7c71 100644 --- a/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java @@ -308,19 +308,25 @@ public class ClassUtilsTests extends TestCase { } } + @SuppressWarnings("unused") private static class OverloadedMethodsClass { + public void print(String messages) { /* no-op */ } + public void print(String[] messages) { /* no-op */ } } - private static class SubOverloadedMethodsClass extends OverloadedMethodsClass{ + @SuppressWarnings("unused") + private static class SubOverloadedMethodsClass extends OverloadedMethodsClass { + public void print(String header, String[] messages) { /* no-op */ } + void print(String header, String[] messages, String footer) { /* no-op */ } diff --git a/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java b/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java index 2fa0245aa1..679ab9566e 100644 --- a/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java +++ b/spring-core/src/test/java/org/springframework/util/MethodInvokerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -191,6 +191,7 @@ public class MethodInvokerTests extends TestCase { } + @SuppressWarnings("unused") public static class Greeter { // should handle Salesman (only interface) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java index 138518660a..8eb1e1ea5a 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/GenericTableMetaDataProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -310,7 +310,6 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { tmd.setCatalogName(tables.getString("TABLE_CAT")); tmd.setSchemaName(tables.getString("TABLE_SCHEM")); tmd.setTableName(tables.getString("TABLE_NAME")); - tmd.setType(tables.getString("TABLE_TYPE")); if (tmd.getSchemaName() == null) { tableMeta.put(userName != null ? userName.toUpperCase() : "", tmd); } @@ -445,7 +444,6 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { private String tableName; - private String type; public void setCatalogName(String catalogName) { this.catalogName = catalogName; @@ -470,14 +468,6 @@ public class GenericTableMetaDataProvider implements TableMetaDataProvider { public String getTableName() { return this.tableName; } - - public void setType(String type) { - this.type = type; - } - - public String getType() { - return this.type; - } } } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java index 9c6ebcfde2..b0e9811e3a 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceTransactionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -348,10 +348,6 @@ public class DataSourceTransactionManager extends AbstractPlatformTransactionMan return this.newConnectionHolder; } - public boolean hasTransaction() { - return (getConnectionHolder() != null && getConnectionHolder().isTransactionActive()); - } - public void setMustRestoreAutoCommit(boolean mustRestoreAutoCommit) { this.mustRestoreAutoCommit = mustRestoreAutoCommit; } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java index a684629973..15b0e21933 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/BeanPropertySqlParameterSourceTests.java @@ -81,6 +81,8 @@ public class BeanPropertySqlParameterSourceTests { assertFalse(source.hasValue("noOp")); } + + @SuppressWarnings("unused") private static final class NoReadableProperties { public void setNoOp(String noOp) { diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java index 598c5ada29..f91da0b40c 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ import javax.jms.Destination; import javax.jms.Session; import junit.framework.TestCase; -import org.easymock.MockControl; +import org.easymock.MockControl; import org.springframework.jca.StubResourceAdapter; import org.springframework.jms.StubQueue; import org.springframework.jms.support.destination.DestinationResolver; @@ -89,6 +89,7 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { } + @SuppressWarnings("unused") private static class StubActiveMQActivationSpec extends StubJmsActivationSpec { private int maxSessions; @@ -133,6 +134,7 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { } + @SuppressWarnings("unused") private static class StubWebSphereActivationSpecImpl extends StubJmsActivationSpec { private Destination destination; diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java index c88e58cd07..1967c188d5 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoInterceptorTests.java @@ -77,6 +77,7 @@ public class JdoInterceptorTests { } + @SuppressWarnings("unused") private static class TestInvocation implements MethodInvocation { private PersistenceManagerFactory persistenceManagerFactory; diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java index acc8f3b555..959fa0efe9 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/JpaInterceptorTests.java @@ -198,6 +198,7 @@ public class JpaInterceptorTests { } + @SuppressWarnings("unused") private static class TestInvocation implements MethodInvocation { private EntityManagerFactory entityManagerFactory; diff --git a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java index 3d7a497867..43101e62d0 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/jaxb/Jaxb2MarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -311,10 +311,12 @@ public class Jaxb2MarshallerTests extends AbstractMarshallerTests { private String s = "Hello"; } + @SuppressWarnings("unused") private JAXBElement createDummyRootElement() { return null; } + @SuppressWarnings("unused") private JAXBElement createDummyType() { return null; } diff --git a/spring-test/src/main/java/org/springframework/test/jpa/AbstractJpaTests.java b/spring-test/src/main/java/org/springframework/test/jpa/AbstractJpaTests.java index ba959d162f..005c19e3d8 100644 --- a/spring-test/src/main/java/org/springframework/test/jpa/AbstractJpaTests.java +++ b/spring-test/src/main/java/org/springframework/test/jpa/AbstractJpaTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -326,6 +326,7 @@ public abstract class AbstractJpaTests extends AbstractAnnotationAwareTransactio private final LoadTimeWeaver ltw; + @SuppressWarnings("unused") public LoadTimeWeaverInjectingBeanPostProcessor(LoadTimeWeaver ltw) { this.ltw = ltw; } @@ -346,6 +347,7 @@ public abstract class AbstractJpaTests extends AbstractAnnotationAwareTransactio private final ClassLoader shadowingClassLoader; + @SuppressWarnings("unused") public ShadowingLoadTimeWeaver(ClassLoader shadowingClassLoader) { this.shadowingClassLoader = shadowingClassLoader; } diff --git a/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java index 29df40fbf3..b264a44613 100644 --- a/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/multipart/commons/CommonsMultipartResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -465,19 +465,11 @@ public class CommonsMultipartResolverTests { this.writtenFile = file; } - public File getWrittenFile() { - return writtenFile; - } - @Override public void delete() { this.deleted = true; } - public boolean isDeleted() { - return deleted; - } - @Override public String getFieldName() { return fieldName; From 065b1c0e463e0d2b63931d487a6e29ef7c99b189 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 25 Jan 2013 14:33:23 -0800 Subject: [PATCH 158/311] Fix unused local variable warnings --- .../aspectj/AbstractTransactionAspect.aj | 2 +- .../aspectj/AbstractBeanConfigurerTests.java | 1 + .../config/CustomScopeConfigurerTests.java | 3 +-- .../PropertyResourceConfigurerTests.java | 2 ++ .../security/CallbacksSecurityTests.java | 3 +-- .../factory/xml/AbstractBeanFactoryTests.java | 9 +++++---- .../assembler/AbstractJmxAssemblerTests.java | 4 +++- ...faceBasedMBeanInfoAssemblerMappedTests.java | 6 +++--- .../core/enums/LabeledEnumTests.java | 7 ++++--- .../springframework/util/StopWatchTests.java | 6 +++--- .../expression/spel/MapAccessTests.java | 8 +++++--- .../spel/SpelDocumentationTests.java | 5 ++++- .../expression/spel/SpelReproTests.java | 5 +++++ .../SQLStateExceptionTranslatorTests.java | 3 +-- .../jms/core/JmsTemplate102Tests.java | 8 ++++---- .../jms/core/JmsTemplateTests.java | 18 +++++++++--------- ...onManagedEntityManagerIntegrationTests.java | 3 ++- .../AbstractTransactionAspectTests.java | 2 +- .../BeanFactoryTransactionTests.java | 3 ++- ...StreamingSimpleHttpRequestFactoryTests.java | 4 ++-- .../ResponseStatusExceptionResolverTests.java | 2 +- .../MultiActionControllerTests.java | 5 +++-- .../view/ResourceBundleViewResolverTests.java | 8 ++++---- ...tionScannerJsr330ScopeIntegrationTests.java | 3 ++- 24 files changed, 69 insertions(+), 51 deletions(-) diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj index 3ce264d9e1..54bd4ef746 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj @@ -60,7 +60,7 @@ public abstract aspect AbstractTransactionAspect extends TransactionAspectSuppor before(Object txObject) : transactionalMethodExecution(txObject) { MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature(); Method method = methodSignature.getMethod(); - TransactionInfo txInfo = createTransactionIfNecessary(method, txObject.getClass()); + createTransactionIfNecessary(method, txObject.getClass()); } @SuppressAjWarnings("adviceDidNotMatch") diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java index 054c99f3e3..71a10afcaf 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerTests.java @@ -211,6 +211,7 @@ public abstract class AbstractBeanConfigurerTests extends TestCase { MailClientDependencyInjectionAspect.aspectOf().setMailSender(new JavaMailSenderImpl()); Order testOrder = new Order(); Order deserializedOrder = serializeAndDeserialize(testOrder); + assertNotNull(deserializedOrder); assertNotNull("Interface driven injection didn't occur for deserialization", testOrder.mailSender); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java index 65e6debd15..f06388cc8d 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/CustomScopeConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,7 +45,6 @@ public final class CustomScopeConfigurerTests { @Test public void testWithNoScopes() throws Exception { - Scope scope = mock(Scope.class); CustomScopeConfigurer figurer = new CustomScopeConfigurer(); figurer.postProcessBeanFactory(factory); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java index 1212913cb1..fab64afdcb 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/config/PropertyResourceConfigurerTests.java @@ -17,6 +17,7 @@ package org.springframework.beans.factory.config; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; @@ -644,6 +645,7 @@ public final class PropertyResourceConfigurerTests { ppc.postProcessBeanFactory(factory); TestBean tb = (TestBean) factory.getBean("tb"); + assertNotNull(tb); assertEquals(0, factory.getAliases("tb").length); } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java index 249c5bac02..c8c6595e45 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java @@ -515,8 +515,7 @@ public class CallbacksSecurityTests { perms.add(new AuthPermission("getSubject")); ProtectionDomain pd = new ProtectionDomain(null, perms); - AccessControlContext acc = new AccessControlContext( - new ProtectionDomain[] { pd }); + new AccessControlContext(new ProtectionDomain[] { pd }); final Subject subject = new Subject(); subject.getPrincipals().add(new TestPrincipal("user1")); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java index 4510487801..3d88251b7e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/xml/AbstractBeanFactoryTests.java @@ -121,7 +121,7 @@ public abstract class AbstractBeanFactoryTests extends TestCase { public void testGetInstanceByNonmatchingClass() { try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); + getBeanFactory().getBean("rod", BeanFactory.class); fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); } catch (BeanNotOfRequiredTypeException ex) { @@ -155,7 +155,7 @@ public abstract class AbstractBeanFactoryTests extends TestCase { public void testGetSharedInstanceByNonmatchingClass() { try { - Object o = getBeanFactory().getBean("rod", BeanFactory.class); + getBeanFactory().getBean("rod", BeanFactory.class); fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException"); } catch (BeanNotOfRequiredTypeException ex) { @@ -199,7 +199,7 @@ public abstract class AbstractBeanFactoryTests extends TestCase { public void testNotThere() { assertFalse(getBeanFactory().containsBean("Mr Squiggle")); try { - Object o = getBeanFactory().getBean("Mr Squiggle"); + getBeanFactory().getBean("Mr Squiggle"); fail("Can't find missing bean"); } catch (BeansException ex) { @@ -223,7 +223,7 @@ public abstract class AbstractBeanFactoryTests extends TestCase { public void xtestTypeMismatch() { try { - Object o = getBeanFactory().getBean("typeMismatch"); + getBeanFactory().getBean("typeMismatch"); fail("Shouldn't succeed with type mismatch"); } catch (BeanCreationException wex) { @@ -278,6 +278,7 @@ public abstract class AbstractBeanFactoryTests extends TestCase { */ public void testFactoryIsInitialized() throws Exception { TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory"); + assertNotNull(tb); DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory"); assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized()); } diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java index 59b71a58b2..2c4a06e0be 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -51,6 +51,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { public void testRegisterOperations() throws Exception { IJmxTestBean bean = getBean(); + assertNotNull(bean); MBeanInfo inf = getMBeanInfo(); assertEquals("Incorrect number of operations registered", getExpectedOperationCount(), inf.getOperations().length); @@ -58,6 +59,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { public void testRegisterAttributes() throws Exception { IJmxTestBean bean = getBean(); + assertNotNull(bean); MBeanInfo inf = getMBeanInfo(); assertEquals("Incorrect number of attributes registered", getExpectedAttributeCount(), inf.getAttributes().length); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java index dc9db0fc5e..5cd8488eb7 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse public void testWithUnknownClass() throws Exception { try { - InterfaceBasedMBeanInfoAssembler assembler = getWithMapping("com.foo.bar.Unknown"); + getWithMapping("com.foo.bar.Unknown"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { @@ -49,7 +49,7 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse public void testWithNonInterface() throws Exception { try { - InterfaceBasedMBeanInfoAssembler assembler = getWithMapping("JmxTestBean"); + getWithMapping("JmxTestBean"); fail("Should have thrown IllegalArgumentException"); } catch (IllegalArgumentException ex) { diff --git a/spring-core/src/test/java/org/springframework/core/enums/LabeledEnumTests.java b/spring-core/src/test/java/org/springframework/core/enums/LabeledEnumTests.java index 4bd9a3f182..de0fccf46b 100644 --- a/spring-core/src/test/java/org/springframework/core/enums/LabeledEnumTests.java +++ b/spring-core/src/test/java/org/springframework/core/enums/LabeledEnumTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -104,7 +104,7 @@ public class LabeledEnumTests extends TestCase { public void testDoesNotMatchWrongClass() { try { - LabeledEnum none = StaticLabeledEnumResolver.instance().getLabeledEnumByCode(Dog.class, + StaticLabeledEnumResolver.instance().getLabeledEnumByCode(Dog.class, new Short((short) 1)); fail("Should have failed"); } @@ -119,10 +119,11 @@ public class LabeledEnumTests extends TestCase { } - @SuppressWarnings("serial") + @SuppressWarnings({ "serial", "unused" }) private static class Other extends StaticLabeledEnum { public static final Other THING1 = new Other(1, "Thing1"); + public static final Other THING2 = new Other(2, "Thing2"); diff --git a/spring-core/src/test/java/org/springframework/util/StopWatchTests.java b/spring-core/src/test/java/org/springframework/util/StopWatchTests.java index e7d745d416..4170f55624 100644 --- a/spring-core/src/test/java/org/springframework/util/StopWatchTests.java +++ b/spring-core/src/test/java/org/springframework/util/StopWatchTests.java @@ -1,6 +1,6 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,6 @@ public class StopWatchTests extends TestCase { String name1 = "Task 1"; String name2 = "Task 2"; - long fudgeFactor = 5L; assertFalse(sw.isRunning()); sw.start(name1); Thread.sleep(int1); @@ -44,6 +43,7 @@ public class StopWatchTests extends TestCase { // TODO are timings off in JUnit? Why do these assertions sometimes fail // under both Ant and Eclipse? + //long fudgeFactor = 5L; //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1); //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + fudgeFactor); sw.start(name2); @@ -72,7 +72,6 @@ public class StopWatchTests extends TestCase { String name1 = "Task 1"; String name2 = "Task 2"; - long fudgeFactor = 5L; assertFalse(sw.isRunning()); sw.start(name1); Thread.sleep(int1); @@ -82,6 +81,7 @@ public class StopWatchTests extends TestCase { // TODO are timings off in JUnit? Why do these assertions sometimes fail // under both Ant and Eclipse? + //long fudgeFactor = 5L; //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() >= int1); //assertTrue("Unexpected timing " + sw.getTotalTime(), sw.getTotalTime() <= int1 + fudgeFactor); sw.start(name2); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java index 3ea0f98e3d..6118c82af9 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/MapAccessTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.expression.spel; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; @@ -83,9 +84,10 @@ public class MapAccessTests extends ExpressionTestCase { ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("testBean.properties['key2']"); - String key= (String)exp.getValue(bean); + String key = (String) exp.getValue(bean); + assertNotNull(key); - } + } public static class TestBean { diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java index 9416ba87cf..41261a4d7c 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelDocumentationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.expression.spel; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @@ -213,9 +214,11 @@ public class SpelDocumentationTests extends ExpressionTestCase { societyContext.setRootObject(new IEEE()); // Officer's Dictionary Inventor pupin = parser.parseExpression("officers['president']").getValue(societyContext, Inventor.class); + assertNotNull(pupin); // evaluates to "Idvor" String city = parser.parseExpression("officers['president'].PlaceOfBirth.city").getValue(societyContext, String.class); + assertNotNull(city); // setting values Inventor i = parser.parseExpression("officers['advisors'][0]").getValue(societyContext,Inventor.class); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 765422302a..fdf04c7ba8 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -19,6 +19,7 @@ package org.springframework.expression.spel; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -1680,6 +1681,7 @@ public class SpelReproTests extends ExpressionTestCase { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Class valueType = parser.parseExpression("simpleProperty").getValueType(evaluationContext); + assertNotNull(valueType); } @Test @@ -1687,6 +1689,7 @@ public class SpelReproTests extends ExpressionTestCase { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Object value = parser.parseExpression("simpleProperty").getValue(evaluationContext); + assertNotNull(value); } @Test @@ -1694,6 +1697,7 @@ public class SpelReproTests extends ExpressionTestCase { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Class valueType = parser.parseExpression("primitiveProperty").getValueType(evaluationContext); + assertNotNull(valueType); } @Test @@ -1701,6 +1705,7 @@ public class SpelReproTests extends ExpressionTestCase { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext evaluationContext = new StandardEvaluationContext(new BooleanHolder()); Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext); + assertNotNull(value); } @Test diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java index 3578c1e93b..0aad57f96d 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLStateExceptionTranslatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -67,7 +67,6 @@ public class SQLStateExceptionTranslatorTests extends TestCase { * Bug 729170 */ public void testMalformedSqlStateCodes() { - String sql = "SELECT FOO FROM BAR"; SQLException sex = new SQLException("Message", null, 1); testMalformedSqlStateCode(sex); diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java index abcb7a7e66..12f01be2b5 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -207,7 +207,7 @@ public class JmsTemplate102Tests extends TestCase { template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { - boolean b = session.getTransacted(); + session.getTransacted(); return null; } }); @@ -249,8 +249,8 @@ public class JmsTemplate102Tests extends TestCase { template.execute(new ProducerCallback() { @Override public Object doInJms(Session session, MessageProducer producer) throws JMSException { - boolean b = session.getTransacted(); - int i = producer.getPriority(); + session.getTransacted(); + producer.getPriority(); return null; } }); diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java index 500874d8a1..2ff2c9afda 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -190,8 +190,8 @@ public class JmsTemplateTests extends TestCase { template.execute(new ProducerCallback() { @Override public Object doInJms(Session session, MessageProducer producer) throws JMSException { - boolean b = session.getTransacted(); - int i = producer.getPriority(); + session.getTransacted(); + producer.getPriority(); return null; } }); @@ -234,8 +234,8 @@ public class JmsTemplateTests extends TestCase { template.execute(new ProducerCallback() { @Override public Object doInJms(Session session, MessageProducer producer) throws JMSException { - boolean b = session.getTransacted(); - int i = producer.getPriority(); + session.getTransacted(); + producer.getPriority(); return null; } }); @@ -264,7 +264,7 @@ public class JmsTemplateTests extends TestCase { template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { - boolean b = session.getTransacted(); + session.getTransacted(); return null; } }); @@ -303,14 +303,14 @@ public class JmsTemplateTests extends TestCase { template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { - boolean b = session.getTransacted(); + session.getTransacted(); return null; } }); template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { - boolean b = session.getTransacted(); + session.getTransacted(); return null; } }); @@ -321,7 +321,7 @@ public class JmsTemplateTests extends TestCase { TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf); Connection tac = tacf.createConnection(); Session tas = tac.createSession(false, Session.AUTO_ACKNOWLEDGE); - boolean b = tas.getTransacted(); + tas.getTransacted(); tas.close(); tac.close(); diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java index 23f241e5ab..920099caf9 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/ApplicationManagedEntityManagerIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,6 +48,7 @@ public class ApplicationManagedEntityManagerIntegrationTests extends AbstractEnt assertTrue(Proxy.isProxyClass(em.getClass())); Query q = em.createQuery("select p from Person as p"); List people = q.getResultList(); + assertNotNull(people); assertTrue("Should be open to start with", em.isOpen()); em.close(); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java index 2b01ef4a91..0a49a21b63 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/AbstractTransactionAspectTests.java @@ -539,7 +539,7 @@ public abstract class AbstractTransactionAspectTests extends TestCase { Method m = setNameMethod; MapTransactionAttributeSource tas = new MapTransactionAttributeSource(); tas.register(m, txatt); - Method m2 = getNameMethod; + // Method m2 = getNameMethod; // No attributes for m2 MockControl ptmControl = MockControl.createControl(PlatformTransactionManager.class); diff --git a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java index 1ff4a262f4..1dda314dda 100644 --- a/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java +++ b/spring-tx/src/test/java/org/springframework/transaction/interceptor/BeanFactoryTransactionTests.java @@ -163,6 +163,7 @@ public class BeanFactoryTransactionTests extends TestCase { public void testGetBeansOfTypeWithAbstract() { Map beansOfType = factory.getBeansOfType(ITestBean.class, true, true); + assertNotNull(beansOfType); } /** @@ -172,7 +173,7 @@ public class BeanFactoryTransactionTests extends TestCase { try { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("noTransactionAttributeSource.xml", getClass())); - ITestBean testBean = (ITestBean) bf.getBean("noTransactionAttributeSource"); + bf.getBean("noTransactionAttributeSource"); fail("Should require TransactionAttributeSource to be set"); } catch (FatalBeanException ex) { diff --git a/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleHttpRequestFactoryTests.java index ccb91450a4..6eed7ae1be 100644 --- a/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleHttpRequestFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/http/client/StreamingSimpleHttpRequestFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ public class StreamingSimpleHttpRequestFactoryTests extends AbstractHttpRequestF ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/post"), HttpMethod.POST); final int BUF_SIZE = 4096; final int ITERATIONS = Integer.MAX_VALUE / BUF_SIZE; - final int contentLength = ITERATIONS * BUF_SIZE; +// final int contentLength = ITERATIONS * BUF_SIZE; // request.getHeaders().setContentLength(contentLength); OutputStream body = request.getBody(); for (int i = 0; i < ITERATIONS; i++) { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java index 25348f53f7..4731ce6fed 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/annotation/ResponseStatusExceptionResolverTests.java @@ -63,7 +63,7 @@ public class ResponseStatusExceptionResolverTests { exceptionResolver.setMessageSource(messageSource); StatusCodeAndReasonMessageException ex = new StatusCodeAndReasonMessageException(); - ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); + exceptionResolver.resolveException(request, response, null, ex); assertEquals("Invalid status reason", "Gone reason message", response.getErrorMessage()); } finally { diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java index 64de09b05a..de40940d0d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/multiaction/MultiActionControllerTests.java @@ -453,7 +453,7 @@ public class MultiActionControllerTests extends TestCase { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/handleIllegalStateException.html"); MockHttpServletResponse response = new MockHttpServletResponse(); - ModelAndView mav = mac.handleRequest(request, response); + mac.handleRequest(request, response); assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus()); } @@ -524,7 +524,6 @@ public class MultiActionControllerTests extends TestCase { this.invoked.put("commandNoSession", Boolean.TRUE); String pname = request.getParameter("name"); - String page = request.getParameter("age"); // ALLOW FOR NULL if (pname == null) { assertTrue("name null", command.getName() == null); @@ -532,6 +531,8 @@ public class MultiActionControllerTests extends TestCase { else { assertTrue("name param set", pname.equals(command.getName())); } + + //String page = request.getParameter("age"); // if (page == null) // assertTrue("age default", command.getAge() == 0); // else diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java index b100a6a68e..19e4551fb3 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/ResourceBundleViewResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,14 +72,14 @@ public class ResourceBundleViewResolverTests extends TestCase { public void testParentsAreAbstract() throws Exception { try { - View v = rb.resolveViewName("debug.Parent", Locale.ENGLISH); + rb.resolveViewName("debug.Parent", Locale.ENGLISH); fail("Should have thrown BeanIsAbstractException"); } catch (BeanIsAbstractException ex) { // expected } try { - View v = rb.resolveViewName("testParent", Locale.ENGLISH); + rb.resolveViewName("testParent", Locale.ENGLISH); fail("Should have thrown BeanIsAbstractException"); } catch (BeanIsAbstractException ex) { @@ -152,7 +152,7 @@ public class ResourceBundleViewResolverTests extends TestCase { public void testNoSuchBasename() throws Exception { try { rb.setBasename("weoriwoierqupowiuer"); - View v = rb.resolveViewName("debugView", Locale.ENGLISH); + rb.resolveViewName("debugView", Locale.ENGLISH); fail("No such basename: all requests should fail with exception"); } catch (MissingResourceException ex) { diff --git a/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java b/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java index b213a2a4e0..5f5938ed36 100644 --- a/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java +++ b/src/test/java/org/springframework/context/annotation/jsr330/ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,6 +86,7 @@ public class ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests { public void testPrototype() { ApplicationContext context = createContext(ScopedProxyMode.NO); ScopedTestBean bean = (ScopedTestBean) context.getBean("prototype"); + assertNotNull(bean); assertTrue(context.isPrototype("prototype")); assertFalse(context.isSingleton("prototype")); } From bc80d25b490a540c36ce4265d1ebaad11b679138 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 25 Jan 2013 16:38:30 -0800 Subject: [PATCH 159/311] Restore compile dependencies in generated POMs Ensure that merge projects do not downgrade the compile time dependencies of the projects that they are merged into. This commit restores the scope of the following dependencies which were inadvertently changed between Spring 3.2.0 and 3.2.1: spring-orm -> spring-tx -> spring-jdbc spring-webmvc -> spring-context -> spring-web spring-test -> spring-webmvc Issue: SPR-10218 --- build.gradle | 2 +- .../org/springframework/build/gradle/MergePlugin.groovy | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 19fe164e4d..9ac71e790a 100644 --- a/build.gradle +++ b/build.gradle @@ -689,7 +689,7 @@ project("spring-test-mvc") { description = "Spring Test MVC Framework" merge.into = project(":spring-test") dependencies { - provided(project(":spring-context")) + optional(project(":spring-context")) provided(project(":spring-webmvc")) provided("javax.servlet:javax.servlet-api:3.0.1") optional("org.hamcrest:hamcrest-core:1.3") diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy index 097e65ab93..510a2698c6 100644 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy @@ -128,7 +128,13 @@ class MergePlugin implements Plugin { (ExcludeRule.GROUP_KEY) : it.group, (ExcludeRule.MODULE_KEY) : it.module]) } - intoConfiguration.dependencies.addAll(configuration.dependencies) + configuration.dependencies.each { + def intoCompile = project.merge.into.configurations.getByName("compile") + // Protect against changing a compile scope dependency (SPR-10218) + if(!intoCompile.dependencies.contains(it)) { + intoConfiguration.dependencies.add(it) + } + } project.merge.into.install.repositories.mavenInstaller.pom.scopeMappings.addMapping( mapping.priority + 100, intoConfiguration, mapping.scope) } From 2b0d8609231deaf1a3790334f6ffd7dae326aa0e Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 25 Jan 2013 17:30:58 -0800 Subject: [PATCH 160/311] Fix Javadoc warnings --- .../org/springframework/beans/ExtendedBeanInfo.java | 4 ++-- .../java/org/springframework/util/ObjectUtils.java | 10 +++++----- .../core/type/CachingMetadataReaderLeakTest.java | 2 +- .../java/org/springframework/web/util/UriTemplate.java | 4 ++-- .../AopNamespaceHandlerScopeIntegrationTests.java | 2 +- .../AdvisorAutoProxyCreatorIntegrationTests.java | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java index c3609c10c2..6606741ee4 100644 --- a/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java +++ b/spring-beans/src/main/java/org/springframework/beans/ExtendedBeanInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,7 +56,7 @@ import static org.springframework.beans.PropertyDescriptorUtils.*; * this.foo = foo; * return this; * } - * } + * }} * The standard JavaBeans {@code Introspector} will discover the {@code getFoo} read * method, but will bypass the {@code #setFoo(Foo)} write method, because its non-void * returning signature does not comply with the JavaBeans specification. diff --git a/spring-core/src/main/java/org/springframework/util/ObjectUtils.java b/spring-core/src/main/java/org/springframework/util/ObjectUtils.java index 3ec3617418..09980f1e2c 100644 --- a/spring-core/src/main/java/org/springframework/util/ObjectUtils.java +++ b/spring-core/src/main/java/org/springframework/util/ObjectUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -481,7 +481,7 @@ public abstract class ObjectUtils { } /** - * Return the same value as {@code {@link Boolean#hashCode()}}. + * Return the same value as {@link Boolean#hashCode()}}. * @see Boolean#hashCode() */ public static int hashCode(boolean bool) { @@ -489,7 +489,7 @@ public abstract class ObjectUtils { } /** - * Return the same value as {@code {@link Double#hashCode()}}. + * Return the same value as {@link Double#hashCode()}}. * @see Double#hashCode() */ public static int hashCode(double dbl) { @@ -498,7 +498,7 @@ public abstract class ObjectUtils { } /** - * Return the same value as {@code {@link Float#hashCode()}}. + * Return the same value as {@link Float#hashCode()}}. * @see Float#hashCode() */ public static int hashCode(float flt) { @@ -506,7 +506,7 @@ public abstract class ObjectUtils { } /** - * Return the same value as {@code {@link Long#hashCode()}}. + * Return the same value as {@link Long#hashCode()}}. * @see Long#hashCode() */ public static int hashCode(long lng) { diff --git a/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTest.java b/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTest.java index db0b50242d..1d138b76f6 100644 --- a/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTest.java +++ b/spring-core/src/test/java/org/springframework/core/type/CachingMetadataReaderLeakTest.java @@ -31,7 +31,7 @@ import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; /** - * Unit test checking the behaviour of {@link CachingMetadataReaderFactory under load. + * Unit test checking the behaviour of {@link CachingMetadataReaderFactory} under load. * If the cache is not controller, this test should fail with an out of memory exception around entry * 5k. * diff --git a/spring-web/src/main/java/org/springframework/web/util/UriTemplate.java b/spring-web/src/main/java/org/springframework/web/util/UriTemplate.java index a8699042e9..3aacd60559 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriTemplate.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.util.Assert; /** * Represents a URI template. A URI template is a URI-like String that contains variables enclosed - * by braces ({@code {}, {@code }}), which can be expanded to produce an actual URI. + * by braces ({@code {}}), which can be expanded to produce an actual URI. * *

See {@link #expand(Map)}, {@link #expand(Object[])}, and {@link #match(String)} for example usages. * diff --git a/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java b/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java index 8a3c178627..067a335166 100644 --- a/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java +++ b/src/test/java/org/springframework/aop/config/AopNamespaceHandlerScopeIntegrationTests.java @@ -41,7 +41,7 @@ import org.springframework.web.context.support.XmlWebApplicationContext; * Integration tests for scoped proxy use in conjunction with aop: namespace. * Deemed an integration test because .web mocks and application contexts are required. * - * @see org.springframework.aop.config.AopNamespaceHandlerTests; + * @see org.springframework.aop.config.AopNamespaceHandlerTests * * @author Rob Harrop * @author Juergen Hoeller diff --git a/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java index d2fbb3e1e0..a972be2d97 100644 --- a/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java +++ b/src/test/java/org/springframework/aop/framework/autoproxy/AdvisorAutoProxyCreatorIntegrationTests.java @@ -44,7 +44,7 @@ import org.springframework.transaction.interceptor.TransactionInterceptor; * Integration tests for auto proxy creation by advisor recognition working in * conjunction with transaction managment resources. * - * @see org.springframework.aop.framework.autoproxy.AdvisorAutoProxyCreatorTests; + * @see org.springframework.aop.framework.autoproxy.AdvisorAutoProxyCreatorTests * * @author Rod Johnson * @author Chris Beams From b8e7314c433123be0e7b9eadcdc64be841116c82 Mon Sep 17 00:00:00 2001 From: Ken Dombeck Date: Fri, 25 Jan 2013 14:13:25 -0600 Subject: [PATCH 161/311] Fix typo in new-in-3.2.xml document This commit fixes a typo in the "New Features and Enhancements in Spring Framework 3.2" chapter of the reference manual. Specifically, ContentNegotiationStrategy is now spelled correctly. --- src/reference/docbook/new-in-3.2.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/new-in-3.2.xml b/src/reference/docbook/new-in-3.2.xml index 1f3d04e3ba..4ffd3cf6cd 100644 --- a/src/reference/docbook/new-in-3.2.xml +++ b/src/reference/docbook/new-in-3.2.xml @@ -57,7 +57,7 @@

Content negotiation improvements - A ContentNeogtiationStrategy is now + A ContentNegotiationStrategy is now available for resolving the requested media types from an incoming request. The available implementations are based on the file extension, query parameter, the 'Accept' header, or a fixed content type. From ac881066767bd7c1e840198f51ab0e3e7aedbe99 Mon Sep 17 00:00:00 2001 From: Rob Winch Date: Mon, 28 Jan 2013 10:28:14 -0600 Subject: [PATCH 162/311] Sort maven dependencies in generated pom files Previously the maven dependencies were specified in an arbitrary order which made comparing the poms against other versions difficult. This commit sorts the dependencies by scope, group id, and then artifact id. --- gradle/publish-maven.gradle | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/gradle/publish-maven.gradle b/gradle/publish-maven.gradle index 528e78c15d..d47098b4f1 100644 --- a/gradle/publish-maven.gradle +++ b/gradle/publish-maven.gradle @@ -13,6 +13,11 @@ def customizePom(pom, gradleProject) { dep.scope == "test" } + // sort to make pom dependencies order consistent to ease comparison of older poms + generatedPom.dependencies = generatedPom.dependencies.sort { dep -> + "$dep.scope:$dep.groupId:$dep.artifactId" + } + // add all items necessary for maven central publication generatedPom.project { name = gradleProject.description From 321004143b0941a10be10edd665c843ec1ab7967 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Tue, 29 Jan 2013 17:48:14 +0100 Subject: [PATCH 163/311] Improve Javadoc for ContextLoaderUtils - class-level Javadoc now mentions application context initializers. - avoided and suppressed warnings in method-level Javadoc. Issue: SPR-10232 --- .../test/context/ContextLoaderUtils.java | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java index 47ee0c78cf..8016c5d7c7 100644 --- a/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java +++ b/spring-test/src/main/java/org/springframework/test/context/ContextLoaderUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,7 +41,8 @@ import org.springframework.util.StringUtils; /** * Utility methods for working with {@link ContextLoader ContextLoaders} and * {@link SmartContextLoader SmartContextLoaders} and resolving resource locations, - * annotated classes, and active bean definition profiles. + * annotated classes, active bean definition profiles, and application context + * initializers. * * @author Sam Brannen * @since 3.1 @@ -50,6 +51,7 @@ import org.springframework.util.StringUtils; * @see ContextConfiguration * @see ContextConfigurationAttributes * @see ActiveProfiles + * @see ApplicationContextInitializer * @see MergedContextConfiguration */ abstract class ContextLoaderUtils { @@ -78,7 +80,7 @@ abstract class ContextLoaderUtils { * either {@value #DEFAULT_CONTEXT_LOADER_CLASS_NAME} * or {@value #DEFAULT_WEB_CONTEXT_LOADER_CLASS_NAME} will be used as the * default context loader class name. For details on the class resolution - * process, see {@link #resolveContextLoaderClass()}. + * process, see {@link #resolveContextLoaderClass}. * * @param testClass the test class for which the {@code ContextLoader} * should be resolved; must not be {@code null} @@ -89,8 +91,9 @@ abstract class ContextLoaderUtils { * {@code ContextLoader} class to use; may be {@code null} or empty * @return the resolved {@code ContextLoader} for the supplied * {@code testClass} (never {@code null}) - * @see #resolveContextLoaderClass() + * @see #resolveContextLoaderClass */ + @SuppressWarnings("javadoc") static ContextLoader resolveContextLoader(Class testClass, List configAttributesList, String defaultContextLoaderClassName) { Assert.notNull(testClass, "Class must not be null"); @@ -348,11 +351,11 @@ abstract class ContextLoaderUtils { * @param defaultContextLoaderClassName the name of the default * {@code ContextLoader} class to use (may be {@code null}) * @return the merged context configuration - * @see #resolveContextLoader() - * @see #resolveContextConfigurationAttributes() - * @see SmartContextLoader#processContextConfiguration() - * @see ContextLoader#processLocations() - * @see #resolveActiveProfiles() + * @see #resolveContextLoader + * @see #resolveContextConfigurationAttributes + * @see SmartContextLoader#processContextConfiguration + * @see ContextLoader#processLocations + * @see #resolveActiveProfiles * @see MergedContextConfiguration */ static MergedContextConfiguration buildMergedContextConfiguration(Class testClass, From d89e30b864c3303b2ba881451c38329bd3c16a09 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 29 Jan 2013 15:37:25 -0800 Subject: [PATCH 164/311] Fix unnecessary @SupressWarnings annotations --- .../annotation/AbstractAspectJAdvisorFactoryTests.java | 1 - .../org/springframework/beans/BeanWrapperGenericsTests.java | 1 - .../org/springframework/beans/ExtendedBeanInfoTests.java | 1 - .../beans/factory/DefaultListableBeanFactoryTests.java | 1 - .../context/event/SimpleApplicationEventMulticaster.java | 1 - .../src/test/java/example/scannable/FooServiceImpl.java | 1 - .../annotation/AnnotationConfigApplicationContextTests.java | 1 - .../context/annotation/BeanMethodPolymorphismTests.java | 2 +- .../BeanAnnotationAttributePropagationTests.java | 1 - .../FormattingConversionServiceFactoryBeanTests.java | 1 - .../format/support/FormattingConversionServiceTests.java | 1 - .../glassfish/GlassFishLoadTimeWeaverTests.java | 1 - .../scheduling/annotation/EnableAsyncTests.java | 1 - .../core/convert/support/GenericConversionServiceTests.java | 1 - .../jdbc/datasource/embedded/EmbeddedDatabaseFactory.java | 1 - .../main/java/org/springframework/orm/jdo/JdoTemplate.java | 1 - .../web/servlet/result/FlashAttributeResultMatchers.java | 1 - .../http/converter/FormHttpMessageConverterTests.java | 1 - .../method/annotation/InitBinderDataBinderFactoryTests.java | 6 +----- .../annotation/ModelAttributeMethodProcessorTests.java | 3 +-- 20 files changed, 3 insertions(+), 25 deletions(-) diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java index 3faf43c07c..5180ca7d14 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java @@ -404,7 +404,6 @@ public abstract class AbstractAspectJAdvisorFactoryTests { } } - @SuppressWarnings("unchecked") @Test public void testIntroductionOnTargetExcludedByTypePattern() { LinkedList target = new LinkedList(); diff --git a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java index 88f647850d..3a9e03accc 100644 --- a/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/BeanWrapperGenericsTests.java @@ -157,7 +157,6 @@ public class BeanWrapperGenericsTests { GenericBean gb = new GenericBean(); BeanWrapper bw = new BeanWrapperImpl(gb); bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false)); - @SuppressWarnings("unchecked") Map input = new HashMap(); HashSet value1 = new HashSet(); value1.add(new Integer(1)); diff --git a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java index ec2ca31e2b..30b2013d07 100644 --- a/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/ExtendedBeanInfoTests.java @@ -974,7 +974,6 @@ public class ExtendedBeanInfoTests { } static class WithStaticWriteMethod { - @SuppressWarnings("unused") public static void setProp1(String prop1) { } } diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 59141704b7..4045578c8c 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -2200,7 +2200,6 @@ public class DefaultListableBeanFactoryTests { doTestFieldSettingWithInstantiationAwarePostProcessor(true); } - @SuppressWarnings("unchecked") private void doTestFieldSettingWithInstantiationAwarePostProcessor(final boolean skipPropertyPopulation) { DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); diff --git a/spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java b/spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java index 2e13855d4a..71e4ec5369 100644 --- a/spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java +++ b/spring-context/src/main/java/org/springframework/context/event/SimpleApplicationEventMulticaster.java @@ -87,7 +87,6 @@ public class SimpleApplicationEventMulticaster extends AbstractApplicationEventM Executor executor = getTaskExecutor(); if (executor != null) { executor.execute(new Runnable() { - @SuppressWarnings("unchecked") public void run() { listener.onApplicationEvent(event); } diff --git a/spring-context/src/test/java/example/scannable/FooServiceImpl.java b/spring-context/src/test/java/example/scannable/FooServiceImpl.java index 1db44f5bb0..15da02b0f2 100644 --- a/spring-context/src/test/java/example/scannable/FooServiceImpl.java +++ b/spring-context/src/test/java/example/scannable/FooServiceImpl.java @@ -65,7 +65,6 @@ public class FooServiceImpl implements FooService { private boolean initCalled = false; - @SuppressWarnings("unused") @PostConstruct private void init() { if (this.initCalled) { diff --git a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java index 5906ea485d..f53c9e1a25 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java @@ -133,7 +133,6 @@ public class AnnotationConfigApplicationContextTests { } } - @SuppressWarnings("unchecked") @Test public void getBeanByTypeAmbiguityRaisesException() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TwoTestBeanConfig.class); diff --git a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java index 655324d1c7..1d573540f8 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/BeanMethodPolymorphismTests.java @@ -47,7 +47,7 @@ public class BeanMethodPolymorphismTests { @Test public void beanMethodOverloadingWithoutInheritance() { - @SuppressWarnings({ "unused", "hiding" }) + @SuppressWarnings({ "hiding" }) @Configuration class Config { @Bean String aString() { return "na"; } @Bean String aString(Integer dependency) { return "na"; } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java index f0dcbab8ab..f063133eab 100644 --- a/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java +++ b/spring-context/src/test/java/org/springframework/context/annotation/configuration/BeanAnnotationAttributePropagationTests.java @@ -41,7 +41,6 @@ import org.springframework.context.annotation.DependsOn; * * @author Chris Beams */ -@SuppressWarnings("unused") // for unused @Bean methods in local classes public class BeanAnnotationAttributePropagationTests { @Test diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java index ae9aa8be0e..284b238e56 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceFactoryBeanTests.java @@ -130,7 +130,6 @@ public class FormattingConversionServiceFactoryBeanTests { private static class TestBean { - @SuppressWarnings("unused") @NumberFormat(style = Style.PERCENT) private double percent; diff --git a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java index 6b0fb87da7..417ded1a45 100644 --- a/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java +++ b/spring-context/src/test/java/org/springframework/format/support/FormattingConversionServiceTests.java @@ -393,7 +393,6 @@ public class FormattingConversionServiceTests { private static class ModelWithSubclassField { - @SuppressWarnings("unused") @org.springframework.format.annotation.DateTimeFormat(style = "S-") public MyDate date; } diff --git a/spring-context/src/test/java/org/springframework/instrument/classloading/glassfish/GlassFishLoadTimeWeaverTests.java b/spring-context/src/test/java/org/springframework/instrument/classloading/glassfish/GlassFishLoadTimeWeaverTests.java index b2efa269c1..7907a51871 100644 --- a/spring-context/src/test/java/org/springframework/instrument/classloading/glassfish/GlassFishLoadTimeWeaverTests.java +++ b/spring-context/src/test/java/org/springframework/instrument/classloading/glassfish/GlassFishLoadTimeWeaverTests.java @@ -20,7 +20,6 @@ import org.junit.Ignore; // converting away from old-style EasyMock APIs was problematic with this class // glassfish dependencies no longer on classpath -@SuppressWarnings("deprecation") @Ignore public class GlassFishLoadTimeWeaverTests { diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java index 3b3329e0d9..bc30910d5f 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/EnableAsyncTests.java @@ -74,7 +74,6 @@ public class EnableAsyncTests { } - @SuppressWarnings("unchecked") @Test public void withAsyncBeanWithExecutorQualifiedByName() throws ExecutionException, InterruptedException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java index 01dd03c770..c08cdeebb7 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/GenericConversionServiceTests.java @@ -358,7 +358,6 @@ public class GenericConversionServiceTests { GenericConversionService service = new DefaultConversionService(); List list1 = Arrays.asList("Foo", "Bar"); List list2 = Arrays.asList("Baz", "Boop"); - @SuppressWarnings("unchecked") List> list = Arrays.asList(list1, list2); String result = service.convert(list, String.class); assertNotNull(result); diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java index 5e3db7cff4..20a5bfdf61 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseFactory.java @@ -205,7 +205,6 @@ public class EmbeddedDatabaseFactory { } // getParentLogger() is required for JDBC 4.1 compatibility - @SuppressWarnings("unused") public Logger getParentLogger() { return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); } diff --git a/spring-orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java b/spring-orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java index ce0f61aefc..6ed2028384 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java +++ b/spring-orm/src/main/java/org/springframework/orm/jdo/JdoTemplate.java @@ -481,7 +481,6 @@ public class JdoTemplate extends JdoAccessor implements JdoOperations { public Collection find(final String queryString) throws DataAccessException { return execute(new JdoCallback() { - @SuppressWarnings("unchecked") public Collection doInJdo(PersistenceManager pm) throws JDOException { Query query = pm.newQuery(queryString); prepareQuery(query); diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java index 61c2f37df6..a2747bb102 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java @@ -57,7 +57,6 @@ public class FlashAttributeResultMatchers { */ public ResultMatcher attribute(final String name, final Object value) { return new ResultMatcher() { - @SuppressWarnings("unchecked") public void match(MvcResult result) throws Exception { assertEquals("Flash attribute", value, result.getFlashMap().get(name)); } diff --git a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java index 0792d6c6a8..908783e4c1 100644 --- a/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java +++ b/spring-web/src/test/java/org/springframework/http/converter/FormHttpMessageConverterTests.java @@ -72,7 +72,6 @@ public class FormHttpMessageConverterTests { } @Test - @SuppressWarnings("unchecked") public void readForm() throws Exception { String body = "name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3"; Charset iso88591 = Charset.forName("ISO-8859-1"); diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java index 40b600377c..866fcae1ad 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/InitBinderDataBinderFactoryTests.java @@ -140,29 +140,25 @@ public class InitBinderDataBinderFactoryTests { private static class InitBinderHandler { - @SuppressWarnings("unused") @InitBinder public void initBinder(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); } - @SuppressWarnings("unused") @InitBinder(value="foo") public void initBinderWithAttributeName(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); } - @SuppressWarnings("unused") @InitBinder public String initBinderReturnValue(WebDataBinder dataBinder) { return "invalid"; } - @SuppressWarnings("unused") @InitBinder public void initBinderTypeConversion(WebDataBinder dataBinder, @RequestParam int requestParam) { dataBinder.setDisallowedFields("requestParam-" + requestParam); } } -} \ No newline at end of file +} diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java index 170e8e2c9b..42c13d2671 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/ModelAttributeMethodProcessorTests.java @@ -299,7 +299,6 @@ public class ModelAttributeMethodProcessorTests { } } - @SuppressWarnings("unused") @ModelAttribute("modelAttrName") private String annotatedReturnValue() { return null; @@ -310,4 +309,4 @@ public class ModelAttributeMethodProcessorTests { return null; } -} \ No newline at end of file +} From 94a88069ac57a4a8cc69ca2d72c1a0de69efa9e6 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 29 Jan 2013 15:39:37 -0800 Subject: [PATCH 165/311] Update example years to 2013 in CONTRIBUTING.md --- CONTRIBUTING.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 65db556fab..02d0bc12e2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,7 +87,7 @@ present in the framework. ```java /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -108,16 +108,16 @@ package ...; ## Update Apache license header to modified files as necessary Always check the date range in the license header. For example, if you've -modified a file in 2012 whose header still reads +modified a file in 2013 whose header still reads ```java * Copyright 2002-2011 the original author or authors. ``` -then be sure to update it to 2012 appropriately +then be sure to update it to 2013 appropriately ```java - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. ``` ## Use @since tags for newly-added public API types and methods From 6a98b40e1c76a285dd2c364fc189a960f6598615 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 30 Jan 2013 14:57:36 +0100 Subject: [PATCH 166/311] Consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks Issue: SPR-10224 --- .../mock/web/MockHttpServletRequest.java | 3 ++- .../mock/web/MockHttpSession.java | 6 ++++-- .../mock/web/MockPageContext.java | 5 +++-- .../mock/web/MockServletContext.java | 5 ++--- .../mock/web/portlet/MockPortletContext.java | 5 ++--- .../mock/web/portlet/MockPortletRequest.java | 7 +++---- .../mock/web/portlet/MockPortletSession.java | 16 ++++++++-------- 7 files changed, 24 insertions(+), 23 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java index d609f39e8f..0d29289c77 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpServletRequest.java @@ -30,6 +30,7 @@ import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; @@ -294,7 +295,7 @@ public class MockHttpServletRequest implements HttpServletRequest { public Enumeration getAttributeNames() { checkActive(); - return Collections.enumeration(this.attributes.keySet()); + return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); } public String getCharacterEncoding() { diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockHttpSession.java b/spring-test/src/main/java/org/springframework/mock/web/MockHttpSession.java index 1855230d2c..548c2016d1 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockHttpSession.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockHttpSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; @@ -50,6 +51,7 @@ public class MockHttpSession implements HttpSession { public static final String SESSION_COOKIE_NAME = "JSESSION"; + private static int nextId = 1; private final String id; @@ -141,7 +143,7 @@ public class MockHttpSession implements HttpSession { } public Enumeration getAttributeNames() { - return Collections.enumeration(this.attributes.keySet()); + return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); } public String[] getValueNames() { diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java b/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java index b492c1fa98..2c5d07e8e3 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockPageContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.io.UnsupportedEncodingException; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; import javax.el.ELContext; import javax.servlet.Servlet; @@ -249,7 +250,7 @@ public class MockPageContext extends PageContext { } public Enumeration getAttributeNames() { - return Collections.enumeration(this.attributes.keySet()); + return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); } @SuppressWarnings("unchecked") diff --git a/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java b/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java index 562179ceac..40fbabd1a1 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,6 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; - import javax.activation.FileTypeMap; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; @@ -434,7 +433,7 @@ public class MockServletContext implements ServletContext { } public Enumeration getAttributeNames() { - return Collections.enumeration(this.attributes.keySet()); + return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); } public void setAttribute(String name, Object value) { diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java index b1193ff5e1..39dc9f5b29 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import java.util.Vector; import javax.activation.FileTypeMap; import javax.portlet.PortletContext; import javax.portlet.PortletRequestDispatcher; @@ -210,7 +209,7 @@ public class MockPortletContext implements PortletContext { } public Enumeration getAttributeNames() { - return new Vector(this.attributes.keySet()).elements(); + return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); } public void setAttribute(String name, Object value) { diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java index 70e90567b0..38b517351a 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,12 @@ import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.Vector; - import javax.portlet.PortalContext; import javax.portlet.PortletContext; import javax.portlet.PortletMode; @@ -332,7 +331,7 @@ public class MockPortletRequest implements PortletRequest { public Enumeration getAttributeNames() { checkActive(); - return new Vector(this.attributes.keySet()).elements(); + return Collections.enumeration(new LinkedHashSet(this.attributes.keySet())); } public void setParameters(Map parameters) { diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java index 93800340b8..5eaec79906 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockPortletSession.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,10 +18,10 @@ package org.springframework.mock.web.portlet; import java.util.Collections; import java.util.Enumeration; -import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; import java.util.Map; -import java.util.Vector; import javax.portlet.PortletContext; import javax.portlet.PortletSession; import javax.servlet.http.HttpSessionBindingEvent; @@ -51,9 +51,9 @@ public class MockPortletSession implements PortletSession { private final PortletContext portletContext; - private final Map portletAttributes = new HashMap(); + private final Map portletAttributes = new LinkedHashMap(); - private final Map applicationAttributes = new HashMap(); + private final Map applicationAttributes = new LinkedHashMap(); private boolean invalid = false; @@ -92,15 +92,15 @@ public class MockPortletSession implements PortletSession { } public Enumeration getAttributeNames() { - return new Vector(this.portletAttributes.keySet()).elements(); + return Collections.enumeration(new LinkedHashSet(this.portletAttributes.keySet())); } public Enumeration getAttributeNames(int scope) { if (scope == PortletSession.PORTLET_SCOPE) { - return new Vector(this.portletAttributes.keySet()).elements(); + return Collections.enumeration(new LinkedHashSet(this.portletAttributes.keySet())); } else if (scope == PortletSession.APPLICATION_SCOPE) { - return new Vector(this.applicationAttributes.keySet()).elements(); + return Collections.enumeration(new LinkedHashSet(this.applicationAttributes.keySet())); } return null; } From 58f59d6851e40d872225952791741b2b50b43b06 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 30 Jan 2013 14:58:36 +0100 Subject: [PATCH 167/311] MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException Issue: SPR-10226 --- .../http/InvalidMediaTypeException.java | 51 +++++++++++++++++++ .../org/springframework/http/MediaType.java | 33 +++++++----- .../springframework/http/MediaTypeTests.java | 30 +++++------ 3 files changed, 87 insertions(+), 27 deletions(-) create mode 100644 spring-web/src/main/java/org/springframework/http/InvalidMediaTypeException.java diff --git a/spring-web/src/main/java/org/springframework/http/InvalidMediaTypeException.java b/spring-web/src/main/java/org/springframework/http/InvalidMediaTypeException.java new file mode 100644 index 0000000000..358c9c8226 --- /dev/null +++ b/spring-web/src/main/java/org/springframework/http/InvalidMediaTypeException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.http; + +/** + * Exception thrown from {@link MediaType#parseMediaType(String)} in case of + * encountering an invalid media type specification String. + * + * @author Juergen Hoeller + * @since 3.2.2 + */ +@SuppressWarnings("serial") +public class InvalidMediaTypeException extends IllegalArgumentException { + + private String mediaType; + + + /** + * Create a new InvalidMediaTypeException for the given media type. + * @param mediaType the offending media type + * @param msg a detail message indicating the invalid part + */ + public InvalidMediaTypeException(String mediaType, String msg) { + super("Invalid media type \"" + mediaType + "\": " + msg); + this.mediaType = mediaType; + + } + + + /** + * Return the offending media type. + */ + public String getMediaType() { + return this.mediaType; + } + +} diff --git a/spring-web/src/main/java/org/springframework/http/MediaType.java b/spring-web/src/main/java/org/springframework/http/MediaType.java index 99e1b2d124..9f527c7c8c 100644 --- a/spring-web/src/main/java/org/springframework/http/MediaType.java +++ b/spring-web/src/main/java/org/springframework/http/MediaType.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.http; import java.nio.charset.Charset; +import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; @@ -321,8 +322,8 @@ public class MediaType implements Comparable { * @throws IllegalArgumentException if any of the parameters contain illegal characters */ public MediaType(String type, String subtype, Map parameters) { - Assert.hasLength(type, "'type' must not be empty"); - Assert.hasLength(subtype, "'subtype' must not be empty"); + Assert.hasLength(type, "type must not be empty"); + Assert.hasLength(subtype, "subtype must not be empty"); checkToken(type); checkToken(subtype); this.type = type.toLowerCase(Locale.ENGLISH); @@ -347,11 +348,11 @@ public class MediaType implements Comparable { * @throws IllegalArgumentException in case of illegal characters * @see HTTP 1.1, section 2.2 */ - private void checkToken(String s) { - for (int i=0; i < s.length(); i++ ) { - char ch = s.charAt(i); + private void checkToken(String token) { + for (int i=0; i < token.length(); i++ ) { + char ch = token.charAt(i); if (!TOKEN.get(ch)) { - throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + s + "\""); + throw new IllegalArgumentException("Invalid token character '" + ch + "' in token \"" + token + "\""); } } } @@ -681,7 +682,7 @@ public class MediaType implements Comparable { * Parse the given String into a single {@code MediaType}. * @param mediaType the string to parse * @return the media type - * @throws IllegalArgumentException if the string cannot be parsed + * @throws InvalidMediaTypeException if the string cannot be parsed */ public static MediaType parseMediaType(String mediaType) { Assert.hasLength(mediaType, "'mediaType' must not be empty"); @@ -694,15 +695,15 @@ public class MediaType implements Comparable { } int subIndex = fullType.indexOf('/'); if (subIndex == -1) { - throw new IllegalArgumentException("\"" + mediaType + "\" does not contain '/'"); + throw new InvalidMediaTypeException(mediaType, "does not contain '/'"); } if (subIndex == fullType.length() - 1) { - throw new IllegalArgumentException("\"" + mediaType + "\" does not contain subtype after '/'"); + throw new InvalidMediaTypeException(mediaType, "does not contain subtype after '/'"); } String type = fullType.substring(0, subIndex); String subtype = fullType.substring(subIndex + 1, fullType.length()); if (WILDCARD_TYPE.equals(type) && !WILDCARD_TYPE.equals(subtype)) { - throw new IllegalArgumentException("A wildcard type is legal only in '*/*' (all media types)."); + throw new InvalidMediaTypeException(mediaType, "wildcard type is legal only in '*/*' (all media types)"); } Map parameters = null; @@ -719,7 +720,15 @@ public class MediaType implements Comparable { } } - return new MediaType(type, subtype, parameters); + try { + return new MediaType(type, subtype, parameters); + } + catch (UnsupportedCharsetException ex) { + throw new InvalidMediaTypeException(mediaType, "unsupported charset '" + ex.getCharsetName() + "'"); + } + catch (IllegalArgumentException ex) { + throw new InvalidMediaTypeException(mediaType, ex.getMessage()); + } } diff --git a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java index 906c8dec58..d5657d199e 100644 --- a/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java +++ b/spring-web/src/test/java/org/springframework/http/MediaTypeTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,12 +97,12 @@ public class MediaTypeTests { assertEquals("Invalid toString() returned", "text/plain;q=0.7", result); } - @Test(expected= IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void slashInType() { new MediaType("text/plain"); } - @Test(expected= IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void slashInSubtype() { new MediaType("text", "/"); } @@ -122,57 +122,57 @@ public class MediaTypeTests { assertEquals("Invalid quality factor", 0.2D, mediaType.getQualityValue(), 0D); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeNoSubtype() { MediaType.parseMediaType("audio"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeNoSubtypeSlash() { MediaType.parseMediaType("audio/"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeTypeRange() { MediaType.parseMediaType("*/json"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalType() { MediaType.parseMediaType("audio(/basic"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalSubtype() { MediaType.parseMediaType("audio/basic)"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeEmptyParameterAttribute() { MediaType.parseMediaType("audio/*;=value"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeEmptyParameterValue() { MediaType.parseMediaType("audio/*;attr="); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalParameterAttribute() { MediaType.parseMediaType("audio/*;attr<=value"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalParameterValue() { MediaType.parseMediaType("audio/*;attr=v>alue"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalQualityFactor() { MediaType.parseMediaType("audio/basic;q=1.1"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalCharset() { MediaType.parseMediaType("text/html; charset=foo-bar"); } @@ -193,7 +193,7 @@ public class MediaTypeTests { assertEquals("'v>alue'", mediaType.getParameter("attr")); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = InvalidMediaTypeException.class) public void parseMediaTypeIllegalQuotedParameterValue() { MediaType.parseMediaType("audio/*;attr=\""); } From 6d77f1cf3b3f060ead70d49079bc87d75e0b105c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 31 Jan 2013 16:51:56 +0100 Subject: [PATCH 168/311] ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM Issue: SPR-10249 --- .../annotation/ConfigurationClassParser.java | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java index 2901e5cea0..c03aca61dd 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -54,6 +54,7 @@ import org.springframework.core.type.StandardAnnotationMetadata; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.core.type.filter.AssignableTypeFilter; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import static org.springframework.context.annotation.MetadataUtils.*; @@ -228,7 +229,7 @@ class ConfigurationClassParser { // process any @Import annotations Set imports = getImports(metadata.getClassName(), null, new HashSet()); - if (imports != null && !imports.isEmpty()) { + if (!CollectionUtils.isEmpty(imports)) { processImport(configClass, imports.toArray(new String[imports.size()]), true); } @@ -292,9 +293,8 @@ class ConfigurationClassParser { * @return a set of all {@link Import#value() import values} or {@code null} * @throws IOException if there is any problem reading metadata from the named class */ - private Set getImports(String className, Set imports, - Set visited) throws IOException { - if (visited.add(className)) { + private Set getImports(String className, Set imports, Set visited) throws IOException { + if (visited.add(className) && !className.startsWith("java")) { AnnotationMetadata metadata = metadataReaderFactory.getMetadataReader(className).getAnnotationMetadata(); for (String annotationType : metadata.getAnnotationTypes()) { imports = getImports(annotationType, imports, visited); @@ -331,7 +331,7 @@ class ConfigurationClassParser { throw new IllegalStateException(ex); } } - else if (new AssignableTypeFilter(ImportBeanDefinitionRegistrar.class).match(reader, metadataReaderFactory)) { + else if (new AssignableTypeFilter(ImportBeanDefinitionRegistrar.class).match(reader, this.metadataReaderFactory)) { // the candidate class is an ImportBeanDefinitionRegistrar -> delegate to it to register additional bean definitions try { ImportBeanDefinitionRegistrar registrar = BeanUtils.instantiateClass( @@ -360,17 +360,16 @@ class ConfigurationClassParser { private void invokeAwareMethods(ImportBeanDefinitionRegistrar registrar) { if (registrar instanceof Aware) { if (registrar instanceof ResourceLoaderAware) { - ((ResourceLoaderAware) registrar).setResourceLoader(resourceLoader); + ((ResourceLoaderAware) registrar).setResourceLoader(this.resourceLoader); } if (registrar instanceof BeanClassLoaderAware) { - ClassLoader classLoader = - registry instanceof ConfigurableBeanFactory ? - ((ConfigurableBeanFactory) registry).getBeanClassLoader() : - resourceLoader.getClassLoader(); + ClassLoader classLoader = (this.registry instanceof ConfigurableBeanFactory ? + ((ConfigurableBeanFactory) this.registry).getBeanClassLoader() : + this.resourceLoader.getClassLoader()); ((BeanClassLoaderAware) registrar).setBeanClassLoader(classLoader); } - if (registrar instanceof BeanFactoryAware && registry instanceof BeanFactory) { - ((BeanFactoryAware) registrar).setBeanFactory((BeanFactory) registry); + if (registrar instanceof BeanFactoryAware && this.registry instanceof BeanFactory) { + ((BeanFactoryAware) registrar).setBeanFactory((BeanFactory) this.registry); } } } @@ -398,6 +397,7 @@ class ConfigurationClassParser { return this.importStack; } + interface ImportRegistry { String getImportingClassFor(String importedClass); @@ -470,4 +470,5 @@ class ConfigurationClassParser { new Location(importStack.peek().getResource(), metadata)); } } + } From b3af29b8f655176244f42cdf086f69ea25cd6038 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 31 Jan 2013 16:53:04 +0100 Subject: [PATCH 169/311] DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well Also, DefaultMessageListenerContainer logs recovery failures at error level and exposes an "isRecovering()" method now. Issue: SPR-10230 --- .../DefaultMessageListenerContainer.java | 43 +++++++++++++++---- 1 file changed, 35 insertions(+), 8 deletions(-) diff --git a/spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java b/spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java index 91b15c319d..de0132dae1 100644 --- a/spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java +++ b/spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -183,6 +183,8 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe private int registeredWithDestination = 0; + private volatile boolean recovering = false; + private Runnable stopCallback; private Object currentRecoveryMarker = new Object(); @@ -758,6 +760,9 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe super.establishSharedConnection(); } catch (Exception ex) { + if (ex instanceof JMSException) { + invokeExceptionListener((JMSException) ex); + } logger.debug("Could not establish shared JMS Connection - " + "leaving it up to asynchronous invokers to establish a Connection as soon as possible", ex); } @@ -796,7 +801,7 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe /** * Handle the given exception that arose during setup of a listener. * Called for every such exception in every concurrent listener. - *

The default implementation logs the exception at info level + *

The default implementation logs the exception at warn level * if not recovered yet, and at debug level if already recovered. * Can be overridden in subclasses. * @param ex the exception to handle @@ -837,7 +842,7 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe /** * Recover this listener container after a listener failed to set itself up, - * for example reestablishing the underlying Connection. + * for example re-establishing the underlying Connection. *

The default implementation delegates to DefaultMessageListenerContainer's * recovery-capable {@link #refreshConnectionUntilSuccessful()} method, which will * try to re-establish a Connection to the JMS provider both for the shared @@ -846,8 +851,14 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe * @see #refreshDestination() */ protected void recoverAfterListenerSetupFailure() { - refreshConnectionUntilSuccessful(); - refreshDestination(); + this.recovering = true; + try { + refreshConnectionUntilSuccessful(); + refreshDestination(); + } + finally { + this.recovering = false; + } } /** @@ -856,9 +867,11 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe * Connection, so either needs to operate on the shared Connection or on a * temporary Connection that just gets established for validation purposes. *

The default implementation retries until it successfully established a - * Connection, for as long as this message listener container is active. + * Connection, for as long as this message listener container is running. * Applies the specified recovery interval between retries. * @see #setRecoveryInterval + * @see #start() + * @see #stop() */ protected void refreshConnectionUntilSuccessful() { while (isRunning()) { @@ -874,16 +887,19 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe break; } catch (Exception ex) { + if (ex instanceof JMSException) { + invokeExceptionListener((JMSException) ex); + } StringBuilder msg = new StringBuilder(); msg.append("Could not refresh JMS Connection for destination '"); msg.append(getDestinationDescription()).append("' - retrying in "); msg.append(this.recoveryInterval).append(" ms. Cause: "); msg.append(ex instanceof JMSException ? JmsUtils.buildExceptionMessage((JMSException) ex) : ex.getMessage()); if (logger.isDebugEnabled()) { - logger.warn(msg, ex); + logger.error(msg, ex); } else { - logger.warn(msg); + logger.error(msg); } } sleepInbetweenRecoveryAttempts(); @@ -925,6 +941,17 @@ public class DefaultMessageListenerContainer extends AbstractPollingMessageListe } } + /** + * Return whether this listener container is currently in a recovery attempt. + *

May be used to detect recovery phases but also the end of a recovery phase, + * with {@code isRecovering()} switching to {@code false} after having been found + * to return {@code true} before. + * @see #recoverAfterListenerSetupFailure() + */ + public final boolean isRecovering() { + return this.recovering; + } + //------------------------------------------------------------------------- // Inner classes used as internal adapters From bd72fcd4690c6e49e07f84dba264ca943a8a393d Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 31 Jan 2013 16:53:58 +0100 Subject: [PATCH 170/311] Initial preparations for 3.2.2 --- src/dist/changelog.txt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 25b90985b9..70defd90dd 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -3,6 +3,16 @@ SPRING FRAMEWORK CHANGELOG http://www.springsource.org +Changes in version 3.2.2 (2013-03-07) +-------------------------------------- + +* ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) +* DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) +* DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) +* MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) +* consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) + + Changes in version 3.2.1 (2013-01-24) -------------------------------------- From 7d798acd35984b4cedf0e1035305698a618407d8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 31 Jan 2013 17:50:37 +0100 Subject: [PATCH 171/311] Added getOriginalValue() accessor to (Real)Literal Issue: SPR-10248 --- .../expression/spel/ast/Literal.java | 40 +++++++++++++------ 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Literal.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Literal.java index 19ddf7caac..9b35a78a40 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Literal.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Literal.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,23 +17,32 @@ package org.springframework.expression.spel.ast; import org.springframework.expression.TypedValue; -import org.springframework.expression.spel.*; +import org.springframework.expression.spel.ExpressionState; +import org.springframework.expression.spel.InternalParseException; +import org.springframework.expression.spel.SpelEvaluationException; +import org.springframework.expression.spel.SpelMessage; +import org.springframework.expression.spel.SpelParseException; /** * Common superclass for nodes representing literals (boolean, string, number, etc). * * @author Andy Clement + * @author Juergen Hoeller */ public abstract class Literal extends SpelNodeImpl { - protected String literalValue; + private final String originalValue; - public Literal(String payload, int pos) { + + public Literal(String originalValue, int pos) { super(pos); - this.literalValue = payload; + this.originalValue = originalValue; } - public abstract TypedValue getLiteralValue(); + + public final String getOriginalValue() { + return this.originalValue; + } @Override public final TypedValue getValueInternal(ExpressionState state) throws SpelEvaluationException { @@ -50,10 +59,13 @@ public abstract class Literal extends SpelNodeImpl { return toString(); } + + public abstract TypedValue getLiteralValue(); + + /** * Process the string form of a number, using the specified base if supplied and return an appropriate literal to * hold it. Any suffix to indicate a long will be taken into account (either 'l' or 'L' is supported). - * * @param numberToken the token holding the number as its payload (eg. 1234 or 0xCAFE) * @param radix the base of number * @return a subtype of Literal that can represent it @@ -62,7 +74,8 @@ public abstract class Literal extends SpelNodeImpl { try { int value = Integer.parseInt(numberToken, radix); return new IntLiteral(numberToken, pos, value); - } catch (NumberFormatException nfe) { + } + catch (NumberFormatException nfe) { throw new InternalParseException(new SpelParseException(pos>>16, nfe, SpelMessage.NOT_AN_INTEGER, numberToken)); } } @@ -71,25 +84,26 @@ public abstract class Literal extends SpelNodeImpl { try { long value = Long.parseLong(numberToken, radix); return new LongLiteral(numberToken, pos, value); - } catch (NumberFormatException nfe) { + } + catch (NumberFormatException nfe) { throw new InternalParseException(new SpelParseException(pos>>16, nfe, SpelMessage.NOT_A_LONG, numberToken)); } } - public static Literal getRealLiteral(String numberToken, int pos, boolean isFloat) { try { if (isFloat) { float value = Float.parseFloat(numberToken); return new FloatLiteral(numberToken, pos, value); - } else { + } + else { double value = Double.parseDouble(numberToken); return new RealLiteral(numberToken, pos, value); } - } catch (NumberFormatException nfe) { + } + catch (NumberFormatException nfe) { throw new InternalParseException(new SpelParseException(pos>>16, nfe, SpelMessage.NOT_A_REAL, numberToken)); } } } - From a694db2933b9f86455e2cb53c9933d3fd79b1904 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 31 Jan 2013 18:01:01 +0100 Subject: [PATCH 172/311] Removed logging from GenericTypeResolver's resolveReturnTypeForGenericMethod GenericTypeResolver is very low-level and quite a hotspot, so let's not do any logging there and rather use the debugger instead. --- .../core/GenericTypeResolver.java | 66 ++++--------------- 1 file changed, 13 insertions(+), 53 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java b/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java index cb9e8fba33..3842a741c7 100644 --- a/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java +++ b/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,11 +26,7 @@ import java.lang.reflect.WildcardType; import java.util.HashMap; import java.util.Map; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; import org.springframework.util.ConcurrentReferenceHashMap; /** @@ -47,12 +43,11 @@ import org.springframework.util.ConcurrentReferenceHashMap; */ public abstract class GenericTypeResolver { - private static final Log logger = LogFactory.getLog(GenericTypeResolver.class); - /** Cache from Class to TypeVariable Map */ private static final Map> typeVariableCache = new ConcurrentReferenceHashMap>(); + /** * Determine the target type for the given parameter specification. * @param methodParam the method parameter specification @@ -93,7 +88,6 @@ public abstract class GenericTypeResolver { /** * Determine the target type for the generic return type of the given method, * where formal type variables are declared on the given class. - * * @param method the method to introspect * @param clazz the class to resolve type variables against * @return the corresponding generic parameter or return type @@ -112,15 +106,12 @@ public abstract class GenericTypeResolver { * Determine the target type for the generic return type of the given * generic method, where formal type variables are declared on * the given method itself. - * *

For example, given a factory method with the following signature, * if {@code resolveReturnTypeForGenericMethod()} is invoked with the reflected * method for {@code creatProxy()} and an {@code Object[]} array containing * {@code MyService.class}, {@code resolveReturnTypeForGenericMethod()} will * infer that the target return type is {@code MyService}. - * *

{@code public static  T createProxy(Class clazz)}
- * *

Possible Return Values

*
    *
  • the target return type, if it can be inferred
  • @@ -134,27 +125,20 @@ public abstract class GenericTypeResolver { * Method#getGenericParameterTypes() formal argument list} for the given * method *
- * * @param method the method to introspect, never {@code null} * @param args the arguments that will be supplied to the method when it is * invoked, never {@code null} - * @return the resolved target return type, the standard return type, or - * {@code null} + * @return the resolved target return type, the standard return type, or {@code null} * @since 3.2 * @see #resolveReturnType */ public static Class resolveReturnTypeForGenericMethod(Method method, Object[] args) { - Assert.notNull(method, "method must not be null"); - Assert.notNull(args, "args must not be null"); + Assert.notNull(method, "Method must not be null"); + Assert.notNull(args, "Argument array must not be null"); - if (logger.isDebugEnabled()) { - logger.debug(String.format("Resolving return type for [%s] with concrete method arguments [%s].", - method.toGenericString(), ObjectUtils.nullSafeToString(args))); - } - - final TypeVariable[] declaredTypeVariables = method.getTypeParameters(); - final Type genericReturnType = method.getGenericReturnType(); - final Type[] methodArgumentTypes = method.getGenericParameterTypes(); + TypeVariable[] declaredTypeVariables = method.getTypeParameters(); + Type genericReturnType = method.getGenericReturnType(); + Type[] methodArgumentTypes = method.getGenericParameterTypes(); // No declared type variables to inspect, so just return the standard return type. if (declaredTypeVariables.length == 0) { @@ -172,11 +156,6 @@ public abstract class GenericTypeResolver { boolean locallyDeclaredTypeVariableMatchesReturnType = false; for (TypeVariable currentTypeVariable : declaredTypeVariables) { if (currentTypeVariable.equals(genericReturnType)) { - if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Found declared type variable [%s] that matches the target return type [%s].", - currentTypeVariable, genericReturnType)); - } locallyDeclaredTypeVariableMatchesReturnType = true; break; } @@ -184,39 +163,20 @@ public abstract class GenericTypeResolver { if (locallyDeclaredTypeVariableMatchesReturnType) { for (int i = 0; i < methodArgumentTypes.length; i++) { - final Type currentMethodArgumentType = methodArgumentTypes[i]; - + Type currentMethodArgumentType = methodArgumentTypes[i]; if (currentMethodArgumentType.equals(genericReturnType)) { - if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Found method argument type at index [%s] that matches the target return type.", i)); - } return args[i].getClass(); } - if (currentMethodArgumentType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) currentMethodArgumentType; Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); - - for (int j = 0; j < actualTypeArguments.length; j++) { - final Type typeArg = actualTypeArguments[j]; - + for (Type typeArg : actualTypeArguments) { if (typeArg.equals(genericReturnType)) { - if (logger.isDebugEnabled()) { - logger.debug(String.format( - "Found method argument type at index [%s] that is parameterized with a type argument that matches the target return type.", - i)); - } - if (args[i] instanceof Class) { return (Class) args[i]; - } else { - // Consider adding logic to determine the class of the - // J'th typeArg, if possible. - logger.info(String.format( - "Could not determine the target type for type argument [%s] for method [%s].", - typeArg, method.toGenericString())); - + } + else { + // Consider adding logic to determine the class of the typeArg, if possible. // For now, just fall back... return method.getReturnType(); } From ae0c34baaf341bd65a1077d472e3b161cce2e704 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 1 Feb 2013 15:40:01 +0100 Subject: [PATCH 173/311] Improve 3.2 migration guide re: JUnit & Hamcrest This commit improves the "Spring Test Dependencies" section of the 3.2 migration guide by correctly explaining that Hamcrest Core is now a required transitive dependency of JUnit. Issue: SPR-10251 --- src/reference/docbook/migration-3.2.xml | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/reference/docbook/migration-3.2.xml b/src/reference/docbook/migration-3.2.xml index c96b43d8ba..79f5c9150c 100644 --- a/src/reference/docbook/migration-3.2.xml +++ b/src/reference/docbook/migration-3.2.xml @@ -138,16 +138,14 @@ depend on JUnit 4.11 (junit:junit), TestNG 6.5.2 (org.testng:testng), and Hamcrest Core 1.3 (org.hamcrest:hamcrest-core). Each of these - dependencies is declared as an optional dependency - in the Maven POM. Furthermore, it is important to note that the JUnit - team has stopped inlining Hamcrest Core within the - junit:junit Maven artifact as of JUnit 4.11. Thus, if - your existing JUnit-based tests make use of Hamcrest matchers that were - previously available directly within the junit:junit - JAR, you will now need to explicitly declare a dependency on - org.hamcrest:hamcrest-core, - org.hamcrest:hamcrest-library, or - org.hamcrest:hamcrest-all. + dependencies is declared as an optional dependency in + the Maven POM. Furthermore, it is important to note that the JUnit team + has stopped inlining Hamcrest Core within the + junit:junit Maven artifact as of JUnit 4.11. Hamcrest + Core is now a required transitive dependency of + junit, and users may therefore need to remove any + exclusions on hamcrest-core that they had previously + configured for their build.
From 220d2311c7ab50d441f5aaa1dbb480d762ebcff4 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Fri, 1 Feb 2013 23:51:07 +0100 Subject: [PATCH 174/311] Polish documentation in Hibernate support classes This commit fixes some minor typos in Hibernate support classes. --- .../orm/hibernate4/HibernateTransactionManager.java | 12 ++++++------ .../orm/hibernate4/LocalSessionFactoryBean.java | 3 ++- .../orm/hibernate3/HibernateTransactionManager.java | 10 +++++----- .../orm/hibernate3/SessionFactoryUtils.java | 4 ++-- 4 files changed, 15 insertions(+), 14 deletions(-) diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java index ddde103c1d..6d3e7ccf25 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -150,8 +150,8 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * The DataSource should match the one used by the Hibernate SessionFactory: * for example, you could specify the same JNDI DataSource for both. *

If the SessionFactory was configured with LocalDataSourceConnectionProvider, - * i.e. by Spring's SessionFactoryBuilder with a specified "dataSource", - * the DataSource will be auto-detected: You can still explictly specify the + * i.e. by Spring's LocalSessionFactoryBean with a specified "dataSource", + * the DataSource will be auto-detected: You can still explicitly specify the * DataSource, but you don't need to in this case. *

A transactional JDBC Connection for this DataSource will be provided to * application code accessing this DataSource directly via DataSourceUtils @@ -188,7 +188,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana /** * Set whether to autodetect a JDBC DataSource used by the Hibernate SessionFactory, - * if set via SessionFactoryBuilder's {@code setDataSource}. Default is "true". + * if set via LocalSessionFactoryBean's {@code setDataSource}. Default is "true". *

Can be turned off to deliberately ignore an available DataSource, in order * to not expose Hibernate transactions as JDBC transactions for that DataSource. * @see #setDataSource @@ -358,7 +358,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana } if (definition.isReadOnly() && txObject.isNewSession()) { - // Just set to NEVER in case of a new Session for this transaction. + // Just set to MANUAL in case of a new Session for this transaction. session.setFlushMode(FlushMode.MANUAL); } @@ -586,7 +586,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * from the {@code org.springframework.dao} hierarchy. *

Will automatically apply a specified SQLExceptionTranslator to a * Hibernate JDBCException, else rely on Hibernate's default translation. - * @param ex HibernateException that occured + * @param ex HibernateException that occurred * @return a corresponding DataAccessException * @see SessionFactoryUtils#convertHibernateAccessException */ diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBean.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBean.java index dea7f1a139..f281415008 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBean.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,6 +58,7 @@ import org.springframework.core.io.support.ResourcePatternUtils; * @since 3.1 * @see #setDataSource * @see #setPackagesToScan + * @see LocalSessionFactoryBuilder */ public class LocalSessionFactoryBean extends HibernateExceptionTranslator implements FactoryBean, ResourceLoaderAware, InitializingBean, DisposableBean { diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java index d3d1e13733..896a91379f 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -196,7 +196,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * for example, you could specify the same JNDI DataSource for both. *

If the SessionFactory was configured with LocalDataSourceConnectionProvider, * i.e. by Spring's LocalSessionFactoryBean with a specified "dataSource", - * the DataSource will be auto-detected: You can still explictly specify the + * the DataSource will be auto-detected: You can still explicitly specify the * DataSource, but you don't need to in this case. *

A transactional JDBC Connection for this DataSource will be provided to * application code accessing this DataSource directly via DataSourceUtils @@ -527,7 +527,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana } if (definition.isReadOnly() && txObject.isNewSession()) { - // Just set to NEVER in case of a new Session for this transaction. + // Just set to MANUAL in case of a new Session for this transaction. session.setFlushMode(FlushMode.MANUAL); } @@ -779,7 +779,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * from the {@code org.springframework.dao} hierarchy. *

Will automatically apply a specified SQLExceptionTranslator to a * Hibernate JDBCException, else rely on Hibernate's default translation. - * @param ex HibernateException that occured + * @param ex HibernateException that occurred * @return a corresponding DataAccessException * @see SessionFactoryUtils#convertHibernateAccessException * @see #setJdbcExceptionTranslator @@ -798,7 +798,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * Convert the given Hibernate JDBCException to an appropriate exception * from the {@code org.springframework.dao} hierarchy, using the * given SQLExceptionTranslator. - * @param ex Hibernate JDBCException that occured + * @param ex Hibernate JDBCException that occurred * @param translator the SQLExceptionTranslator to use * @return a corresponding DataAccessException */ diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryUtils.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryUtils.java index 49c49a6976..a6e13b673d 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryUtils.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/SessionFactoryUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -621,7 +621,7 @@ public abstract class SessionFactoryUtils { /** * Convert the given HibernateException to an appropriate exception * from the {@code org.springframework.dao} hierarchy. - * @param ex HibernateException that occured + * @param ex HibernateException that occurred * @return the corresponding DataAccessException instance * @see HibernateAccessor#convertHibernateAccessException * @see HibernateTransactionManager#convertHibernateAccessException From f464a45ba481ff3e960ad3dd8b5edd4464a46289 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 1 Feb 2013 10:14:01 -0800 Subject: [PATCH 175/311] Polish formatting Minor formatting polish across that codebase. Primarily fixing whitespace issues. --- .../aop/aspectj/AspectJExpressionPointcut.java | 4 ++-- .../org/springframework/aop/aspectj/AspectJProxyUtils.java | 4 ++-- .../InstantiationModelAwarePointcutAdvisorImpl.java | 4 ++-- .../aop/framework/autoproxy/AbstractAutoProxyCreator.java | 4 ++-- .../aop/support/DelegatingIntroductionInterceptor.java | 2 +- .../aspectj/MethodInvocationProceedingJoinPointTests.java | 4 ++-- .../annotation/AbstractAspectJAdvisorFactoryTests.java | 2 +- .../springframework/aop/framework/AopProxyUtilsTests.java | 2 +- .../springframework/aop/framework/PrototypeTargetTests.java | 1 - .../aop/interceptor/ExposeInvocationInterceptorTests.java | 2 +- .../tests/aop/advice/CountingAfterReturningAdvice.java | 2 +- .../springframework/tests/aop/advice/MyThrowsHandler.java | 2 +- .../test/java/test/annotation/EmptySpringAnnotation.java | 2 +- spring-aop/src/test/java/test/aop/Lockable.java | 2 +- spring-aop/src/test/java/test/aop/PerTargetAspect.java | 2 +- spring-aop/src/test/java/test/aop/TwoAdviceAspect.java | 2 +- .../annotation/aspectj/SpringConfiguredConfiguration.java | 2 +- .../aspectj/SpringConfiguredWithAutoProxyingTests.java | 2 +- .../cache/config/AnnotatedClassCacheableService.java | 2 +- .../org/springframework/cache/config/CacheableService.java | 2 +- .../java/org/springframework/beans/BeanWrapperImpl.java | 2 +- .../main/java/org/springframework/beans/factory/Aware.java | 2 +- .../annotation/AutowiredAnnotationBeanPostProcessor.java | 4 ++-- .../annotation/InitDestroyAnnotationBeanPostProcessor.java | 4 ++-- .../annotation/RequiredAnnotationBeanPostProcessor.java | 4 ++-- .../beans/factory/config/CustomEditorConfigurer.java | 4 ++-- .../beans/factory/config/RuntimeBeanNameReference.java | 2 +- .../beans/factory/config/RuntimeBeanReference.java | 2 +- .../beans/factory/support/BeanDefinitionBuilder.java | 2 +- .../beans/factory/support/ConstructorResolver.java | 2 +- .../beans/factory/support/DefaultListableBeanFactory.java | 4 ++-- .../beans/factory/wiring/BeanConfigurerSupport.java | 2 +- .../beans/factory/xml/DelegatingEntityResolver.java | 2 +- .../factory/xml/SimpleConstructorNamespaceHandler.java | 2 +- .../scheduling/quartz/SchedulerFactoryBean.java | 2 +- .../cache/interceptor/CacheAspectSupport.java | 2 +- .../cache/interceptor/ExpressionEvaluator.java | 2 +- .../cache/interceptor/LazyParamAwareEvaluationContext.java | 2 +- .../org/springframework/context/annotation/AdviceMode.java | 2 +- .../annotation/CommonAnnotationBeanPostProcessor.java | 2 +- .../context/annotation/EnableAspectJAutoProxy.java | 2 +- .../context/annotation/ImportBeanDefinitionRegistrar.java | 2 +- .../config/PropertyOverrideBeanDefinitionParser.java | 2 +- .../context/support/ResourceBundleMessageSource.java | 2 +- .../ejb/access/SimpleRemoteSlsbInvokerInterceptor.java | 2 +- .../format/support/FormattingConversionService.java | 2 +- .../support/FormattingConversionServiceFactoryBean.java | 2 +- .../instrument/classloading/ReflectiveLoadTimeWeaver.java | 2 +- .../classloading/SimpleInstrumentableClassLoader.java | 2 +- .../instrument/classloading/jboss/JBossMCAdapter.java | 2 +- .../classloading/jboss/JBossMCTranslatorAdapter.java | 2 +- .../instrument/classloading/jboss/JBossModulesAdapter.java | 2 +- .../classloading/oc4j/OC4JClassLoaderAdapter.java | 2 +- .../classloading/oc4j/OC4JClassPreprocessorAdapter.java | 2 +- .../instrument/classloading/oc4j/OC4JLoadTimeWeaver.java | 1 - .../classloading/weblogic/WebLogicClassLoaderAdapter.java | 2 +- .../weblogic/WebLogicClassPreProcessorAdapter.java | 2 +- .../classloading/weblogic/WebLogicLoadTimeWeaver.java | 2 +- .../org/springframework/jmx/export/SpringModelMBean.java | 2 +- .../springframework/remoting/rmi/RmiClientInterceptor.java | 4 ++-- .../springframework/remoting/rmi/RmiServiceExporter.java | 2 +- .../springframework/scripting/jruby/JRubyScriptUtils.java | 2 +- .../scripting/support/ResourceScriptSource.java | 2 +- .../springframework/core/NamedInheritableThreadLocal.java | 2 +- .../org/springframework/core/env/MapPropertySource.java | 2 +- .../core/env/SimpleCommandLineArgsParser.java | 2 +- .../src/main/java/org/springframework/core/io/VfsUtils.java | 2 +- .../classreading/AnnotationAttributesReadingVisitor.java | 2 +- .../type/classreading/MethodMetadataReadingVisitor.java | 2 +- .../java/org/springframework/util/CompositeIterator.java | 2 +- .../java/org/springframework/expression/MethodFilter.java | 2 +- .../expression/spel/ast/CompoundExpression.java | 1 + .../org/springframework/expression/spel/ast/Projection.java | 2 +- .../org/springframework/expression/spel/ast/Selection.java | 6 +++--- .../springframework/expression/spel/ast/SpelNodeImpl.java | 1 - .../org/springframework/expression/spel/standard/Token.java | 2 +- .../springframework/expression/spel/standard/TokenKind.java | 2 +- .../jdbc/core/metadata/CallParameterMetaData.java | 2 +- .../jdbc/core/metadata/DerbyTableMetaDataProvider.java | 2 +- .../datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java | 2 +- .../java/org/springframework/oxm/GenericUnmarshaller.java | 2 +- .../java/org/springframework/web/struts/package-info.java | 2 +- .../mock/web/portlet/MockClientDataRequest.java | 2 +- .../org/springframework/mock/web/portlet/MockEvent.java | 2 +- .../springframework/mock/web/portlet/MockEventRequest.java | 2 +- .../mock/web/portlet/MockStateAwareResponse.java | 2 +- .../springframework/test/context/TestContextManager.java | 2 +- .../http/client/CommonsClientHttpResponse.java | 2 +- .../http/converter/feed/RssChannelHttpMessageConverter.java | 3 +-- .../springframework/web/bind/annotation/ResponseBody.java | 2 +- .../web/bind/support/WebDataBinderFactory.java | 2 +- .../springframework/web/method/HandlerMethodSelector.java | 2 +- .../AbstractCookieValueMethodArgumentResolver.java | 2 +- .../annotation/ExpressionValueMethodArgumentResolver.java | 2 +- .../springframework/web/method/annotation/ModelFactory.java | 2 +- .../annotation/RequestHeaderMethodArgumentResolver.java | 2 +- .../annotation/RequestParamMethodArgumentResolver.java | 2 +- .../web/method/support/HandlerMethodArgumentResolver.java | 2 +- .../web/method/support/HandlerMethodReturnValueHandler.java | 2 +- .../config/annotation/DefaultServletHandlerConfigurer.java | 2 +- .../servlet/config/annotation/ResourceHandlerRegistry.java | 2 +- .../servlet/config/annotation/ViewControllerRegistry.java | 2 +- .../servlet/config/annotation/WebMvcConfigurerAdapter.java | 2 +- .../servlet/mvc/condition/AbstractMediaTypeExpression.java | 2 +- .../web/servlet/mvc/condition/MediaTypeExpression.java | 2 +- .../web/servlet/mvc/condition/NameValueExpression.java | 2 +- .../annotation/PathVariableMapMethodArgumentResolver.java | 2 +- .../annotation/PathVariableMethodArgumentResolver.java | 2 +- .../mvc/method/annotation/RequestMappingHandlerAdapter.java | 2 +- .../annotation/RequestResponseBodyMethodProcessor.java | 2 +- .../ServletCookieValueMethodArgumentResolver.java | 2 +- .../annotation/ServletModelAttributeMethodProcessor.java | 2 +- .../annotation/ServletWebArgumentResolverAdapter.java | 2 +- .../servlet/view/jasperreports/JasperReportsCsvView.java | 2 +- 114 files changed, 124 insertions(+), 127 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java index 7e101ea57d..e14f254612 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJExpressionPointcut.java @@ -282,8 +282,8 @@ public class AspectJExpressionPointcut extends AbstractExpressionPointcut return false; } else { - // the maybe case - return (beanHasIntroductions || matchesIgnoringSubtypes(shadowMatch) || matchesTarget(shadowMatch, targetClass)); + // the maybe case + return (beanHasIntroductions || matchesIgnoringSubtypes(shadowMatch) || matchesTarget(shadowMatch, targetClass)); } } diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJProxyUtils.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJProxyUtils.java index 3463e8cc61..0fe0559679 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJProxyUtils.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJProxyUtils.java @@ -64,8 +64,8 @@ public abstract class AspectJProxyUtils { */ private static boolean isAspectJAdvice(Advisor advisor) { return (advisor instanceof InstantiationModelAwarePointcutAdvisor || - advisor.getAdvice() instanceof AbstractAspectJAdvice || - (advisor instanceof PointcutAdvisor && + advisor.getAdvice() instanceof AbstractAspectJAdvice || + (advisor instanceof PointcutAdvisor && ((PointcutAdvisor) advisor).getPointcut() instanceof AspectJExpressionPointcut)); } diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java index b9863ab67a..65e296f594 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/InstantiationModelAwarePointcutAdvisorImpl.java @@ -63,8 +63,8 @@ class InstantiationModelAwarePointcutAdvisorImpl private Boolean isAfterAdvice; - public InstantiationModelAwarePointcutAdvisorImpl(AspectJAdvisorFactory af, AspectJExpressionPointcut ajexp, - MetadataAwareAspectInstanceFactory aif, Method method, int declarationOrderInAspect, String aspectName) { + public InstantiationModelAwarePointcutAdvisorImpl(AspectJAdvisorFactory af, AspectJExpressionPointcut ajexp, + MetadataAwareAspectInstanceFactory aif, Method method, int declarationOrderInAspect, String aspectName) { this.declaredPointcut = ajexp; this.method = method; diff --git a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java index 06010d6710..d66adc843c 100644 --- a/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java +++ b/spring-aop/src/main/java/org/springframework/aop/framework/autoproxy/AbstractAutoProxyCreator.java @@ -152,11 +152,11 @@ public abstract class AbstractAutoProxyCreator extends ProxyConfig * @param order ordering value */ public final void setOrder(int order) { - this.order = order; + this.order = order; } public final int getOrder() { - return this.order; + return this.order; } /** diff --git a/spring-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java b/spring-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java index c27d1872cf..a695d98e4c 100644 --- a/spring-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java +++ b/spring-aop/src/main/java/org/springframework/aop/support/DelegatingIntroductionInterceptor.java @@ -95,7 +95,7 @@ public class DelegatingIntroductionInterceptor extends IntroductionInfoSupport /** - * Subclasses may need to override this if they want to perform custom + * Subclasses may need to override this if they want to perform custom * behaviour in around advice. However, subclasses should invoke this * method, which handles introduced interfaces and forwarding to the target. */ diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java index 551756eea7..0e0e4377c9 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/MethodInvocationProceedingJoinPointTests.java @@ -139,7 +139,7 @@ public final class MethodInvocationProceedingJoinPointTests { @Override public void before(Method method, Object[] args, Object target) throws Throwable { SourceLocation sloc = AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(); - assertEquals("Same source location must be returned on subsequent requests", sloc, AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()); + assertEquals("Same source location must be returned on subsequent requests", sloc, AbstractAspectJAdvice.currentJoinPoint().getSourceLocation()); assertEquals(TestBean.class, sloc.getWithinType()); try { sloc.getLine(); @@ -172,7 +172,7 @@ public final class MethodInvocationProceedingJoinPointTests { @Override public void before(Method method, Object[] args, Object target) throws Throwable { StaticPart staticPart = AbstractAspectJAdvice.currentJoinPoint().getStaticPart(); - assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart()); + assertEquals("Same static part must be returned on subsequent requests", staticPart, AbstractAspectJAdvice.currentJoinPoint().getStaticPart()); assertEquals(ProceedingJoinPoint.METHOD_EXECUTION, staticPart.getKind()); assertSame(AbstractAspectJAdvice.currentJoinPoint().getSignature(), staticPart.getSignature()); assertEquals(AbstractAspectJAdvice.currentJoinPoint().getSourceLocation(), staticPart.getSourceLocation()); diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java index 5180ca7d14..d0009394a1 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/annotation/AbstractAspectJAdvisorFactoryTests.java @@ -940,7 +940,7 @@ abstract class AbstractMakeModifiable { } // Find the current raw value, by invoking the corresponding setter - Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod()); + Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod()); boolean modified = true; if (correspondingGetter != null) { try { diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java index e2abdda799..bfd5a35c07 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/AopProxyUtilsTests.java @@ -137,4 +137,4 @@ public final class AopProxyUtilsTests { AopProxyUtils.proxiedUserInterfaces(proxy); } -} \ No newline at end of file +} diff --git a/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java b/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java index d9d43527de..3c373cdb77 100644 --- a/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/framework/PrototypeTargetTests.java @@ -63,7 +63,6 @@ public final class PrototypeTargetTests { assertEquals(10, interceptor.invocationCount); } - public static interface TestBean { public void doSomething(); } diff --git a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java index 5405d09831..5a0cc658c9 100644 --- a/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/interceptor/ExposeInvocationInterceptorTests.java @@ -44,7 +44,7 @@ public final class ExposeInvocationInterceptorTests { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(CONTEXT); ITestBean tb = (ITestBean) bf.getBean("proxy"); - String name= "tony"; + String name = "tony"; tb.setName(name); // Fires context checks assertEquals(name, tb.getName()); diff --git a/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java index 5b206516af..2b37761fab 100644 --- a/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/CountingAfterReturningAdvice.java @@ -33,4 +33,4 @@ public class CountingAfterReturningAdvice extends MethodCounter implements After count(m); } -} \ No newline at end of file +} diff --git a/spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java b/spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java index 96edd1280c..cb2d10d6ab 100644 --- a/spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java +++ b/spring-aop/src/test/java/org/springframework/tests/aop/advice/MyThrowsHandler.java @@ -24,4 +24,4 @@ public class MyThrowsHandler extends MethodCounter implements ThrowsAdvice { public void afterThrowing(Method m, Exception ex) throws Throwable { throw new UnsupportedOperationException("Shouldn't be called"); } -} \ No newline at end of file +} diff --git a/spring-aop/src/test/java/test/annotation/EmptySpringAnnotation.java b/spring-aop/src/test/java/test/annotation/EmptySpringAnnotation.java index 60c43c858f..140f0fee3d 100644 --- a/spring-aop/src/test/java/test/annotation/EmptySpringAnnotation.java +++ b/spring-aop/src/test/java/test/annotation/EmptySpringAnnotation.java @@ -25,4 +25,4 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) public @interface EmptySpringAnnotation { -} \ No newline at end of file +} diff --git a/spring-aop/src/test/java/test/aop/Lockable.java b/spring-aop/src/test/java/test/aop/Lockable.java index 039b06e8a7..e62a4e2ff3 100644 --- a/spring-aop/src/test/java/test/aop/Lockable.java +++ b/spring-aop/src/test/java/test/aop/Lockable.java @@ -30,4 +30,4 @@ public interface Lockable { void unlock(); boolean locked(); -} \ No newline at end of file +} diff --git a/spring-aop/src/test/java/test/aop/PerTargetAspect.java b/spring-aop/src/test/java/test/aop/PerTargetAspect.java index 3896f2dc7a..7c8c1fec83 100644 --- a/spring-aop/src/test/java/test/aop/PerTargetAspect.java +++ b/spring-aop/src/test/java/test/aop/PerTargetAspect.java @@ -33,4 +33,4 @@ public class PerTargetAspect implements Ordered { public void setOrder(int order) { this.order = order; } -} \ No newline at end of file +} diff --git a/spring-aop/src/test/java/test/aop/TwoAdviceAspect.java b/spring-aop/src/test/java/test/aop/TwoAdviceAspect.java index 42ee4bf0ca..6745457a9d 100644 --- a/spring-aop/src/test/java/test/aop/TwoAdviceAspect.java +++ b/spring-aop/src/test/java/test/aop/TwoAdviceAspect.java @@ -34,4 +34,4 @@ public class TwoAdviceAspect { public void countSet(int newAge) throws Exception { ++totalCalls; } -} \ No newline at end of file +} diff --git a/spring-aspects/src/main/java/org/springframework/context/annotation/aspectj/SpringConfiguredConfiguration.java b/spring-aspects/src/main/java/org/springframework/context/annotation/aspectj/SpringConfiguredConfiguration.java index 51347810dd..8534fd76b5 100644 --- a/spring-aspects/src/main/java/org/springframework/context/annotation/aspectj/SpringConfiguredConfiguration.java +++ b/spring-aspects/src/main/java/org/springframework/context/annotation/aspectj/SpringConfiguredConfiguration.java @@ -29,7 +29,7 @@ import org.springframework.context.annotation.Role; * Configurable}. * *

This configuration class is automatically imported when using the @{@link - * EnableSpringConfigured} annotation. See {@code @EnableSpringConfigured} Javadoc for + * EnableSpringConfigured} annotation. See {@code @EnableSpringConfigured} Javadoc for * complete usage details. * * @author Chris Beams diff --git a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java index 1c678ba6b1..aae9ff6cd7 100644 --- a/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java +++ b/spring-aspects/src/test/java/org/springframework/beans/factory/aspectj/SpringConfiguredWithAutoProxyingTests.java @@ -30,4 +30,4 @@ public class SpringConfiguredWithAutoProxyingTests extends TestCase { public void testSpringConfiguredAndAutoProxyUsedTogether() { ; // set up is sufficient to trigger failure if this is going to fail... } -} \ No newline at end of file +} diff --git a/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java index 52a1b4265e..5e64cb7fcc 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java +++ b/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java @@ -135,4 +135,4 @@ public class AnnotatedClassCacheableService implements CacheableService public Object multiUpdate(Object arg1) { return arg1; } -} \ No newline at end of file +} diff --git a/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java index 81dd758d19..09ad7df998 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java +++ b/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java @@ -67,4 +67,4 @@ public interface CacheableService { T multiConditionalCacheAndEvict(Object arg1); T multiUpdate(Object arg1); -} \ No newline at end of file +} diff --git a/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java b/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java index bac8df4ce6..df5def12a8 100644 --- a/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java +++ b/spring-beans/src/main/java/org/springframework/beans/BeanWrapperImpl.java @@ -699,7 +699,7 @@ public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWra return nestedBw.getPropertyValue(tokens); } - private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { + private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException { String propertyName = tokens.canonicalName; String actualName = tokens.actualName; PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName); diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/Aware.java b/spring-beans/src/main/java/org/springframework/beans/factory/Aware.java index fb107425c3..f993f1f713 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/Aware.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/Aware.java @@ -19,7 +19,7 @@ package org.springframework.beans.factory; /** * Marker superinterface indicating that a bean is eligible to be * notified by the Spring container of a particular framework object - * through a callback-style method. Actual method signature is + * through a callback-style method. Actual method signature is * determined by individual subinterfaces, but should typically * consist of just one void-returning method that accepts a single * argument. diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java index e1f0e2f392..6775dd78ed 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java @@ -196,11 +196,11 @@ public class AutowiredAnnotationBeanPostProcessor extends InstantiationAwareBean } public void setOrder(int order) { - this.order = order; + this.order = order; } public int getOrder() { - return this.order; + return this.order; } public void setBeanFactory(BeanFactory beanFactory) throws BeansException { diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java index 74a5e59d24..62f62dccd9 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/InitDestroyAnnotationBeanPostProcessor.java @@ -109,11 +109,11 @@ public class InitDestroyAnnotationBeanPostProcessor } public void setOrder(int order) { - this.order = order; + this.order = order; } public int getOrder() { - return this.order; + return this.order; } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java index 862dbd6fa6..4e94523486 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.java @@ -123,11 +123,11 @@ public class RequiredAnnotationBeanPostProcessor extends InstantiationAwareBeanP } public void setOrder(int order) { - this.order = order; + this.order = order; } public int getOrder() { - return this.order; + return this.order; } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java index 03e5716fdd..a9b29f9657 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/CustomEditorConfigurer.java @@ -116,11 +116,11 @@ public class CustomEditorConfigurer implements BeanFactoryPostProcessor, BeanCla public void setOrder(int order) { - this.order = order; + this.order = order; } public int getOrder() { - return this.order; + return this.order; } /** diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanNameReference.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanNameReference.java index 7477e197cb..b23c93e97f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanNameReference.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanNameReference.java @@ -80,7 +80,7 @@ public class RuntimeBeanNameReference implements BeanReference { @Override public String toString() { - return '<' + getBeanName() + '>'; + return '<' + getBeanName() + '>'; } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanReference.java b/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanReference.java index 836098ff8c..e9e5e60a7a 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanReference.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/config/RuntimeBeanReference.java @@ -107,7 +107,7 @@ public class RuntimeBeanReference implements BeanReference { @Override public String toString() { - return '<' + getBeanName() + '>'; + return '<' + getBeanName() + '>'; } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java index 6a2cb27e49..5b9b571f80 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java @@ -30,7 +30,7 @@ import org.springframework.util.ObjectUtils; * @author Juergen Hoeller * @since 2.0 */ -public class BeanDefinitionBuilder { +public class BeanDefinitionBuilder { /** * Create a new {@code BeanDefinitionBuilder} used to construct a {@link GenericBeanDefinition}. diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java index 161eae7e99..384866ffdd 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java @@ -888,4 +888,4 @@ class ConstructorResolver { } } } -} \ No newline at end of file +} diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index 9e681d0dd6..bffe7e764f 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -736,7 +736,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto //--------------------------------------------------------------------- public Object resolveDependency(DependencyDescriptor descriptor, String beanName, - Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { + Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { descriptor.initParameterNameDiscovery(getParameterNameDiscoverer()); if (descriptor.getDependencyType().equals(ObjectFactory.class)) { @@ -751,7 +751,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto } protected Object doResolveDependency(DependencyDescriptor descriptor, Class type, String beanName, - Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { + Set autowiredBeanNames, TypeConverter typeConverter) throws BeansException { Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor); if (value != null) { diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java b/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java index e46145f296..3413b457c0 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java @@ -47,7 +47,7 @@ import org.springframework.util.ClassUtils; * @see #setBeanWiringInfoResolver * @see ClassNameBeanWiringInfoResolver */ -public class BeanConfigurerSupport implements BeanFactoryAware, InitializingBean, DisposableBean { +public class BeanConfigurerSupport implements BeanFactoryAware, InitializingBean, DisposableBean { /** Logger available to subclasses */ protected final Log logger = LogFactory.getLog(getClass()); diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/xml/DelegatingEntityResolver.java b/spring-beans/src/main/java/org/springframework/beans/factory/xml/DelegatingEntityResolver.java index 07bfe7afa9..3bd9e1d85e 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/xml/DelegatingEntityResolver.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/xml/DelegatingEntityResolver.java @@ -92,7 +92,7 @@ public class DelegatingEntityResolver implements EntityResolver { @Override public String toString() { return "EntityResolver delegating " + XSD_SUFFIX + " to " + this.schemaResolver + - " and " + DTD_SUFFIX + " to " + this.dtdResolver; + " and " + DTD_SUFFIX + " to " + this.dtdResolver; } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandler.java b/spring-beans/src/main/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandler.java index a7ca4fbd54..4110ed0a22 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandler.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/xml/SimpleConstructorNamespaceHandler.java @@ -148,4 +148,4 @@ public class SimpleConstructorNamespaceHandler implements NamespaceHandler { } return false; } -} \ No newline at end of file +} diff --git a/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java b/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java index 84db22173a..ed8baa41df 100644 --- a/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java +++ b/spring-context-support/src/main/java/org/springframework/scheduling/quartz/SchedulerFactoryBean.java @@ -173,7 +173,7 @@ public class SchedulerFactoryBean extends SchedulerAccessor implements FactoryBe private DataSource nonTransactionalDataSource; - private Map schedulerContextMap; + private Map schedulerContextMap; private ApplicationContext applicationContext; diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java index 7c62a21af7..9e5162d6e3 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java @@ -470,4 +470,4 @@ public abstract class CacheAspectSupport implements InitializingBean { return this.caches; } } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java b/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java index 2ee38bb872..9bcce589ed 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java @@ -89,4 +89,4 @@ class ExpressionEvaluator { sb.append(expression); return sb.toString(); } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/LazyParamAwareEvaluationContext.java b/spring-context/src/main/java/org/springframework/cache/interceptor/LazyParamAwareEvaluationContext.java index c8c3e27905..7dc1289a41 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/LazyParamAwareEvaluationContext.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/LazyParamAwareEvaluationContext.java @@ -117,4 +117,4 @@ class LazyParamAwareEvaluationContext extends StandardEvaluationContext { sb.append(m.toString()); return sb.toString(); } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/context/annotation/AdviceMode.java b/spring-context/src/main/java/org/springframework/context/annotation/AdviceMode.java index 91b82e2825..5b741d6069 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/AdviceMode.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/AdviceMode.java @@ -29,4 +29,4 @@ package org.springframework.context.annotation; public enum AdviceMode { PROXY, ASPECTJ -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java index a105e147f7..93a71336a0 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/CommonAnnotationBeanPostProcessor.java @@ -725,4 +725,4 @@ public class CommonAnnotationBeanPostProcessor extends InitDestroyAnnotationBean } } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java b/spring-context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java index a4cf352a2b..effcec5df9 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/EnableAspectJAutoProxy.java @@ -110,4 +110,4 @@ public @interface EnableAspectJAutoProxy { */ boolean proxyTargetClass() default false; -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrar.java b/spring-context/src/main/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrar.java index da58779fd8..648a8e9211 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrar.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ImportBeanDefinitionRegistrar.java @@ -60,4 +60,4 @@ public interface ImportBeanDefinitionRegistrar { public void registerBeanDefinitions( AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry); -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java index c7ad16ac50..3a70e3c5f0 100644 --- a/spring-context/src/main/java/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java +++ b/spring-context/src/main/java/org/springframework/context/config/PropertyOverrideBeanDefinitionParser.java @@ -44,4 +44,4 @@ class PropertyOverrideBeanDefinitionParser extends AbstractPropertyLoadingBeanDe } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java b/spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java index eeca86a108..8d711989d9 100644 --- a/spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java +++ b/spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java @@ -135,7 +135,7 @@ public class ResourceBundleMessageSource extends AbstractMessageSource implement * @see #setBasename * @see java.util.ResourceBundle#getBundle(String) */ - public void setBasenames(String... basenames) { + public void setBasenames(String... basenames) { if (basenames != null) { this.basenames = new String[basenames.length]; for (int i = 0; i < basenames.length; i++) { diff --git a/spring-context/src/main/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptor.java b/spring-context/src/main/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptor.java index ce39ce9a6c..29de41bc3e 100644 --- a/spring-context/src/main/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptor.java +++ b/spring-context/src/main/java/org/springframework/ejb/access/SimpleRemoteSlsbInvokerInterceptor.java @@ -110,7 +110,7 @@ public class SimpleRemoteSlsbInvokerInterceptor extends AbstractRemoteSlsbInvoke } else if (targetEx instanceof CreateException) { throw RmiClientInterceptorUtils.convertRmiAccessException( - invocation.getMethod(), targetEx, "Could not create remote EJB [" + getJndiName() + "]"); + invocation.getMethod(), targetEx, "Could not create remote EJB [" + getJndiName() + "]"); } throw targetEx; } diff --git a/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java b/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java index 345131a5aa..7c5fceaed5 100644 --- a/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java +++ b/spring-context/src/main/java/org/springframework/format/support/FormattingConversionService.java @@ -195,7 +195,7 @@ public class FormattingConversionService extends GenericConversionService private Class annotationType; - private AnnotationFormatterFactory annotationFormatterFactory; + private AnnotationFormatterFactory annotationFormatterFactory; private Class fieldType; diff --git a/spring-context/src/main/java/org/springframework/format/support/FormattingConversionServiceFactoryBean.java b/spring-context/src/main/java/org/springframework/format/support/FormattingConversionServiceFactoryBean.java index 2dc19dda74..25d20688dd 100644 --- a/spring-context/src/main/java/org/springframework/format/support/FormattingConversionServiceFactoryBean.java +++ b/spring-context/src/main/java/org/springframework/format/support/FormattingConversionServiceFactoryBean.java @@ -116,7 +116,7 @@ public class FormattingConversionServiceFactoryBean /** * Indicate whether default formatters should be registered or not. *

By default, built-in formatters are registered. This flag can be used - * to turn that off and rely on explicitly registered formatters only. + * to turn that off and rely on explicitly registered formatters only. * @see #setFormatters(Set) * @see #setFormatterRegistrars(Set) */ diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaver.java b/spring-context/src/main/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaver.java index 86907d33dd..14d1beeb8a 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaver.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/ReflectiveLoadTimeWeaver.java @@ -135,4 +135,4 @@ public class ReflectiveLoadTimeWeaver implements LoadTimeWeaver { return new SimpleThrowawayClassLoader(this.classLoader); } } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/SimpleInstrumentableClassLoader.java b/spring-context/src/main/java/org/springframework/instrument/classloading/SimpleInstrumentableClassLoader.java index e35bd31fcb..4405dc3fdc 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/SimpleInstrumentableClassLoader.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/SimpleInstrumentableClassLoader.java @@ -29,7 +29,7 @@ import org.springframework.core.OverridingClassLoader; * @author Costin Leau * @since 2.0 */ -public class SimpleInstrumentableClassLoader extends OverridingClassLoader { +public class SimpleInstrumentableClassLoader extends OverridingClassLoader { private final WeavingTransformer weavingTransformer; diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCAdapter.java index a128608d84..8ae2481ea5 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCAdapter.java @@ -142,4 +142,4 @@ class JBossMCAdapter implements JBossClassLoaderAdapter { public ClassLoader getInstrumentableClassLoader() { return classLoader; } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCTranslatorAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCTranslatorAdapter.java index 8325e1b798..2ba16e0f8e 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCTranslatorAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossMCTranslatorAdapter.java @@ -79,4 +79,4 @@ class JBossMCTranslatorAdapter implements InvocationHandler { builder.append(this.transformer); return builder.toString(); } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossModulesAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossModulesAdapter.java index f9ba2b6204..03403036d0 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossModulesAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/jboss/JBossModulesAdapter.java @@ -68,4 +68,4 @@ class JBossModulesAdapter implements JBossClassLoaderAdapter { public ClassLoader getInstrumentableClassLoader() { return classLoader; } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassLoaderAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassLoaderAdapter.java index 723a947e1a..b1300d699b 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassLoaderAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassLoaderAdapter.java @@ -85,4 +85,4 @@ class OC4JClassLoaderAdapter { throw new IllegalStateException("Could not copy OC4J classloader", ex); } } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassPreprocessorAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassPreprocessorAdapter.java index dce5761898..5b56adf42c 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassPreprocessorAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JClassPreprocessorAdapter.java @@ -92,4 +92,4 @@ class OC4JClassPreprocessorAdapter implements InvocationHandler { builder.append(this.transformer); return builder.toString(); } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JLoadTimeWeaver.java b/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JLoadTimeWeaver.java index 1e71d0cdbb..54211b00d6 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JLoadTimeWeaver.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/oc4j/OC4JLoadTimeWeaver.java @@ -76,5 +76,4 @@ public class OC4JLoadTimeWeaver implements LoadTimeWeaver { public ClassLoader getThrowawayClassLoader() { return this.classLoader.getThrowawayClassLoader(); } - } diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java index 03b49e1326..e925e5bfc3 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassLoaderAdapter.java @@ -110,4 +110,4 @@ class WebLogicClassLoaderAdapter { throw new IllegalStateException("Could not construct WebLogic GenericClassLoader", ex); } } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.java b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.java index aede3544be..5967740664 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicClassPreProcessorAdapter.java @@ -87,4 +87,4 @@ class WebLogicClassPreProcessorAdapter implements InvocationHandler { builder.append(this.transformer); return builder.toString(); } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicLoadTimeWeaver.java b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicLoadTimeWeaver.java index 6662830c73..a4e38db93d 100644 --- a/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicLoadTimeWeaver.java +++ b/spring-context/src/main/java/org/springframework/instrument/classloading/weblogic/WebLogicLoadTimeWeaver.java @@ -69,4 +69,4 @@ public class WebLogicLoadTimeWeaver implements LoadTimeWeaver { public ClassLoader getThrowawayClassLoader() { return this.classLoader.getThrowawayClassLoader(); } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/jmx/export/SpringModelMBean.java b/spring-context/src/main/java/org/springframework/jmx/export/SpringModelMBean.java index f313e65fbc..95f1d07b5f 100644 --- a/spring-context/src/main/java/org/springframework/jmx/export/SpringModelMBean.java +++ b/spring-context/src/main/java/org/springframework/jmx/export/SpringModelMBean.java @@ -58,7 +58,7 @@ public class SpringModelMBean extends RequiredModelMBean { * Construct a new SpringModelMBean instance with the given {@link ModelMBeanInfo}. * @see javax.management.modelmbean.RequiredModelMBean#RequiredModelMBean(ModelMBeanInfo) */ - public SpringModelMBean(ModelMBeanInfo mbi) throws MBeanException, RuntimeOperationsException { + public SpringModelMBean(ModelMBeanInfo mbi) throws MBeanException, RuntimeOperationsException { super(mbi); } diff --git a/spring-context/src/main/java/org/springframework/remoting/rmi/RmiClientInterceptor.java b/spring-context/src/main/java/org/springframework/remoting/rmi/RmiClientInterceptor.java index ba9d8775d9..fb8e903275 100644 --- a/spring-context/src/main/java/org/springframework/remoting/rmi/RmiClientInterceptor.java +++ b/spring-context/src/main/java/org/springframework/remoting/rmi/RmiClientInterceptor.java @@ -345,7 +345,7 @@ public class RmiClientInterceptor extends RemoteInvocationBasedAccessor } catch (RemoteException ex) { throw RmiClientInterceptorUtils.convertRmiAccessException( - invocation.getMethod(), ex, isConnectFailure(ex), getServiceUrl()); + invocation.getMethod(), ex, isConnectFailure(ex), getServiceUrl()); } catch (InvocationTargetException ex) { Throwable exToThrow = ex.getTargetException(); @@ -389,7 +389,7 @@ public class RmiClientInterceptor extends RemoteInvocationBasedAccessor * @see org.springframework.remoting.support.RemoteInvocation */ protected Object doInvoke(MethodInvocation methodInvocation, RmiInvocationHandler invocationHandler) - throws RemoteException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { + throws RemoteException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (AopUtils.isToStringMethod(methodInvocation.getMethod())) { return "RMI invoker proxy for service URL [" + getServiceUrl() + "]"; diff --git a/spring-context/src/main/java/org/springframework/remoting/rmi/RmiServiceExporter.java b/spring-context/src/main/java/org/springframework/remoting/rmi/RmiServiceExporter.java index dcd5f91f85..81bf07e825 100644 --- a/spring-context/src/main/java/org/springframework/remoting/rmi/RmiServiceExporter.java +++ b/spring-context/src/main/java/org/springframework/remoting/rmi/RmiServiceExporter.java @@ -456,4 +456,4 @@ public class RmiServiceExporter extends RmiBasedExporter implements Initializing } } } -} \ No newline at end of file +} diff --git a/spring-context/src/main/java/org/springframework/scripting/jruby/JRubyScriptUtils.java b/spring-context/src/main/java/org/springframework/scripting/jruby/JRubyScriptUtils.java index 97b9a3bc43..3d019c22fe 100644 --- a/spring-context/src/main/java/org/springframework/scripting/jruby/JRubyScriptUtils.java +++ b/spring-context/src/main/java/org/springframework/scripting/jruby/JRubyScriptUtils.java @@ -81,7 +81,7 @@ public abstract class JRubyScriptUtils { Node scriptRootNode = ruby.parseEval(scriptSource, "", null, 0); // keep using the deprecated runNormally variant for JRuby 1.1/1.2 compatibility... - IRubyObject rubyObject = ruby.runNormally(scriptRootNode, false); + IRubyObject rubyObject = ruby.runNormally(scriptRootNode, false); if (rubyObject instanceof RubyNil) { String className = findClassName(scriptRootNode); diff --git a/spring-context/src/main/java/org/springframework/scripting/support/ResourceScriptSource.java b/spring-context/src/main/java/org/springframework/scripting/support/ResourceScriptSource.java index 23be717eac..c0de42493f 100644 --- a/spring-context/src/main/java/org/springframework/scripting/support/ResourceScriptSource.java +++ b/spring-context/src/main/java/org/springframework/scripting/support/ResourceScriptSource.java @@ -126,4 +126,4 @@ public class ResourceScriptSource implements ScriptSource { public String toString() { return this.resource.toString(); } -} \ No newline at end of file +} diff --git a/spring-core/src/main/java/org/springframework/core/NamedInheritableThreadLocal.java b/spring-core/src/main/java/org/springframework/core/NamedInheritableThreadLocal.java index bb7cfb8937..3d30f24615 100644 --- a/spring-core/src/main/java/org/springframework/core/NamedInheritableThreadLocal.java +++ b/spring-core/src/main/java/org/springframework/core/NamedInheritableThreadLocal.java @@ -45,4 +45,4 @@ public class NamedInheritableThreadLocal extends InheritableThreadLocal { return this.name; } -} \ No newline at end of file +} diff --git a/spring-core/src/main/java/org/springframework/core/env/MapPropertySource.java b/spring-core/src/main/java/org/springframework/core/env/MapPropertySource.java index 54f5bad4c5..b8b62706c1 100644 --- a/spring-core/src/main/java/org/springframework/core/env/MapPropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/env/MapPropertySource.java @@ -41,4 +41,4 @@ public class MapPropertySource extends EnumerablePropertySource implements Iterator { public void remove() { throw new UnsupportedOperationException("Remove is not supported"); } -} \ No newline at end of file +} diff --git a/spring-expression/src/main/java/org/springframework/expression/MethodFilter.java b/spring-expression/src/main/java/org/springframework/expression/MethodFilter.java index e273125d34..50992dd798 100644 --- a/spring-expression/src/main/java/org/springframework/expression/MethodFilter.java +++ b/spring-expression/src/main/java/org/springframework/expression/MethodFilter.java @@ -43,4 +43,4 @@ public interface MethodFilter { */ List filter(List methods); -} \ No newline at end of file +} diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java index 7ec464075d..b632adec5e 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/CompoundExpression.java @@ -36,6 +36,7 @@ public class CompoundExpression extends SpelNodeImpl { } } + @Override protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { if (getChildCount()==1) { diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java index ffc5819367..226063cf7c 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Projection.java @@ -70,7 +70,7 @@ public class Projection extends SpelNodeImpl { if (operand instanceof Map) { Map mapData = (Map) operand; List result = new ArrayList(); - for (Map.Entry entry : mapData.entrySet()) { + for (Map.Entry entry : mapData.entrySet()) { try { state.pushActiveContextObject(new TypedValue(entry)); result.add(this.children[0].getValueInternal(state).getValue()); diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java index e532aa9ebc..7489c6ba69 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java @@ -73,9 +73,9 @@ public class Selection extends SpelNodeImpl { if (operand instanceof Map) { Map mapdata = (Map) operand; // TODO don't lose generic info for the new map - Map result = new HashMap(); + Map result = new HashMap(); Object lastKey = null; - for (Map.Entry entry : mapdata.entrySet()) { + for (Map.Entry entry : mapdata.entrySet()) { try { TypedValue kvpair = new TypedValue(entry); state.pushActiveContextObject(kvpair); @@ -101,7 +101,7 @@ public class Selection extends SpelNodeImpl { return new ValueRef.TypedValueHolderValueRef(new TypedValue(null),this); } if (variant == LAST) { - Map resultMap = new HashMap(); + Map resultMap = new HashMap(); Object lastValue = result.get(lastKey); resultMap.put(lastKey,lastValue); return new ValueRef.TypedValueHolderValueRef(new TypedValue(resultMap),this); diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java index 109de5fdc1..e1ee6f90b4 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/SpelNodeImpl.java @@ -149,5 +149,4 @@ public abstract class SpelNodeImpl implements SpelNode { protected ValueRef getValueRef(ExpressionState state) throws EvaluationException { throw new SpelEvaluationException(pos,SpelMessage.NOT_ASSIGNABLE,toStringAST()); } - } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/Token.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/Token.java index 3f8593c5fe..aaba8236a7 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/Token.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/Token.java @@ -84,4 +84,4 @@ class Token { public Token asBetweenToken() { return new Token(TokenKind.BETWEEN,startpos,endpos); } -} \ No newline at end of file +} diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/TokenKind.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/TokenKind.java index ffa6ffa88c..cd1db13d6d 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/TokenKind.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/TokenKind.java @@ -56,4 +56,4 @@ enum TokenKind { public int getLength() { return tokenChars.length; } -} \ No newline at end of file +} diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallParameterMetaData.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallParameterMetaData.java index 4c1393640d..55e747b9cd 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallParameterMetaData.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallParameterMetaData.java @@ -75,4 +75,4 @@ public class CallParameterMetaData { public boolean isNullable() { return nullable; } -} \ No newline at end of file +} diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/DerbyTableMetaDataProvider.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/DerbyTableMetaDataProvider.java index dc3e213128..afabd9bcf9 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/DerbyTableMetaDataProvider.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/DerbyTableMetaDataProvider.java @@ -53,4 +53,4 @@ public class DerbyTableMetaDataProvider extends GenericTableMetaDataProvider { } return derbysAnswer; } -} \ No newline at end of file +} diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java index 298cf37db0..07670934c7 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/embedded/HsqlEmbeddedDatabaseConfigurer.java @@ -59,4 +59,4 @@ final class HsqlEmbeddedDatabaseConfigurer extends AbstractEmbeddedDatabaseConfi properties.setPassword(""); } -} \ No newline at end of file +} diff --git a/spring-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java index fab56e5e5a..0f23da93c4 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java @@ -34,4 +34,4 @@ public interface GenericUnmarshaller extends Unmarshaller { */ boolean supports(Type genericType); -} \ No newline at end of file +} diff --git a/spring-struts/src/main/java/org/springframework/web/struts/package-info.java b/spring-struts/src/main/java/org/springframework/web/struts/package-info.java index b299f31263..33fe62fa52 100644 --- a/spring-struts/src/main/java/org/springframework/web/struts/package-info.java +++ b/spring-struts/src/main/java/org/springframework/web/struts/package-info.java @@ -25,4 +25,4 @@ * */ @Deprecated -package org.springframework.web.struts; \ No newline at end of file +package org.springframework.web.struts; diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java index 8f36c3a764..406c263e9f 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockClientDataRequest.java @@ -125,4 +125,4 @@ public class MockClientDataRequest extends MockPortletRequest implements ClientD return this.method; } -} \ No newline at end of file +} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java index 0dc7efaba8..41e72da9a9 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEvent.java @@ -85,4 +85,4 @@ public class MockEvent implements Event { return this.value; } -} \ No newline at end of file +} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java index 2406f18d01..a2850e3c1f 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockEventRequest.java @@ -85,4 +85,4 @@ public class MockEventRequest extends MockPortletRequest implements EventRequest return this.method; } -} \ No newline at end of file +} diff --git a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java index 6853658447..95df6ed016 100644 --- a/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java +++ b/spring-test/src/main/java/org/springframework/mock/web/portlet/MockStateAwareResponse.java @@ -151,4 +151,4 @@ public class MockStateAwareResponse extends MockPortletResponse implements State return this.events.get(new QName(name)); } -} \ No newline at end of file +} diff --git a/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java b/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java index d138484c8a..c67f0c72d7 100644 --- a/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java +++ b/spring-test/src/main/java/org/springframework/test/context/TestContextManager.java @@ -448,4 +448,4 @@ public class TestContextManager { } } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/http/client/CommonsClientHttpResponse.java b/spring-web/src/main/java/org/springframework/http/client/CommonsClientHttpResponse.java index 7cc8cec6e9..0e3f949da3 100644 --- a/spring-web/src/main/java/org/springframework/http/client/CommonsClientHttpResponse.java +++ b/spring-web/src/main/java/org/springframework/http/client/CommonsClientHttpResponse.java @@ -74,4 +74,4 @@ final class CommonsClientHttpResponse extends AbstractClientHttpResponse { this.httpMethod.releaseConnection(); } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverter.java index 7add4751ba..08091984d9 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/feed/RssChannelHttpMessageConverter.java @@ -43,5 +43,4 @@ public class RssChannelHttpMessageConverter extends AbstractWireFeedHttpMessageC return Channel.class.isAssignableFrom(clazz); } - -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseBody.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseBody.java index fe7fac62cd..69ec801103 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseBody.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/ResponseBody.java @@ -36,4 +36,4 @@ import java.lang.annotation.Target; @Documented public @interface ResponseBody { -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/bind/support/WebDataBinderFactory.java b/spring-web/src/main/java/org/springframework/web/bind/support/WebDataBinderFactory.java index 03f13d86ff..e37776a3c8 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/support/WebDataBinderFactory.java +++ b/spring-web/src/main/java/org/springframework/web/bind/support/WebDataBinderFactory.java @@ -37,4 +37,4 @@ public interface WebDataBinderFactory { */ WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception; -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/HandlerMethodSelector.java b/spring-web/src/main/java/org/springframework/web/method/HandlerMethodSelector.java index 4d93eff7f2..fc43fc5f8b 100644 --- a/spring-web/src/main/java/org/springframework/web/method/HandlerMethodSelector.java +++ b/spring-web/src/main/java/org/springframework/web/method/HandlerMethodSelector.java @@ -69,4 +69,4 @@ public abstract class HandlerMethodSelector { return handlerMethods; } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractCookieValueMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractCookieValueMethodArgumentResolver.java index 07c44b32a8..cd14b2e3ae 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractCookieValueMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractCookieValueMethodArgumentResolver.java @@ -71,4 +71,4 @@ public abstract class AbstractCookieValueMethodArgumentResolver extends Abstract super(annotation.value(), annotation.required(), annotation.defaultValue()); } } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java index 92a2aa88d1..d93a6d43a3 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/ExpressionValueMethodArgumentResolver.java @@ -76,4 +76,4 @@ public class ExpressionValueMethodArgumentResolver extends AbstractNamedValueMet super("@Value", false, annotation.value()); } } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/ModelFactory.java b/spring-web/src/main/java/org/springframework/web/method/annotation/ModelFactory.java index ee5672cfa4..7366edef12 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/ModelFactory.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/ModelFactory.java @@ -243,4 +243,4 @@ public final class ModelFactory { !(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass())); } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolver.java index e7b46bdb6a..7e4fdb4036 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestHeaderMethodArgumentResolver.java @@ -87,4 +87,4 @@ public class RequestHeaderMethodArgumentResolver extends AbstractNamedValueMetho super(annotation.value(), annotation.required(), annotation.defaultValue()); } } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java index 3f351595ec..2a532f4bed 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolver.java @@ -212,4 +212,4 @@ public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethod super(annotation.value(), annotation.required(), annotation.defaultValue()); } } -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolver.java index e2a7b7d798..b3c3442791 100644 --- a/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolver.java @@ -62,4 +62,4 @@ public interface HandlerMethodArgumentResolver { NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception; -} \ No newline at end of file +} diff --git a/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandler.java b/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandler.java index d97fe876d1..ae1afc1155 100644 --- a/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandler.java +++ b/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodReturnValueHandler.java @@ -58,4 +58,4 @@ public interface HandlerMethodReturnValueHandler { ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception; -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java index 6b6f5d1acf..7e85dcf956 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DefaultServletHandlerConfigurer.java @@ -95,4 +95,4 @@ public class DefaultServletHandlerConfigurer { return handlerMapping; } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java index 96fdcaf4e0..65ef9be6c5 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java @@ -108,4 +108,4 @@ public class ResourceHandlerRegistry { return handlerMapping; } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java index fcc284989f..adfd5cf163 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java @@ -74,4 +74,4 @@ public class ViewControllerRegistry { return handlerMapping; } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java index ac63b1cbca..6f6c82733c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java @@ -128,4 +128,4 @@ public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer { public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/AbstractMediaTypeExpression.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/AbstractMediaTypeExpression.java index 15aee22ec2..bc65b27de2 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/AbstractMediaTypeExpression.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/AbstractMediaTypeExpression.java @@ -107,4 +107,4 @@ abstract class AbstractMediaTypeExpression implements Comparable { boolean isNegated(); -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolver.java index 52af8e427a..514df91002 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMapMethodArgumentResolver.java @@ -67,4 +67,4 @@ public class PathVariableMapMethodArgumentResolver implements HandlerMethodArgum } } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java index d93b7746a7..7b960f001c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/PathVariableMethodArgumentResolver.java @@ -119,4 +119,4 @@ public class PathVariableMethodArgumentResolver extends AbstractNamedValueMethod super(annotation.value(), true, ValueConstants.DEFAULT_NONE); } } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java index d79a9ef5db..848e912703 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java @@ -879,4 +879,4 @@ public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter i } }; -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java index 9b320cedb9..a7473a60f1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java @@ -190,4 +190,4 @@ public class RequestResponseBodyMethodProcessor extends AbstractMessageConverter } } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolver.java index 8d3d77acd9..48080aa16a 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletCookieValueMethodArgumentResolver.java @@ -60,4 +60,4 @@ public class ServletCookieValueMethodArgumentResolver extends AbstractCookieValu return null; } } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessor.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessor.java index 3b54676ed3..3cfd087e33 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessor.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessor.java @@ -153,4 +153,4 @@ public class ServletModelAttributeMethodProcessor extends ModelAttributeMethodPr servletBinder.bind(servletRequest); } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletWebArgumentResolverAdapter.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletWebArgumentResolverAdapter.java index 5513dddae0..d716a9bc48 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletWebArgumentResolverAdapter.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletWebArgumentResolverAdapter.java @@ -51,4 +51,4 @@ public class ServletWebArgumentResolverAdapter extends AbstractWebArgumentResolv } return null; } -} \ No newline at end of file +} diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsCsvView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsCsvView.java index f8297f3b14..b93a28269b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsCsvView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/jasperreports/JasperReportsCsvView.java @@ -43,4 +43,4 @@ public class JasperReportsCsvView extends AbstractJasperReportsSingleFormatView return true; } -} \ No newline at end of file +} From 8c2ace33cbfe35f9f132c7ec8ca7d3c3beb59f7a Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 24 Jan 2013 17:16:29 -0800 Subject: [PATCH 176/311] Support 'unless' expression for cache veto Allow @Cachable, @CachePut and equivalent XML configuration to provide a SpEL expression that can be used to veto putting an item into the cache. Unlike 'condition' the 'unless' parameter is evaluated after the method has been called and can therefore reference the #result. For example: @Cacheable(value="book", condition="#name.length < 32", unless="#result.hardback") This commit also allows #result to be referenced from @CacheEvict expressions as long as 'beforeInvocation' is false. Issue: SPR-8871 --- .../AnnotatedClassCacheableService.java | 7 +- .../cache/config/CacheableService.java | 5 +- .../cache/config/DefaultCacheableService.java | 7 ++ .../cache/annotation/CachePut.java | 12 ++- .../cache/annotation/Cacheable.java | 12 ++- .../SpringCacheAnnotationParser.java | 5 +- .../cache/config/CacheAdviceParser.java | 42 +++++----- .../cache/interceptor/CacheAspectSupport.java | 81 +++++++++++++------ .../interceptor/CacheEvictOperation.java | 3 +- .../cache/interceptor/CacheOperation.java | 8 +- .../cache/interceptor/CachePutOperation.java | 22 ++++- .../cache/interceptor/CacheableOperation.java | 22 ++++- .../interceptor/ExpressionEvaluator.java | 79 +++++++++++++----- .../cache/config/spring-cache-3.2.xsd | 48 ++++++++--- .../cache/config/AbstractAnnotationTests.java | 26 +++++- .../AnnotatedClassCacheableService.java | 11 ++- .../cache/config/CacheableService.java | 7 +- .../cache/config/DefaultCacheableService.java | 11 ++- .../interceptor/ExpressionEvalutatorTest.java | 54 ++++++++++++- .../cache/config/cache-advice.xml | 14 ++-- src/dist/changelog.txt | 1 + src/reference/docbook/cache.xml | 14 ++++ 22 files changed, 385 insertions(+), 106 deletions(-) diff --git a/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java index 5e64cb7fcc..b810805179 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java +++ b/spring-aspects/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import org.springframework.cache.annotation.Caching; /** * @author Costin Leau + * @author Phillip Webb */ @Cacheable("default") public class AnnotatedClassCacheableService implements CacheableService { @@ -40,6 +41,10 @@ public class AnnotatedClassCacheableService implements CacheableService return null; } + public Object unless(int arg) { + return arg; + } + @CacheEvict("default") public void invalidate(Object arg1) { } diff --git a/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java index 09ad7df998..98c1da1e03 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java +++ b/spring-aspects/src/test/java/org/springframework/cache/config/CacheableService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ package org.springframework.cache.config; * Basic service interface. * * @author Costin Leau + * @author Phillip Webb */ public interface CacheableService { @@ -39,6 +40,8 @@ public interface CacheableService { T conditional(int field); + T unless(int arg); + T key(Object arg1, Object arg2); T name(Object arg1); diff --git a/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java b/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java index 6d83d91c02..d29d43894e 100644 --- a/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java +++ b/spring-aspects/src/test/java/org/springframework/cache/config/DefaultCacheableService.java @@ -27,6 +27,7 @@ import org.springframework.cache.annotation.Caching; * Simple cacheable service * * @author Costin Leau + * @author Phillip Webb */ public class DefaultCacheableService implements CacheableService { @@ -78,6 +79,12 @@ public class DefaultCacheableService implements CacheableService { return counter.getAndIncrement(); } + @Override + @Cacheable(value = "default", unless = "#result > 10") + public Long unless(int arg) { + return (long) arg; + } + @Override @Cacheable(value = "default", key = "#p0") public Long key(Object arg1, Object arg2) { diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/CachePut.java b/spring-context/src/main/java/org/springframework/cache/annotation/CachePut.java index 0cc7f883f1..3ab2f52b0a 100644 --- a/spring-context/src/main/java/org/springframework/cache/annotation/CachePut.java +++ b/spring-context/src/main/java/org/springframework/cache/annotation/CachePut.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,6 +32,7 @@ import org.springframework.cache.Cache; * always causes the method to be invoked and its result to be placed into the cache. * * @author Costin Leau + * @author Phillip Webb * @since 3.1 */ @Target({ ElementType.METHOD, ElementType.TYPE }) @@ -58,4 +59,13 @@ public @interface CachePut { *

Default is "", meaning the method result is always cached. */ String condition() default ""; + + /** + * Spring Expression Language (SpEL) attribute used to veto the cache update. + *

Unlike {@link #condition()}, this expression is evaluated after the method + * has been called and can therefore refer to the {@code result}. Default is "", + * meaning that caching is never vetoed. + * @since 3.2 + */ + String unless() default ""; } diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java b/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java index 716b840ad0..1ab8df5762 100644 --- a/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java +++ b/spring-context/src/main/java/org/springframework/cache/annotation/Cacheable.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import java.lang.annotation.Target; * returned instance is used as the cache value. * * @author Costin Leau + * @author Phillip Webb * @since 3.1 */ @Target({ElementType.METHOD, ElementType.TYPE}) @@ -56,4 +57,13 @@ public @interface Cacheable { *

Default is "", meaning the method is always cached. */ String condition() default ""; + + /** + * Spring Expression Language (SpEL) attribute used to veto method caching. + *

Unlike {@link #condition()}, this expression is evaluated after the method + * has been called and can therefore refer to the {@code result}. Default is "", + * meaning that caching is never vetoed. + * @since 3.2 + */ + String unless() default ""; } diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/SpringCacheAnnotationParser.java b/spring-context/src/main/java/org/springframework/cache/annotation/SpringCacheAnnotationParser.java index 9114dfc633..d8c7575ce7 100644 --- a/spring-context/src/main/java/org/springframework/cache/annotation/SpringCacheAnnotationParser.java +++ b/spring-context/src/main/java/org/springframework/cache/annotation/SpringCacheAnnotationParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +35,7 @@ import org.springframework.util.ObjectUtils; * @author Costin Leau * @author Juergen Hoeller * @author Chris Beams + * @author Phillip Webb * @since 3.1 */ @SuppressWarnings("serial") @@ -82,6 +83,7 @@ public class SpringCacheAnnotationParser implements CacheAnnotationParser, Seria CacheableOperation cuo = new CacheableOperation(); cuo.setCacheNames(caching.value()); cuo.setCondition(caching.condition()); + cuo.setUnless(caching.unless()); cuo.setKey(caching.key()); cuo.setName(ae.toString()); return cuo; @@ -102,6 +104,7 @@ public class SpringCacheAnnotationParser implements CacheAnnotationParser, Seria CachePutOperation cuo = new CachePutOperation(); cuo.setCacheNames(caching.value()); cuo.setCondition(caching.condition()); + cuo.setUnless(caching.unless()); cuo.setKey(caching.key()); cuo.setName(ae.toString()); return cuo; diff --git a/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java b/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java index a1206c576f..5092f474c7 100644 --- a/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java +++ b/spring-context/src/main/java/org/springframework/cache/config/CacheAdviceParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,6 +44,7 @@ import org.w3c.dom.Element; * BeanDefinitionParser} for the {@code } tag. * * @author Costin Leau + * @author Phillip Webb */ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { @@ -54,7 +55,9 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { */ private static class Props { - private String key, condition, method; + private String key; + private String condition; + private String method; private String[] caches = null; Props(Element root) { @@ -70,13 +73,9 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { T merge(Element element, ReaderContext readerCtx, T op) { String cache = element.getAttribute("cache"); - String k = element.getAttribute("key"); - String c = element.getAttribute("condition"); - - String[] localCaches = caches; - String localKey = key, localCondition = condition; // sanity check + String[] localCaches = caches; if (StringUtils.hasText(cache)) { localCaches = StringUtils.commaDelimitedListToStringArray(cache.trim()); } else { @@ -84,17 +83,10 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { readerCtx.error("No cache specified specified for " + element.getNodeName(), element); } } - - if (StringUtils.hasText(k)) { - localKey = k.trim(); - } - - if (StringUtils.hasText(c)) { - localCondition = c.trim(); - } op.setCacheNames(localCaches); - op.setKey(localKey); - op.setCondition(localCondition); + + op.setKey(getAttributeValue(element, "key", this.key)); + op.setCondition(getAttributeValue(element, "condition", this.condition)); return op; } @@ -165,7 +157,8 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { String name = prop.merge(opElement, parserContext.getReaderContext()); TypedStringValue nameHolder = new TypedStringValue(name); nameHolder.setSource(parserContext.extractSource(opElement)); - CacheOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CacheableOperation()); + CacheableOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CacheableOperation()); + op.setUnless(getAttributeValue(opElement, "unless", "")); Collection col = cacheOpMap.get(nameHolder); if (col == null) { @@ -207,7 +200,8 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { String name = prop.merge(opElement, parserContext.getReaderContext()); TypedStringValue nameHolder = new TypedStringValue(name); nameHolder.setSource(parserContext.extractSource(opElement)); - CacheOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CachePutOperation()); + CachePutOperation op = prop.merge(opElement, parserContext.getReaderContext(), new CachePutOperation()); + op.setUnless(getAttributeValue(opElement, "unless", "")); Collection col = cacheOpMap.get(nameHolder); if (col == null) { @@ -222,4 +216,14 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser { attributeSourceDefinition.getPropertyValues().add("nameMap", cacheOpMap); return attributeSourceDefinition; } + + + private static String getAttributeValue(Element element, String attributeName, String defaultValue) { + String attribute = element.getAttribute(attributeName); + if(StringUtils.hasText(attribute)) { + return attribute.trim(); + } + return defaultValue; + } + } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java index 9e5162d6e3..8e0b36889d 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,6 +56,7 @@ import org.springframework.util.StringUtils; * @author Costin Leau * @author Juergen Hoeller * @author Chris Beams + * @author Phillip Webb * @since 3.1 */ public abstract class CacheAspectSupport implements InitializingBean { @@ -212,7 +213,7 @@ public abstract class CacheAspectSupport implements InitializingBean { retVal = invoker.invoke(); - inspectAfterCacheEvicts(ops.get(EVICT)); + inspectAfterCacheEvicts(ops.get(EVICT), retVal); if (!updates.isEmpty()) { update(updates, retVal); @@ -225,14 +226,16 @@ public abstract class CacheAspectSupport implements InitializingBean { } private void inspectBeforeCacheEvicts(Collection evictions) { - inspectCacheEvicts(evictions, true); + inspectCacheEvicts(evictions, true, ExpressionEvaluator.NO_RESULT); } - private void inspectAfterCacheEvicts(Collection evictions) { - inspectCacheEvicts(evictions, false); + private void inspectAfterCacheEvicts(Collection evictions, + Object result) { + inspectCacheEvicts(evictions, false, result); } - private void inspectCacheEvicts(Collection evictions, boolean beforeInvocation) { + private void inspectCacheEvicts(Collection evictions, + boolean beforeInvocation, Object result) { if (!evictions.isEmpty()) { @@ -242,7 +245,7 @@ public abstract class CacheAspectSupport implements InitializingBean { CacheEvictOperation evictOp = (CacheEvictOperation) context.operation; if (beforeInvocation == evictOp.isBeforeInvocation()) { - if (context.isConditionPassing()) { + if (context.isConditionPassing(result)) { // for each cache // lazy key initialization Object key = null; @@ -278,7 +281,7 @@ public abstract class CacheAspectSupport implements InitializingBean { private CacheStatus inspectCacheables(Collection cacheables) { Map cUpdates = new LinkedHashMap(cacheables.size()); - boolean updateRequire = false; + boolean updateRequired = false; Object retVal = null; if (!cacheables.isEmpty()) { @@ -305,7 +308,7 @@ public abstract class CacheAspectSupport implements InitializingBean { boolean localCacheHit = false; // check whether the cache needs to be inspected or not (the method will be invoked anyway) - if (!updateRequire) { + if (!updateRequired) { for (Cache cache : context.getCaches()) { Cache.ValueWrapper wrapper = cache.get(key); if (wrapper != null) { @@ -317,7 +320,7 @@ public abstract class CacheAspectSupport implements InitializingBean { } if (!localCacheHit) { - updateRequire = true; + updateRequired = true; } } else { @@ -329,7 +332,7 @@ public abstract class CacheAspectSupport implements InitializingBean { // return a status only if at least on cacheable matched if (atLeastOnePassed) { - return new CacheStatus(cUpdates, updateRequire, retVal); + return new CacheStatus(cUpdates, updateRequired, retVal); } } @@ -386,8 +389,11 @@ public abstract class CacheAspectSupport implements InitializingBean { private void update(Map updates, Object retVal) { for (Map.Entry entry : updates.entrySet()) { - for (Cache cache : entry.getKey().getCaches()) { - cache.put(entry.getValue(), retVal); + CacheOperationContext operationContext = entry.getKey(); + if(operationContext.canPutToCache(retVal)) { + for (Cache cache : operationContext.getCaches()) { + cache.put(entry.getValue(), retVal); + } } } } @@ -427,30 +433,49 @@ public abstract class CacheAspectSupport implements InitializingBean { private final CacheOperation operation; - private final Collection caches; - - private final Object target; - private final Method method; private final Object[] args; - // context passed around to avoid multiple creations - private final EvaluationContext evalContext; + private final Object target; + + private final Class targetClass; + + private final Collection caches; public CacheOperationContext(CacheOperation operation, Method method, Object[] args, Object target, Class targetClass) { this.operation = operation; - this.caches = CacheAspectSupport.this.getCaches(operation); - this.target = target; this.method = method; this.args = args; - - this.evalContext = evaluator.createEvaluationContext(caches, method, args, target, targetClass); + this.target = target; + this.targetClass = targetClass; + this.caches = CacheAspectSupport.this.getCaches(operation); } protected boolean isConditionPassing() { + return isConditionPassing(ExpressionEvaluator.NO_RESULT); + } + + protected boolean isConditionPassing(Object result) { if (StringUtils.hasText(this.operation.getCondition())) { - return evaluator.condition(this.operation.getCondition(), this.method, this.evalContext); + EvaluationContext evaluationContext = createEvaluationContext(result); + return evaluator.condition(this.operation.getCondition(), this.method, + evaluationContext); + } + return true; + } + + protected boolean canPutToCache(Object value) { + String unless = ""; + if (this.operation instanceof CacheableOperation) { + unless = ((CacheableOperation) this.operation).getUnless(); + } + else if (this.operation instanceof CachePutOperation) { + unless = ((CachePutOperation) this.operation).getUnless(); + } + if(StringUtils.hasText(unless)) { + EvaluationContext evaluationContext = createEvaluationContext(value); + return !evaluator.unless(unless, this.method, evaluationContext); } return true; } @@ -461,11 +486,17 @@ public abstract class CacheAspectSupport implements InitializingBean { */ protected Object generateKey() { if (StringUtils.hasText(this.operation.getKey())) { - return evaluator.key(this.operation.getKey(), this.method, this.evalContext); + EvaluationContext evaluationContext = createEvaluationContext(ExpressionEvaluator.NO_RESULT); + return evaluator.key(this.operation.getKey(), this.method, evaluationContext); } return keyGenerator.generate(this.target, this.method, this.args); } + private EvaluationContext createEvaluationContext(Object result) { + return evaluator.createEvaluationContext(this.caches, this.method, this.args, + this.target, this.targetClass, result); + } + protected Collection getCaches() { return this.caches; } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java index 62186d8966..f671c84f75 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheEvictOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ public class CacheEvictOperation extends CacheOperation { private boolean cacheWide = false; private boolean beforeInvocation = false; + public void setCacheWide(boolean cacheWide) { this.cacheWide = cacheWide; } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java index cd8a40ceb2..46d84590e8 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -119,10 +119,10 @@ public abstract class CacheOperation { result.append(this.name); result.append("] caches="); result.append(this.cacheNames); - result.append(" | condition='"); - result.append(this.condition); - result.append("' | key='"); + result.append(" | key='"); result.append(this.key); + result.append("' | condition='"); + result.append(this.condition); result.append("'"); return result; } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CachePutOperation.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CachePutOperation.java index edb84ba156..e6a61b0adf 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CachePutOperation.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CachePutOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,28 @@ package org.springframework.cache.interceptor; * Class describing a cache 'put' operation. * * @author Costin Leau + * @author Phillip Webb * @since 3.1 */ public class CachePutOperation extends CacheOperation { + private String unless; + + + public String getUnless() { + return unless; + } + + public void setUnless(String unless) { + this.unless = unless; + } + + @Override + protected StringBuilder getOperationDescription() { + StringBuilder sb = super.getOperationDescription(); + sb.append(" | unless='"); + sb.append(this.unless); + sb.append("'"); + return sb; + } } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheableOperation.java b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheableOperation.java index 23c0b20e2c..f9375a9a54 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/CacheableOperation.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/CacheableOperation.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,28 @@ package org.springframework.cache.interceptor; * Class describing a cache 'cacheable' operation. * * @author Costin Leau + * @author Phillip Webb * @since 3.1 */ public class CacheableOperation extends CacheOperation { + private String unless; + + + public String getUnless() { + return unless; + } + + public void setUnless(String unless) { + this.unless = unless; + } + + @Override + protected StringBuilder getOperationDescription() { + StringBuilder sb = super.getOperationDescription(); + sb.append(" | unless='"); + sb.append(this.unless); + sb.append("'"); + return sb; + } } diff --git a/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java b/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java index 9bcce589ed..ba109397a2 100644 --- a/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java +++ b/spring-context/src/main/java/org/springframework/cache/interceptor/ExpressionEvaluator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,49 +35,84 @@ import org.springframework.expression.spel.standard.SpelExpressionParser; *

Performs internal caching for performance reasons. * * @author Costin Leau + * @author Phillip Webb * @since 3.1 */ class ExpressionEvaluator { + public static final Object NO_RESULT = new Object(); + private final SpelExpressionParser parser = new SpelExpressionParser(); // shared param discoverer since it caches data internally private final ParameterNameDiscoverer paramNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); + private final Map keyCache = new ConcurrentHashMap(64); + private final Map conditionCache = new ConcurrentHashMap(64); - private final Map keyCache = new ConcurrentHashMap(64); + private final Map unlessCache = new ConcurrentHashMap(64); private final Map targetMethodCache = new ConcurrentHashMap(64); - public EvaluationContext createEvaluationContext( - Collection caches, Method method, Object[] args, Object target, Class targetClass) { - - CacheExpressionRootObject rootObject = - new CacheExpressionRootObject(caches, method, args, target, targetClass); - return new LazyParamAwareEvaluationContext(rootObject, - this.paramNameDiscoverer, method, args, targetClass, this.targetMethodCache); + /** + * Create an {@link EvaluationContext} without a return value. + * @see #createEvaluationContext(Collection, Method, Object[], Object, Class, Object) + */ + public EvaluationContext createEvaluationContext(Collection caches, + Method method, Object[] args, Object target, Class targetClass) { + return createEvaluationContext(caches, method, args, target, targetClass, + NO_RESULT); } - public boolean condition(String conditionExpression, Method method, EvaluationContext evalContext) { - String key = toString(method, conditionExpression); - Expression condExp = this.conditionCache.get(key); - if (condExp == null) { - condExp = this.parser.parseExpression(conditionExpression); - this.conditionCache.put(key, condExp); + /** + * Create an {@link EvaluationContext}. + * + * @param caches the current caches + * @param method the method + * @param args the method arguments + * @param target the target object + * @param targetClass the target class + * @param result the return value (can be {@code null}) or + * {@link #NO_RESULT} if there is no return at this time + * @return the evalulation context + */ + public EvaluationContext createEvaluationContext(Collection caches, + Method method, Object[] args, Object target, Class targetClass, + final Object result) { + CacheExpressionRootObject rootObject = new CacheExpressionRootObject(caches, + method, args, target, targetClass); + LazyParamAwareEvaluationContext evaluationContext = new LazyParamAwareEvaluationContext(rootObject, + this.paramNameDiscoverer, method, args, targetClass, this.targetMethodCache); + if(result != NO_RESULT) { + evaluationContext.setVariable("result", result); } - return condExp.getValue(evalContext, boolean.class); + return evaluationContext; } public Object key(String keyExpression, Method method, EvaluationContext evalContext) { - String key = toString(method, keyExpression); - Expression keyExp = this.keyCache.get(key); - if (keyExp == null) { - keyExp = this.parser.parseExpression(keyExpression); - this.keyCache.put(key, keyExp); + return getExpression(this.keyCache, keyExpression, method).getValue(evalContext); + } + + public boolean condition(String conditionExpression, Method method, EvaluationContext evalContext) { + return getExpression(this.conditionCache, conditionExpression, method).getValue( + evalContext, boolean.class); + } + + public boolean unless(String unlessExpression, Method method, EvaluationContext evalContext) { + return getExpression(this.unlessCache, unlessExpression, method).getValue( + evalContext, boolean.class); + } + + private Expression getExpression(Map cache, String expression, Method method) { + String key = toString(method, expression); + Expression rtn = cache.get(key); + if (rtn == null) { + rtn = this.parser.parseExpression(expression); + cache.put(key, rtn); } - return keyExp.getValue(evalContext); + return rtn; } private String toString(Method method, String expression) { diff --git a/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-3.2.xsd b/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-3.2.xsd index 9bfdf14010..baf1f802c0 100644 --- a/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-3.2.xsd +++ b/spring-context/src/main/resources/org/springframework/cache/config/spring-cache-3.2.xsd @@ -36,7 +36,7 @@ @@ -150,7 +150,7 @@ @@ -160,7 +160,7 @@ - + @@ -194,16 +194,42 @@ example, 'get*', 'handle*', '*Order', 'on*Event', etc.]]> - + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -217,16 +243,16 @@ - + - + diff --git a/spring-context/src/test/java/org/springframework/cache/config/AbstractAnnotationTests.java b/spring-context/src/test/java/org/springframework/cache/config/AbstractAnnotationTests.java index 4bc0c888b3..41d717d692 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/AbstractAnnotationTests.java +++ b/spring-context/src/test/java/org/springframework/cache/config/AbstractAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2011 the original author or authors. + * Copyright 2010-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.cache.config; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.*; import java.util.Collection; @@ -33,6 +35,7 @@ import org.springframework.context.ApplicationContext; * * @author Costin Leau * @author Chris Beams + * @author Phillip Webb */ public abstract class AbstractAnnotationTests { @@ -187,6 +190,15 @@ public abstract class AbstractAnnotationTests { assertSame(r3, r4); } + public void testUnlessExpression(CacheableService service) throws Exception { + Cache cache = cm.getCache("default"); + cache.clear(); + service.unless(10); + service.unless(11); + assertThat(cache.get(10).get(), equalTo((Object) 10L)); + assertThat(cache.get(11), nullValue()); + } + public void testKeyExpression(CacheableService service) throws Exception { Object r1 = service.key(5, 1); Object r2 = service.key(5, 2); @@ -441,6 +453,16 @@ public abstract class AbstractAnnotationTests { testConditionalExpression(cs); } + @Test + public void testUnlessExpression() throws Exception { + testUnlessExpression(cs); + } + + @Test + public void testClassCacheUnlessExpression() throws Exception { + testUnlessExpression(cs); + } + @Test public void testKeyExpression() throws Exception { testKeyExpression(cs); @@ -618,4 +640,4 @@ public abstract class AbstractAnnotationTests { public void testClassMultiConditionalCacheAndEvict() { testMultiConditionalCacheAndEvict(ccs); } -} \ No newline at end of file +} diff --git a/spring-context/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java b/spring-context/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java index 4c72d9d593..f168ab990a 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java +++ b/spring-context/src/test/java/org/springframework/cache/config/AnnotatedClassCacheableService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,6 +25,7 @@ import org.springframework.cache.annotation.Caching; /** * @author Costin Leau + * @author Phillip Webb */ @Cacheable("default") public class AnnotatedClassCacheableService implements CacheableService { @@ -42,6 +43,12 @@ public class AnnotatedClassCacheableService implements CacheableService return null; } + @Override + @Cacheable(value = "default", unless = "#result > 10") + public Object unless(int arg) { + return arg; + } + @Override @CacheEvict("default") public void invalidate(Object arg1) { @@ -157,4 +164,4 @@ public class AnnotatedClassCacheableService implements CacheableService public Object multiUpdate(Object arg1) { return arg1; } -} \ No newline at end of file +} diff --git a/spring-context/src/test/java/org/springframework/cache/config/CacheableService.java b/spring-context/src/test/java/org/springframework/cache/config/CacheableService.java index 81dd758d19..98c1da1e03 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/CacheableService.java +++ b/spring-context/src/test/java/org/springframework/cache/config/CacheableService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ package org.springframework.cache.config; * Basic service interface. * * @author Costin Leau + * @author Phillip Webb */ public interface CacheableService { @@ -39,6 +40,8 @@ public interface CacheableService { T conditional(int field); + T unless(int arg); + T key(Object arg1, Object arg2); T name(Object arg1); @@ -67,4 +70,4 @@ public interface CacheableService { T multiConditionalCacheAndEvict(Object arg1); T multiUpdate(Object arg1); -} \ No newline at end of file +} diff --git a/spring-context/src/test/java/org/springframework/cache/config/DefaultCacheableService.java b/spring-context/src/test/java/org/springframework/cache/config/DefaultCacheableService.java index f9f19b4759..f987d7bbe6 100644 --- a/spring-context/src/test/java/org/springframework/cache/config/DefaultCacheableService.java +++ b/spring-context/src/test/java/org/springframework/cache/config/DefaultCacheableService.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import org.springframework.cache.annotation.Caching; * Simple cacheable service * * @author Costin Leau + * @author Phillip Webb */ public class DefaultCacheableService implements CacheableService { @@ -78,6 +79,12 @@ public class DefaultCacheableService implements CacheableService { return counter.getAndIncrement(); } + @Override + @Cacheable(value = "default", unless = "#result > 10") + public Long unless(int arg) { + return (long) arg; + } + @Override @Cacheable(value = "default", key = "#p0") public Long key(Object arg1, Object arg2) { @@ -163,4 +170,4 @@ public class DefaultCacheableService implements CacheableService { public Long multiUpdate(Object arg1) { return Long.valueOf(arg1.toString()); } -} \ No newline at end of file +} diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java index b52f364746..0a664afac0 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,24 +16,39 @@ package org.springframework.cache.interceptor; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; import java.lang.reflect.Method; import java.util.Collection; import java.util.Iterator; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.springframework.cache.Cache; import org.springframework.cache.annotation.AnnotationCacheOperationSource; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.expression.EvaluationContext; +import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.util.ReflectionUtils; import edu.emory.mathcs.backport.java.util.Collections; +/** + * @author Costin Leau + * @author Phillip Webb + */ public class ExpressionEvalutatorTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + private ExpressionEvaluator eval = new ExpressionEvaluator(); private AnnotationCacheOperationSource source = new AnnotationCacheOperationSource(); @@ -59,6 +74,7 @@ public class ExpressionEvalutatorTest { } @Test + @SuppressWarnings("unchecked") public void testMultipleCachingEval() throws Exception { AnnotatedClass target = new AnnotatedClass(); Method method = ReflectionUtils.findMethod(AnnotatedClass.class, "multipleCaching", Object.class, @@ -78,9 +94,41 @@ public class ExpressionEvalutatorTest { assertEquals(args[1], keyB); } + @Test + public void withReturnValue() throws Exception { + EvaluationContext context = createEvaluationContext("theResult"); + Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); + assertThat(value, equalTo((Object) "theResult")); + } + + @Test + public void withNullReturn() throws Exception { + EvaluationContext context = createEvaluationContext(null); + Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); + assertThat(value, nullValue()); + } + + @Test + public void withoutReturnValue() throws Exception { + EvaluationContext context = createEvaluationContext(ExpressionEvaluator.NO_RESULT); + Object value = new SpelExpressionParser().parseExpression("#result").getValue(context); + assertThat(value, nullValue()); + } + + private EvaluationContext createEvaluationContext(Object result) { + AnnotatedClass target = new AnnotatedClass(); + Method method = ReflectionUtils.findMethod(AnnotatedClass.class, "multipleCaching", Object.class, + Object.class); + Object[] args = new Object[] { new Object(), new Object() }; + @SuppressWarnings("unchecked") + Collection map = Collections.singleton(new ConcurrentMapCache("test")); + EvaluationContext context = eval.createEvaluationContext(map, method, args, target, target.getClass(), result); + return context; + } + private static class AnnotatedClass { @Caching(cacheable = { @Cacheable(value = "test", key = "#a"), @Cacheable(value = "test", key = "#b") }) public void multipleCaching(Object a, Object b) { } } -} \ No newline at end of file +} diff --git a/spring-context/src/test/resources/org/springframework/cache/config/cache-advice.xml b/spring-context/src/test/resources/org/springframework/cache/config/cache-advice.xml index d9eef4816b..5ebf54ddcb 100644 --- a/spring-context/src/test/resources/org/springframework/cache/config/cache-advice.xml +++ b/spring-context/src/test/resources/org/springframework/cache/config/cache-advice.xml @@ -3,7 +3,7 @@ xmlns:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p" - xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> @@ -11,6 +11,7 @@ + @@ -54,6 +55,7 @@ + @@ -80,9 +82,9 @@ - + - + @@ -98,12 +100,12 @@ - + - + - + diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 70defd90dd..476a1c5bd5 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -11,6 +11,7 @@ Changes in version 3.2.2 (2013-03-07) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) * consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) +* support 'unless' expression for cache veto (SPR-8871) Changes in version 3.2.1 (2013-01-24) diff --git a/src/reference/docbook/cache.xml b/src/reference/docbook/cache.xml index 08d2f34c0e..2ed4ab2b3f 100644 --- a/src/reference/docbook/cache.xml +++ b/src/reference/docbook/cache.xml @@ -152,6 +152,13 @@ public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed) + + In addition the conditional parameter, the unless parameter can be used to veto the adding of a value to the cache. Unlike + conditional, unless SpEL expressions are evalulated after the method has been called. Expanding + on the previous example - perhaps we only want to cache paperback books: + +
@@ -218,6 +225,13 @@ public Book findBook(String name)]]> stands for the argument index (starting from 0). iban or a0 (one can also use p0 or ]]> notation as an alias). + + result + evaluation context + The result of the method call (the value to be cached). Only available in 'unless' expressions and 'cache evict' + expression (when beforeInvocation is false). + #result + From a6b70722facc7caa52e1d73e273e639d6cce696c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 4 Feb 2013 13:57:48 -0800 Subject: [PATCH 177/311] Update Quartz documentation to use FactoryBeans Update examples for Quartz scheduling to use SimpleTriggerFactoryBean and CronTriggerFactoryBean instead of SimpleTriggerBean and CronTriggerBean. Issue: SPR-10209 --- src/reference/docbook/scheduling.xml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/reference/docbook/scheduling.xml b/src/reference/docbook/scheduling.xml index 6c5b7fbe83..a30a0f7d99 100644 --- a/src/reference/docbook/scheduling.xml +++ b/src/reference/docbook/scheduling.xml @@ -840,9 +840,9 @@ public class ExampleJob extends QuartzJobBean { object. Of course, we still need to schedule the jobs themselves. This is done using triggers and a SchedulerFactoryBean. Several triggers are - available within Quartz. Spring offers two subclassed triggers with - convenient defaults: CronTriggerBean and - SimpleTriggerBean. + available within Quartz and Spring offers two Quartz FactoryBean + implementations with convenient defaults: CronTriggerFactoryBean and + SimpleTriggerFactoryBean. Triggers need to be scheduled. Spring offers a SchedulerFactoryBean that exposes triggers to be @@ -851,7 +851,7 @@ public class ExampleJob extends QuartzJobBean { Find below a couple of examples: - <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> + <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <!-- see the example of method invoking job above --> <property name="jobDetail" ref="jobDetail" /> <!-- 10 seconds --> @@ -860,7 +860,7 @@ public class ExampleJob extends QuartzJobBean { <property name="repeatInterval" value="50000" /> </bean> -<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> +<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="exampleJob" /> <!-- run every morning at 6 AM --> <property name="cronExpression" value="0 0 6 * * ?" /> From 501ce650556c4ccd23f470ce884148346c8094bd Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 4 Feb 2013 15:00:45 -0800 Subject: [PATCH 178/311] Polish @Configuration javadoc --- .../org/springframework/context/annotation/Configuration.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/annotation/Configuration.java b/spring-context/src/main/java/org/springframework/context/annotation/Configuration.java index b09623c29c..ec3cf117ef 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/Configuration.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/Configuration.java @@ -68,8 +68,7 @@ import org.springframework.stereotype.Component; * * * - * - * } + * } * * In the example above, {@code } is required in order to * enable {@link ConfigurationClassPostProcessor} and other annotation-related From 1c724069c3a76d1619d2fee78ded5aaf6ab1b69b Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 4 Feb 2013 15:03:51 -0800 Subject: [PATCH 179/311] Improve presentation of code blocks in Javadoc Include custom javadoc css that formats
 blocks.

Issue: SPR-10155
---
 build.gradle           |   1 +
 src/api/stylesheet.css | 541 +++++++++++++++++++++++++++++++++++++++++
 2 files changed, 542 insertions(+)
 create mode 100644 src/api/stylesheet.css

diff --git a/build.gradle b/build.gradle
index 9ac71e790a..bf2977c699 100644
--- a/build.gradle
+++ b/build.gradle
@@ -817,6 +817,7 @@ configure(rootProject) {
 		options.author = true
 		options.header = rootProject.description
 		options.overview = "src/api/overview.html"
+		options.stylesheetFile = file("src/api/stylesheet.css")
 		options.splitIndex = true
 		options.links(project.ext.javadocLinks)
 
diff --git a/src/api/stylesheet.css b/src/api/stylesheet.css
new file mode 100644
index 0000000000..4b105f4ca4
--- /dev/null
+++ b/src/api/stylesheet.css
@@ -0,0 +1,541 @@
+/* Javadoc style sheet */
+
+/*
+Overall document style
+*/
+body {
+    background-color:#ffffff;
+    color:#353833;
+    font-family:Arial, Helvetica, sans-serif;
+    font-size:76%;
+    margin:0;
+}
+a:link, a:visited {
+    text-decoration:none;
+    color:#4c6b87;
+}
+a:hover, a:focus {
+    text-decoration:none;
+    color:#bb7a2a;
+}
+a:active {
+    text-decoration:none;
+    color:#4c6b87;
+}
+a[name] {
+    color:#353833;
+}
+a[name]:hover {
+    text-decoration:none;
+    color:#353833;
+}
+pre {
+    font-size:1.3em;
+}
+h1 {
+    font-size:1.8em;
+}
+h2 {
+    font-size:1.5em;
+}
+h3 {
+    font-size:1.4em;
+}
+h4 {
+    font-size:1.3em;
+}
+h5 {
+    font-size:1.2em;
+}
+h6 {
+    font-size:1.1em;
+}
+ul {
+    list-style-type:disc;
+}
+code, tt {
+    font-size:1.2em;
+}
+dt code {
+    font-size:1.2em;
+}
+table tr td dt code {
+    font-size:1.2em;
+    vertical-align:top;
+}
+sup {
+    font-size:.6em;
+}
+/*
+Document title and Copyright styles
+*/
+.clear {
+    clear:both;
+    height:0px;
+    overflow:hidden;
+}
+.aboutLanguage {
+    float:right;
+    padding:0px 21px;
+    font-size:.8em;
+    z-index:200;
+    margin-top:-7px;
+}
+.legalCopy {
+    margin-left:.5em;
+}
+.bar a, .bar a:link, .bar a:visited, .bar a:active {
+    color:#FFFFFF;
+    text-decoration:none;
+}
+.bar a:hover, .bar a:focus {
+    color:#bb7a2a;
+}
+.tab {
+    background-color:#0066FF;
+    background-image:url(resources/titlebar.gif);
+    background-position:left top;
+    background-repeat:no-repeat;
+    color:#ffffff;
+    padding:8px;
+    width:5em;
+    font-weight:bold;
+}
+/*
+Navigation bar styles
+*/
+.bar {
+    background-image:url(resources/background.gif);
+    background-repeat:repeat-x;
+    color:#FFFFFF;
+    padding:.8em .5em .4em .8em;
+    height:auto;/*height:1.8em;*/
+    font-size:1em;
+    margin:0;
+}
+.topNav {
+    background-image:url(resources/background.gif);
+    background-repeat:repeat-x;
+    color:#FFFFFF;
+    float:left;
+    padding:0;
+    width:100%;
+    clear:right;
+    height:2.8em;
+    padding-top:10px;
+    overflow:hidden;
+}
+.bottomNav {
+    margin-top:10px;
+    background-image:url(resources/background.gif);
+    background-repeat:repeat-x;
+    color:#FFFFFF;
+    float:left;
+    padding:0;
+    width:100%;
+    clear:right;
+    height:2.8em;
+    padding-top:10px;
+    overflow:hidden;
+}
+.subNav {
+    background-color:#dee3e9;
+    border-bottom:1px solid #9eadc0;
+    float:left;
+    width:100%;
+    overflow:hidden;
+}
+.subNav div {
+    clear:left;
+    float:left;
+    padding:0 0 5px 6px;
+}
+ul.navList, ul.subNavList {
+    float:left;
+    margin:0 25px 0 0;
+    padding:0;
+}
+ul.navList li{
+    list-style:none;
+    float:left;
+    padding:3px 6px;
+}
+ul.subNavList li{
+    list-style:none;
+    float:left;
+    font-size:90%;
+}
+.topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited {
+    color:#FFFFFF;
+    text-decoration:none;
+}
+.topNav a:hover, .bottomNav a:hover {
+    text-decoration:none;
+    color:#bb7a2a;
+}
+.navBarCell1Rev {
+    background-image:url(resources/tab.gif);
+    background-color:#a88834;
+    color:#FFFFFF;
+    margin: auto 5px;
+    border:1px solid #c9aa44;
+}
+/*
+Page header and footer styles
+*/
+.header, .footer {
+    clear:both;
+    margin:0 20px;
+    padding:5px 0 0 0;
+}
+.indexHeader {
+    margin:10px;
+    position:relative;
+}
+.indexHeader h1 {
+    font-size:1.3em;
+}
+.title {
+    color:#2c4557;
+    margin:10px 0;
+}
+.subTitle {
+    margin:5px 0 0 0;
+}
+.header ul {
+    margin:0 0 25px 0;
+    padding:0;
+}
+.footer ul {
+    margin:20px 0 5px 0;
+}
+.header ul li, .footer ul li {
+    list-style:none;
+    font-size:1.2em;
+}
+/*
+Heading styles
+*/
+div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 {
+    background-color:#dee3e9;
+    border-top:1px solid #9eadc0;
+    border-bottom:1px solid #9eadc0;
+    margin:0 0 6px -8px;
+    padding:2px 5px;
+}
+ul.blockList ul.blockList ul.blockList li.blockList h3 {
+    background-color:#dee3e9;
+    border-top:1px solid #9eadc0;
+    border-bottom:1px solid #9eadc0;
+    margin:0 0 6px -8px;
+    padding:2px 5px;
+}
+ul.blockList ul.blockList li.blockList h3 {
+    padding:0;
+    margin:15px 0;
+}
+ul.blockList li.blockList h2 {
+    padding:0px 0 20px 0;
+}
+/*
+Page layout container styles
+*/
+.contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer {
+    clear:both;
+    padding:10px 20px;
+    position:relative;
+}
+.indexContainer {
+    margin:10px;
+    position:relative;
+    font-size:1.0em;
+}
+.indexContainer h2 {
+    font-size:1.1em;
+    padding:0 0 3px 0;
+}
+.indexContainer ul {
+    margin:0;
+    padding:0;
+}
+.indexContainer ul li {
+    list-style:none;
+}
+.contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt {
+    font-size:1.1em;
+    font-weight:bold;
+    margin:10px 0 0 0;
+    color:#4E4E4E;
+}
+.contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd {
+    margin:10px 0 10px 20px;
+}
+.serializedFormContainer dl.nameValue dt {
+    margin-left:1px;
+    font-size:1.1em;
+    display:inline;
+    font-weight:bold;
+}
+.serializedFormContainer dl.nameValue dd {
+    margin:0 0 0 1px;
+    font-size:1.1em;
+    display:inline;
+}
+/*
+List styles
+*/
+ul.horizontal li {
+    display:inline;
+    font-size:0.9em;
+}
+ul.inheritance {
+    margin:0;
+    padding:0;
+}
+ul.inheritance li {
+    display:inline;
+    list-style:none;
+}
+ul.inheritance li ul.inheritance {
+    margin-left:15px;
+    padding-left:15px;
+    padding-top:1px;
+}
+ul.blockList, ul.blockListLast {
+    margin:10px 0 10px 0;
+    padding:0;
+}
+ul.blockList li.blockList, ul.blockListLast li.blockList {
+    list-style:none;
+    margin-bottom:25px;
+}
+ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList {
+    padding:0px 20px 5px 10px;
+    border:1px solid #9eadc0;
+    background-color:#f9f9f9;
+}
+ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList {
+    padding:0 0 5px 8px;
+    background-color:#ffffff;
+    border:1px solid #9eadc0;
+    border-top:none;
+}
+ul.blockList ul.blockList ul.blockList ul.blockList li.blockList {
+    margin-left:0;
+    padding-left:0;
+    padding-bottom:15px;
+    border:none;
+    border-bottom:1px solid #9eadc0;
+}
+ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast {
+    list-style:none;
+    border-bottom:none;
+    padding-bottom:0;
+}
+table tr td dl, table tr td dl dt, table tr td dl dd {
+    margin-top:0;
+    margin-bottom:1px;
+}
+/*
+Table styles
+*/
+.contentContainer table, .classUseContainer table, .constantValuesContainer table {
+    border-bottom:1px solid #9eadc0;
+    width:100%;
+}
+.contentContainer ul li table, .classUseContainer ul li table, .constantValuesContainer ul li table {
+    width:100%;
+}
+.contentContainer .description table, .contentContainer .details table {
+    border-bottom:none;
+}
+.contentContainer ul li table th.colOne, .contentContainer ul li table th.colFirst, .contentContainer ul li table th.colLast, .classUseContainer ul li table th, .constantValuesContainer ul li table th, .contentContainer ul li table td.colOne, .contentContainer ul li table td.colFirst, .contentContainer ul li table td.colLast, .classUseContainer ul li table td, .constantValuesContainer ul li table td{
+    vertical-align:top;
+    padding-right:20px;
+}
+.contentContainer ul li table th.colLast, .classUseContainer ul li table th.colLast,.constantValuesContainer ul li table th.colLast,
+.contentContainer ul li table td.colLast, .classUseContainer ul li table td.colLast,.constantValuesContainer ul li table td.colLast,
+.contentContainer ul li table th.colOne, .classUseContainer ul li table th.colOne,
+.contentContainer ul li table td.colOne, .classUseContainer ul li table td.colOne {
+    padding-right:3px;
+}
+.overviewSummary caption, .packageSummary caption, .contentContainer ul.blockList li.blockList caption, .summary caption, .classUseContainer caption, .constantValuesContainer caption {
+    position:relative;
+    text-align:left;
+    background-repeat:no-repeat;
+    color:#FFFFFF;
+    font-weight:bold;
+    clear:none;
+    overflow:hidden;
+    padding:0px;
+    margin:0px;
+}
+caption a:link, caption a:hover, caption a:active, caption a:visited {
+    color:#FFFFFF;
+}
+.overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span {
+    white-space:nowrap;
+    padding-top:8px;
+    padding-left:8px;
+    display:block;
+    float:left;
+    background-image:url(resources/titlebar.gif);
+    height:18px;
+}
+.contentContainer ul.blockList li.blockList caption span.activeTableTab span {
+    white-space:nowrap;
+    padding-top:8px;
+    padding-left:8px;
+    display:block;
+    float:left;
+    background-image:url(resources/activetitlebar.gif);
+    height:18px;
+}
+.contentContainer ul.blockList li.blockList caption span.tableTab span {
+    white-space:nowrap;
+    padding-top:8px;
+    padding-left:8px;
+    display:block;
+    float:left;
+    background-image:url(resources/titlebar.gif);
+    height:18px;
+}
+.contentContainer ul.blockList li.blockList caption span.tableTab, .contentContainer ul.blockList li.blockList caption span.activeTableTab {
+    padding-top:0px;
+    padding-left:0px;
+    background-image:none;
+    float:none;
+    display:inline;
+}
+.overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd {
+    width:10px;
+    background-image:url(resources/titlebar_end.gif);
+    background-repeat:no-repeat;
+    background-position:top right;
+    position:relative;
+    float:left;
+}
+.contentContainer ul.blockList li.blockList .activeTableTab .tabEnd {
+    width:10px;
+    margin-right:5px;
+    background-image:url(resources/activetitlebar_end.gif);
+    background-repeat:no-repeat;
+    background-position:top right;
+    position:relative;
+    float:left;
+}
+.contentContainer ul.blockList li.blockList .tableTab .tabEnd {
+    width:10px;
+    margin-right:5px;
+    background-image:url(resources/titlebar_end.gif);
+    background-repeat:no-repeat;
+    background-position:top right;
+    position:relative;
+    float:left;
+}
+ul.blockList ul.blockList li.blockList table {
+    margin:0 0 12px 0px;
+    width:100%;
+}
+.tableSubHeadingColor {
+    background-color: #EEEEFF;
+}
+.altColor {
+    background-color:#eeeeef;
+}
+.rowColor {
+    background-color:#ffffff;
+}
+.overviewSummary td, .packageSummary td, .contentContainer ul.blockList li.blockList td, .summary td, .classUseContainer td, .constantValuesContainer td {
+    text-align:left;
+    padding:3px 3px 3px 7px;
+}
+th.colFirst, th.colLast, th.colOne, .constantValuesContainer th {
+    background:#dee3e9;
+    border-top:1px solid #9eadc0;
+    border-bottom:1px solid #9eadc0;
+    text-align:left;
+    padding:3px 3px 3px 7px;
+}
+td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover {
+    font-weight:bold;
+}
+td.colFirst, th.colFirst {
+    border-left:1px solid #9eadc0;
+    white-space:nowrap;
+}
+td.colLast, th.colLast {
+    border-right:1px solid #9eadc0;
+}
+td.colOne, th.colOne {
+    border-right:1px solid #9eadc0;
+    border-left:1px solid #9eadc0;
+}
+table.overviewSummary  {
+    padding:0px;
+    margin-left:0px;
+}
+table.overviewSummary td.colFirst, table.overviewSummary th.colFirst,
+table.overviewSummary td.colOne, table.overviewSummary th.colOne {
+    width:25%;
+    vertical-align:middle;
+}
+table.packageSummary td.colFirst, table.overviewSummary th.colFirst {
+    width:25%;
+    vertical-align:middle;
+}
+/*
+Content styles
+*/
+.description pre {
+    margin-top:0;
+}
+.deprecatedContent {
+    margin:0;
+    padding:10px 0;
+}
+.docSummary {
+    padding:0;
+}
+/*
+Formatting effect styles
+*/
+.sourceLineNo {
+    color:green;
+    padding:0 30px 0 0;
+}
+h1.hidden {
+    visibility:hidden;
+    overflow:hidden;
+    font-size:.9em;
+}
+.block {
+    display:block;
+    margin:3px 0 0 0;
+}
+.strong {
+    font-weight:bold;
+}
+
+
+/*
+Spring
+*/
+
+pre.code {
+    background-color: #F8F8F8;
+    border: 1px solid #CCCCCC;
+    border-radius: 3px 3px 3px 3px;
+    overflow: auto;
+    padding: 10px;
+    margin: 4px 20px 2px 0px;
+}
+
+pre.code code, pre.code code * {
+    font-size: 1em;
+}
+
+pre.code code, pre.code code * {
+    padding: 0 !important;
+    margin: 0 !important;
+}

From 1cc58e0a99f15cb0c071542aed4990898f0e28e1 Mon Sep 17 00:00:00 2001
From: Phillip Webb 
Date: Wed, 6 Feb 2013 10:42:46 -0800
Subject: [PATCH 180/311] Limit auto grow collection size when using SpEL

Provide an additional constructor on SpelParserConfiguration that can
be used to limit the maximum size that a collection will auto grow when
being accessed via a SpEL expression.

This constraint is particularly useful when SpEL is used with data
binding as it prevents a malicious user from crafting a request that
causes OutOfMemory exceptions.

Issue: SPR-10229
---
 .../spel/SpelParserConfiguration.java         | 36 +++++++-
 .../expression/spel/ast/Indexer.java          | 87 +++++++++----------
 .../expression/spel/EvaluationTests.java      | 30 ++++++-
 3 files changed, 102 insertions(+), 51 deletions(-)

diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/SpelParserConfiguration.java b/spring-expression/src/main/java/org/springframework/expression/spel/SpelParserConfiguration.java
index c9e7bad2f1..ccadb93061 100644
--- a/spring-expression/src/main/java/org/springframework/expression/spel/SpelParserConfiguration.java
+++ b/spring-expression/src/main/java/org/springframework/expression/spel/SpelParserConfiguration.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2009 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ package org.springframework.expression.spel;
  * Configuration object for the SpEL expression parser.
  *
  * @author Juergen Hoeller
+ * @author Phillip Webb
  * @since 3.0
  * @see org.springframework.expression.spel.standard.SpelExpressionParser#SpelExpressionParser(SpelParserConfiguration)
  */
@@ -29,19 +30,52 @@ public class SpelParserConfiguration {
 
 	private final boolean autoGrowCollections;
 
+	private int maximumAutoGrowSize;
 
+
+	/**
+	 * Create a new {@link SpelParserConfiguration} instance.
+	 * @param autoGrowNullReferences if null references should automatically grow
+	 * @param autoGrowCollections if collections should automatically grow
+	 * @see #SpelParserConfiguration(boolean, boolean, int)
+	 */
 	public SpelParserConfiguration(boolean autoGrowNullReferences, boolean autoGrowCollections) {
+		this(autoGrowNullReferences, autoGrowCollections, Integer.MAX_VALUE);
+	}
+
+	/**
+	 * Create a new {@link SpelParserConfiguration} instance.
+	 * @param autoGrowNullReferences if null references should automatically grow
+	 * @param autoGrowCollections if collections should automatically grow
+	 * @param maximumAutoGrowSize the maximum size that the collection can auto grow
+	 */
+	public SpelParserConfiguration(boolean autoGrowNullReferences,
+			boolean autoGrowCollections, int maximumAutoGrowSize) {
 		this.autoGrowNullReferences = autoGrowNullReferences;
 		this.autoGrowCollections = autoGrowCollections;
+		this.maximumAutoGrowSize = maximumAutoGrowSize;
 	}
 
 
+	/**
+	 * @return {@code true} if {@code null} references should be automatically grown
+	 */
 	public boolean isAutoGrowNullReferences() {
 		return this.autoGrowNullReferences;
 	}
 
+	/**
+	 * @return {@code true} if collections should be automatically grown
+	 */
 	public boolean isAutoGrowCollections() {
 		return this.autoGrowCollections;
 	}
 
+	/**
+	 * @return the maximum size that a collection can auto grow
+	 */
+	public int getMaximumAutoGrowSize() {
+		return this.maximumAutoGrowSize;
+	}
+
 }
diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
index f061326251..2e19cc81e2 100644
--- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
+++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -38,6 +38,7 @@ import org.springframework.expression.spel.support.ReflectivePropertyAccessor;
  * (lists/sets)/arrays
  *
  * @author Andy Clement
+ * @author Phillip Webb
  * @since 3.0
  */
 // TODO support multidimensional arrays
@@ -257,25 +258,20 @@ public class Indexer extends SpelNodeImpl {
 
 		private final boolean growCollection;
 
+		private int maximumSize;
+
 		CollectionIndexingValueRef(Collection collection, int index, TypeDescriptor collectionEntryTypeDescriptor,
-				TypeConverter typeConverter, boolean growCollection) {
+				TypeConverter typeConverter, boolean growCollection, int maximumSize) {
 			this.collection = collection;
 			this.index = index;
 			this.collectionEntryTypeDescriptor = collectionEntryTypeDescriptor;
 			this.typeConverter = typeConverter;
 			this.growCollection = growCollection;
+			this.maximumSize = maximumSize;
 		}
 
 		public TypedValue getValue() {
-			if (this.index >= this.collection.size()) {
-				if (this.growCollection) {
-					growCollection(this.collectionEntryTypeDescriptor, this.index, this.collection);
-				}
-				else {
-					throw new SpelEvaluationException(getStartPosition(), SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,
-							this.collection.size(), this.index);
-				}
-			}
+			growCollectionIfNecessary();
 			if (this.collection instanceof List) {
 				Object o = ((List) this.collection).get(this.index);
 				return new TypedValue(o, this.collectionEntryTypeDescriptor.elementTypeDescriptor(o));
@@ -291,15 +287,7 @@ public class Indexer extends SpelNodeImpl {
 		}
 
 		public void setValue(Object newValue) {
-			if (this.index >= this.collection.size()) {
-				if (this.growCollection) {
-					growCollection(this.collectionEntryTypeDescriptor, this.index, this.collection);
-				}
-				else {
-					throw new SpelEvaluationException(getStartPosition(), SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,
-							this.collection.size(), this.index);
-				}
-			}
+			growCollectionIfNecessary();
 			if (this.collection instanceof List) {
 				List list = (List) this.collection;
 				if (this.collectionEntryTypeDescriptor.getElementTypeDescriptor() != null) {
@@ -314,6 +302,36 @@ public class Indexer extends SpelNodeImpl {
 			}
 		}
 
+		private void growCollectionIfNecessary() {
+			if (this.index >= this.collection.size()) {
+
+				if (!this.growCollection) {
+					throw new SpelEvaluationException(getStartPosition(), SpelMessage.COLLECTION_INDEX_OUT_OF_BOUNDS,
+							this.collection.size(), this.index);
+				}
+
+				if(this.index >= this.maximumSize) {
+					throw new SpelEvaluationException(getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION);
+				}
+
+				if (this.collectionEntryTypeDescriptor.getElementTypeDescriptor() == null) {
+					throw new SpelEvaluationException(getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE);
+				}
+
+				TypeDescriptor elementType = this.collectionEntryTypeDescriptor.getElementTypeDescriptor();
+				try {
+					int newElements = this.index - this.collection.size();
+					while (newElements >= 0) {
+						(this.collection).add(elementType.getType().newInstance());
+						newElements--;
+					}
+				}
+				catch (Exception ex) {
+					throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_GROW_COLLECTION);
+				}
+			}
+		}
+
 		public boolean isWritable() {
 			return true;
 		}
@@ -403,7 +421,8 @@ public class Indexer extends SpelNodeImpl {
 			}
 			else if (targetObject instanceof Collection) {
 				return new CollectionIndexingValueRef((Collection) targetObject, idx, targetObjectTypeDescriptor,
-						state.getTypeConverter(), state.getConfiguration().isAutoGrowCollections());
+						state.getTypeConverter(), state.getConfiguration().isAutoGrowCollections(),
+						state.getConfiguration().getMaximumAutoGrowSize());
 			}
 			else if (targetObject instanceof String) {
 				return new StringIndexingLValue((String) targetObject, idx, targetObjectTypeDescriptor);
@@ -421,32 +440,6 @@ public class Indexer extends SpelNodeImpl {
 				targetObjectTypeDescriptor.toString());
 	}
 
-	/**
-	 * Attempt to grow the specified collection so that the specified index is valid.
-	 * @param targetType the type of the elements in the collection
-	 * @param index the index into the collection that needs to be valid
-	 * @param collection the collection to grow with elements
-	 */
-	private void growCollection(TypeDescriptor targetType, int index, Collection collection) {
-		if (targetType.getElementTypeDescriptor() == null) {
-			throw new SpelEvaluationException(getStartPosition(), SpelMessage.UNABLE_TO_GROW_COLLECTION_UNKNOWN_ELEMENT_TYPE);
-		}
-		TypeDescriptor elementType = targetType.getElementTypeDescriptor();
-		Object newCollectionElement;
-		try {
-			int newElements = index - collection.size();
-			while (newElements > 0) {
-				collection.add(elementType.getType().newInstance());
-				newElements--;
-			}
-			newCollectionElement = elementType.getType().newInstance();
-		}
-		catch (Exception ex) {
-			throw new SpelEvaluationException(getStartPosition(), ex, SpelMessage.UNABLE_TO_GROW_COLLECTION);
-		}
-		collection.add(newCollectionElement);
-	}
-
 	@Override
 	public String toStringAST() {
 		StringBuilder sb = new StringBuilder();
diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
index aeb991ab55..25fcba0f4b 100644
--- a/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
+++ b/spring-expression/src/test/java/org/springframework/expression/spel/EvaluationTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,7 +16,14 @@
 
 package org.springframework.expression.spel;
 
-import static org.junit.Assert.*;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
 
 import java.lang.reflect.Method;
 import java.util.ArrayList;
@@ -24,7 +31,6 @@ import java.util.List;
 import java.util.Map;
 
 import org.junit.Test;
-
 import org.springframework.core.convert.TypeDescriptor;
 import org.springframework.expression.AccessException;
 import org.springframework.expression.BeanResolver;
@@ -48,6 +54,7 @@ import org.springframework.expression.spel.testresources.TestPerson;
  * @author Andy Clement
  * @author Mark Fisher
  * @author Sam Brannen
+ * @author Phillip Webb
  * @since 3.0
  */
 public class EvaluationTests extends ExpressionTestCase {
@@ -708,6 +715,23 @@ public class EvaluationTests extends ExpressionTestCase {
 		}
 	}
 
+	@Test
+	public void limitCollectionGrowing() throws Exception {
+		TestClass instance = new TestClass();
+		StandardEvaluationContext ctx = new StandardEvaluationContext(instance);
+		SpelExpressionParser parser = new SpelExpressionParser( new SpelParserConfiguration(true, true, 3));
+		Expression expression = parser.parseExpression("foo[2]");
+		expression.setValue(ctx, "2");
+		assertThat(instance.getFoo().size(), equalTo(3));
+		expression = parser.parseExpression("foo[3]");
+		try {
+			expression.setValue(ctx, "3");
+		} catch(SpelEvaluationException see) {
+			assertEquals(SpelMessage.UNABLE_TO_GROW_COLLECTION, see.getMessageCode());
+			assertThat(instance.getFoo().size(), equalTo(3));
+		}
+	}
+
 	// For now I am making #this not assignable
 	@Test
 	public void increment01root() {

From 6b82d293d5ed2ec6f4e02432594a73e354d17928 Mon Sep 17 00:00:00 2001
From: Juergen Hoeller 
Date: Wed, 6 Feb 2013 20:41:37 +0100
Subject: [PATCH 181/311] ConfigurationClassPostProcessor allows for overriding
 of scoped-proxy bean definitions

Issue: SPR-10265
---
 .../ConfigurationClassBeanDefinitionReader.java      | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
index e41aca1728..e1676c6eb2 100644
--- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
+++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -256,7 +256,8 @@ class ConfigurationClassBeanDefinitionReader {
 		if (proxyMode != ScopedProxyMode.NO) {
 			BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
 					new BeanDefinitionHolder(beanDef, beanName), this.registry, proxyMode == ScopedProxyMode.TARGET_CLASS);
-			beanDefToRegister = proxyDef.getBeanDefinition();
+			beanDefToRegister =
+					new ConfigurationClassBeanDefinition((RootBeanDefinition) proxyDef.getBeanDefinition(), configClass);
 		}
 
 		if (logger.isDebugEnabled()) {
@@ -307,12 +308,17 @@ class ConfigurationClassBeanDefinitionReader {
 	@SuppressWarnings("serial")
 	private static class ConfigurationClassBeanDefinition extends RootBeanDefinition implements AnnotatedBeanDefinition {
 
-		private AnnotationMetadata annotationMetadata;
+		private final AnnotationMetadata annotationMetadata;
 
 		public ConfigurationClassBeanDefinition(ConfigurationClass configClass) {
 			this.annotationMetadata = configClass.getMetadata();
 		}
 
+		public ConfigurationClassBeanDefinition(RootBeanDefinition original, ConfigurationClass configClass) {
+			super(original);
+			this.annotationMetadata = configClass.getMetadata();
+		}
+
 		private ConfigurationClassBeanDefinition(ConfigurationClassBeanDefinition original) {
 			super(original);
 			this.annotationMetadata = original.annotationMetadata;

From ab3aa6c8c263057b61037471af98d15623506fec Mon Sep 17 00:00:00 2001
From: Juergen Hoeller 
Date: Wed, 6 Feb 2013 20:52:04 +0100
Subject: [PATCH 182/311] Added
 ContentNegotiationManager(Collection) constructor

---
 .../web/accept/ContentNegotiationManager.java | 23 +++++++++++--
 .../ContentNegotiationManagerFactoryBean.java | 33 +++++++++----------
 2 files changed, 37 insertions(+), 19 deletions(-)

diff --git a/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java b/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java
index 961ffdcc72..0024eef27d 100644
--- a/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java
+++ b/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2012 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.web.accept;
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -55,6 +56,7 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me
 	private final Set fileExtensionResolvers =
 			new LinkedHashSet();
 
+
 	/**
 	 * Create an instance with the given ContentNegotiationStrategy instances.
 	 * 

Each instance is checked to see if it is also an implementation of @@ -72,12 +74,29 @@ public class ContentNegotiationManager implements ContentNegotiationStrategy, Me } /** - * Create an instance with a {@link HeaderContentNegotiationStrategy}. + * Create an instance with the given ContentNegotiationStrategy instances. + *

Each instance is checked to see if it is also an implementation of + * MediaTypeFileExtensionResolver, and if so it is registered as such. + * @param strategies one more more ContentNegotiationStrategy instances + */ + public ContentNegotiationManager(Collection strategies) { + Assert.notEmpty(strategies, "At least one ContentNegotiationStrategy is expected"); + this.contentNegotiationStrategies.addAll(strategies); + for (ContentNegotiationStrategy strategy : this.contentNegotiationStrategies) { + if (strategy instanceof MediaTypeFileExtensionResolver) { + this.fileExtensionResolvers.add((MediaTypeFileExtensionResolver) strategy); + } + } + } + + /** + * Create a default instance with a {@link HeaderContentNegotiationStrategy}. */ public ContentNegotiationManager() { this(new HeaderContentNegotiationStrategy()); } + /** * Add MediaTypeFileExtensionResolver instances. *

Note that some {@link ContentNegotiationStrategy} implementations also diff --git a/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java b/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java index 8cf79f927d..a5d0357d91 100644 --- a/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java +++ b/spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.web.accept; import java.util.ArrayList; @@ -22,7 +23,6 @@ import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; - import javax.servlet.ServletContext; import org.springframework.beans.factory.FactoryBean; @@ -39,13 +39,13 @@ import org.springframework.web.context.ServletContextAware; *

By default strategies for checking the extension of the request path and * the {@code Accept} header are registered. The path extension check will perform * lookups through the {@link ServletContext} and the Java Activation Framework - * (if present) unless {@linkplain #setMediaTypes(Properties) media types} are configured. + * (if present) unless {@linkplain #setMediaTypes media types} are configured. * * @author Rossen Stoyanchev * @since 3.2 */ public class ContentNegotiationManagerFactoryBean - implements FactoryBean, InitializingBean, ServletContextAware { + implements FactoryBean, ServletContextAware, InitializingBean { private boolean favorPathExtension = true; @@ -65,6 +65,7 @@ public class ContentNegotiationManagerFactoryBean private ServletContext servletContext; + /** * Indicate whether the extension of the request path should be used to determine * the requested media type with the highest priority. @@ -81,7 +82,6 @@ public class ContentNegotiationManagerFactoryBean *

When this mapping is not set or when an extension is not found, the Java * Action Framework, if available, may be used if enabled via * {@link #setFavorPathExtension(boolean)}. - * * @see #addMediaType(String, MediaType) * @see #addMediaTypes(Map) */ @@ -121,9 +121,8 @@ public class ContentNegotiationManagerFactoryBean * to map from file extensions to media types. This is used only when * {@link #setFavorPathExtension(boolean)} is set to {@code true}. *

The default value is {@code true}. - * - * @see #parameterName - * @see #setMediaTypes(Properties) + * @see #setParameterName + * @see #setMediaTypes */ public void setUseJaf(boolean useJaf) { this.useJaf = useJaf; @@ -138,8 +137,7 @@ public class ContentNegotiationManagerFactoryBean * {@code "application/pdf"} regardless of the {@code Accept} header. *

To use this option effectively you must also configure the MediaType * type mappings via {@link #setMediaTypes(Properties)}. - * - * @see #setParameterName(String) + * @see #setParameterName */ public void setFavorParameter(boolean favorParameter) { this.favorParameter = favorParameter; @@ -180,7 +178,8 @@ public class ContentNegotiationManagerFactoryBean this.servletContext = servletContext; } - public void afterPropertiesSet() throws Exception { + + public void afterPropertiesSet() { List strategies = new ArrayList(); if (this.favorPathExtension) { @@ -210,8 +209,12 @@ public class ContentNegotiationManagerFactoryBean strategies.add(new FixedContentNegotiationStrategy(this.defaultContentType)); } - ContentNegotiationStrategy[] array = strategies.toArray(new ContentNegotiationStrategy[strategies.size()]); - this.contentNegotiationManager = new ContentNegotiationManager(array); + this.contentNegotiationManager = new ContentNegotiationManager(strategies); + } + + + public ContentNegotiationManager getObject() { + return this.contentNegotiationManager; } public Class getObjectType() { @@ -222,8 +225,4 @@ public class ContentNegotiationManagerFactoryBean return true; } - public ContentNegotiationManager getObject() throws Exception { - return this.contentNegotiationManager; - } - } From 188a11bdb925e3a4c1f38f8ff52f0039eb343eaf Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 6 Feb 2013 20:57:45 +0100 Subject: [PATCH 183/311] Fixed setFavorPathExtension delegation code --- .../view/ContentNegotiatingViewResolver.java | 25 ++++++------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java index 2d543941af..f7b59c3f6c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; - import javax.activation.FileTypeMap; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; @@ -33,6 +32,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.OrderComparator; @@ -95,7 +95,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport private ContentNegotiationManager contentNegotiationManager; - private ContentNegotiationManagerFactoryBean cnManagerFactoryBean = new ContentNegotiationManagerFactoryBean(); + private final ContentNegotiationManagerFactoryBean cnManagerFactoryBean = new ContentNegotiationManagerFactoryBean(); private boolean useNotAcceptableStatusCode = false; @@ -104,10 +104,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport private List viewResolvers; - public ContentNegotiatingViewResolver() { - super(); - } - public void setOrder(int order) { this.order = order; } @@ -118,7 +114,9 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport /** * Set the {@link ContentNegotiationManager} to use to determine requested media types. - * If not set, the default constructor is used. + *

If not set, ContentNegotiationManager's default constructor will be used, + * applying a {@link org.springframework.web.accept.HeaderContentNegotiationStrategy}. + * @see ContentNegotiationManager#ContentNegotiationManager() */ public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { this.contentNegotiationManager = contentNegotiationManager; @@ -130,18 +128,16 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport *

For instance, when this flag is {@code true} (the default), a request for {@code /hotels.pdf} * will result in an {@code AbstractPdfView} being resolved, while the {@code Accept} header can be the * browser-defined {@code text/html,application/xhtml+xml}. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated public void setFavorPathExtension(boolean favorPathExtension) { - this.cnManagerFactoryBean.setFavorParameter(favorPathExtension); + this.cnManagerFactoryBean.setFavorPathExtension(favorPathExtension); } /** * Indicate whether to use the Java Activation Framework to map from file extensions to media types. *

Default is {@code true}, i.e. the Java Activation Framework is used (if available). - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -155,7 +151,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport *

For instance, when this flag is {@code true}, a request for {@code /hotels?format=pdf} will result * in an {@code AbstractPdfView} being resolved, while the {@code Accept} header can be the browser-defined * {@code text/html,application/xhtml+xml}. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -166,7 +161,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport /** * Set the parameter name that can be used to determine the requested media type if the {@link * #setFavorParameter} property is {@code true}. The default parameter name is {@code format}. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -179,7 +173,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport *

If set to {@code true}, this view resolver will only refer to the file extension and/or * parameter, as indicated by the {@link #setFavorPathExtension favorPathExtension} and * {@link #setFavorParameter favorParameter} properties. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -191,7 +184,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport * Set the mapping from file extensions to media types. *

When this mapping is not set or when an extension is not present, this view resolver * will fall back to using a {@link FileTypeMap} when the Java Action Framework is available. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -207,7 +199,6 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport * Set the default content type. *

This content type will be used when file extension, parameter, nor {@code Accept} * header define a content-type, either through being disabled or empty. - * * @deprecated use {@link #setContentNegotiationManager(ContentNegotiationManager)} */ @Deprecated @@ -275,7 +266,7 @@ public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport this.cnManagerFactoryBean.setServletContext(servletContext); } - public void afterPropertiesSet() throws Exception { + public void afterPropertiesSet() { if (this.contentNegotiationManager == null) { this.cnManagerFactoryBean.afterPropertiesSet(); this.contentNegotiationManager = this.cnManagerFactoryBean.getObject(); From 8a4ce142c42375486542054b00c82331fecac311 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 6 Feb 2013 21:32:42 +0100 Subject: [PATCH 184/311] SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code, looping through the causes. Issue: SPR-10260 --- .../SQLErrorCodeSQLExceptionTranslator.java | 26 +++++++++++-------- ...LErrorCodeSQLExceptionTranslatorTests.java | 20 ++++++++++---- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java index a3290b8825..3bf52d3f71 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import java.lang.reflect.Constructor; import java.sql.BatchUpdateException; import java.sql.SQLException; import java.util.Arrays; - import javax.sql.DataSource; import org.springframework.core.JdkVersion; @@ -30,9 +29,9 @@ import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DeadlockLoserDataAccessException; +import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.PermissionDeniedDataAccessException; import org.springframework.dao.TransientDataAccessResourceException; -import org.springframework.dao.DuplicateKeyException; import org.springframework.jdbc.BadSqlGrammarException; import org.springframework.jdbc.InvalidResultSetAccessException; @@ -201,20 +200,25 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep // Check SQLErrorCodes with corresponding error code, if available. if (this.sqlErrorCodes != null) { - String errorCode = null; + String errorCode; if (this.sqlErrorCodes.isUseSqlStateForTranslation()) { errorCode = sqlEx.getSQLState(); } else { - errorCode = Integer.toString(sqlEx.getErrorCode()); + // Try to find SQLException with actual error code, looping through the causes. + // E.g. applicable to java.sql.DataTruncation as of JDK 1.6. + SQLException current = sqlEx; + while (current.getErrorCode() == 0 && current.getCause() instanceof SQLException) { + current = (SQLException) current.getCause(); + } + errorCode = Integer.toString(current.getErrorCode()); } if (errorCode != null) { // Look for defined custom translations first. CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations(); if (customTranslations != null) { - for (int i = 0; i < customTranslations.length; i++) { - CustomSQLErrorCodesTranslation customTranslation = customTranslations[i]; + for (CustomSQLErrorCodesTranslation customTranslation : customTranslations) { if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) { if (customTranslation.getExceptionClass() != null) { DataAccessException customException = createCustomException( @@ -273,7 +277,7 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator. if (logger.isDebugEnabled()) { - String codes = null; + String codes; if (this.sqlErrorCodes != null && this.sqlErrorCodes.isUseSqlStateForTranslation()) { codes = "SQL state '" + sqlEx.getSQLState() + "', error code '" + sqlEx.getErrorCode(); } @@ -321,8 +325,8 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep try { int constructorType = 0; Constructor[] constructors = exceptionClass.getConstructors(); - for (int i = 0; i < constructors.length; i++) { - Class[] parameterTypes = constructors[i].getParameterTypes(); + for (Constructor constructor : constructors) { + Class[] parameterTypes = constructor.getParameterTypes(); if (parameterTypes.length == 1 && parameterTypes[0].equals(String.class)) { if (constructorType < MESSAGE_ONLY_CONSTRUCTOR) constructorType = MESSAGE_ONLY_CONSTRUCTOR; @@ -350,7 +354,7 @@ public class SQLErrorCodeSQLExceptionTranslator extends AbstractFallbackSQLExcep } // invoke constructor - Constructor exceptionConstructor = null; + Constructor exceptionConstructor; switch (constructorType) { case MESSAGE_SQL_SQLEX_CONSTRUCTOR: Class[] messageAndSqlAndSqlExArgsClass = new Class[] {String.class, String.class, SQLException.class}; diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java index c2e07ec765..f7a23fa2e0 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/support/SQLErrorCodeSQLExceptionTranslatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,9 @@ package org.springframework.jdbc.support; -import java.sql.SQLException; import java.sql.BatchUpdateException; +import java.sql.DataTruncation; +import java.sql.SQLException; import junit.framework.TestCase; @@ -33,6 +34,7 @@ import org.springframework.jdbc.InvalidResultSetAccessException; /** * @author Rod Johnson + * @author Juergen Hoeller */ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { @@ -92,13 +94,21 @@ public class SQLErrorCodeSQLExceptionTranslatorTests extends TestCase { SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); SQLException badSqlEx = new SQLException("", "", 1); - BatchUpdateException batchUdateEx = new BatchUpdateException(); - batchUdateEx.setNextException(badSqlEx); - BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUdateEx); + BatchUpdateException batchUpdateEx = new BatchUpdateException(); + batchUpdateEx.setNextException(badSqlEx); + BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUpdateEx); assertEquals("SQL", bsgex.getSql()); assertEquals(badSqlEx, bsgex.getSQLException()); } + public void testDataTruncationTranslation() { + SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES); + + SQLException dataAccessEx = new SQLException("", "", 5); + DataTruncation dataTruncation = new DataTruncation(1, true, true, 1, 1, dataAccessEx); + DataAccessResourceFailureException daex = (DataAccessResourceFailureException) sext.translate("task", "SQL", dataTruncation); + assertEquals(dataTruncation, daex.getCause()); + } @SuppressWarnings("serial") public void testCustomTranslateMethodTranslation() { From c6cf91193175d540ad632960cb32d01178c2cbd5 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 6 Feb 2013 21:44:34 +0100 Subject: [PATCH 185/311] Marked spring-web module as 'distributable' in order for session replication to work on Tomcat Issue: SPR-10219 --- spring-web/src/main/resources/META-INF/web-fragment.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-web/src/main/resources/META-INF/web-fragment.xml b/spring-web/src/main/resources/META-INF/web-fragment.xml index d7c28cbccd..e687c8b58e 100644 --- a/spring-web/src/main/resources/META-INF/web-fragment.xml +++ b/spring-web/src/main/resources/META-INF/web-fragment.xml @@ -5,5 +5,6 @@ version="3.0" metadata-complete="true"> spring_web + - \ No newline at end of file + From 1ed26d63895442b48e3c5cd33a07ab6f639acb75 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 6 Feb 2013 21:48:28 +0100 Subject: [PATCH 186/311] Preparations for 3.2.2 --- src/dist/changelog.txt | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 476a1c5bd5..d033dfbc53 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -6,10 +6,15 @@ http://www.springsource.org Changes in version 3.2.2 (2013-03-07) -------------------------------------- +* official support for Hibernate 4.2 * ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) +* ConfigurationClassPostProcessor allows for overriding of scoped-proxy bean definitions (SPR-10265) +* added "maximumAutoGrowSize" property to SpelParserConfiguration (SPR-10229) +* SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) +* marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) * consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) * support 'unless' expression for cache veto (SPR-8871) @@ -35,7 +40,7 @@ Changes in version 3.2.1 (2013-01-24) * MessageSourceResourceBundle overrides JDK 1.6 containsKey method, avoiding NPE in getKeys (SPR-10136) * SpringValidationAdapter properly detects invalid value for JSR-303 field-level bean constraints (SPR-9332) * SpringBeanAutowiringInterceptor eagerly releases BeanFactory if post-construction fails (SPR-10013) -* added "exposeAccessContext" flag JndiRmiClientInterceptor/ProxyFactoryBean (for WebLogic; SPR-9428) +* added "exposeAccessContext" flag to JndiRmiClientInterceptor/ProxyFactoryBean (for WebLogic; SPR-9428) * MBeanExporter does not log warnings for manually unregistered MBeans (SPR-9451) * MBeanInfoAssembler impls expose actual method parameter names if possible (SPR-9985) * AbstractCacheManager accepts no caches defined, allowing for EHCache default cache setup (SPR-7955) From b21063ec056d8b681f540b78cd5311c642687c84 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 6 Feb 2013 14:25:28 -0800 Subject: [PATCH 187/311] Polish @Test annotation position --- .../factory/xml/XmlBeanFactoryTests.java | 285 ++++++++++++------ 1 file changed, 190 insertions(+), 95 deletions(-) diff --git a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java index b4e6a07538..6115b4979e 100644 --- a/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/beans/factory/xml/XmlBeanFactoryTests.java @@ -134,13 +134,15 @@ public final class XmlBeanFactoryTests { } /* SPR-2368 */ - public @Test void testCollectionsReferredToAsRefLocals() throws Exception { + @Test + public void testCollectionsReferredToAsRefLocals() throws Exception { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(COLLECTIONS_XSD_CONTEXT); factory.preInstantiateSingletons(); } - public @Test void testRefToSeparatePrototypeInstances() throws Exception { + @Test + public void testRefToSeparatePrototypeInstances() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -158,7 +160,8 @@ public final class XmlBeanFactoryTests { assertTrue("They object equal direct ref", emmasJenks.equals(xbf.getBean("jenks"))); } - public @Test void testRefToSingleton() throws Exception { + @Test + public void testRefToSingleton() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -173,7 +176,8 @@ public final class XmlBeanFactoryTests { assertTrue("1 jen instance", davesJen == jen); } - public @Test void testInnerBeans() throws IOException { + @Test + public void testInnerBeans() throws IOException { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); @@ -236,7 +240,8 @@ public final class XmlBeanFactoryTests { assertTrue(inner5.wasDestroyed()); } - public @Test void testInnerBeansWithoutDestroy() { + @Test + public void testInnerBeansWithoutDestroy() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -269,7 +274,8 @@ public final class XmlBeanFactoryTests { assertEquals("innerBean", inner5.getBeanName()); } - public @Test void testFailsOnInnerBean() { + @Test + public void testFailsOnInnerBean() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -296,7 +302,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testInheritanceFromParentFactoryPrototype() throws Exception { + @Test + public void testInheritanceFromParentFactoryPrototype() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -311,7 +318,8 @@ public final class XmlBeanFactoryTests { assertFalse(inherits2 == inherits); } - public @Test void testInheritanceWithDifferentClass() throws Exception { + @Test + public void testInheritanceWithDifferentClass() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -325,7 +333,8 @@ public final class XmlBeanFactoryTests { assertTrue(inherits.wasInitialized()); } - public @Test void testInheritanceWithClass() throws Exception { + @Test + public void testInheritanceWithClass() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -339,7 +348,8 @@ public final class XmlBeanFactoryTests { assertTrue(inherits.wasInitialized()); } - public @Test void testPrototypeInheritanceFromParentFactoryPrototype() throws Exception { + @Test + public void testPrototypeInheritanceFromParentFactoryPrototype() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -358,7 +368,8 @@ public final class XmlBeanFactoryTests { assertTrue(inherits.getAge() == 2); } - public @Test void testPrototypeInheritanceFromParentFactorySingleton() throws Exception { + @Test + public void testPrototypeInheritanceFromParentFactorySingleton() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -376,7 +387,8 @@ public final class XmlBeanFactoryTests { assertTrue(inherits.getAge() == 1); } - public @Test void testAutowireModeNotInherited() { + @Test + public void testAutowireModeNotInherited() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(OVERRIDES_CONTEXT); @@ -390,7 +402,8 @@ public final class XmlBeanFactoryTests { assertNull("autowiring not propagated along child relationships", derivedDavid.getSpouse()); } - public @Test void testAbstractParentBeans() { + @Test + public void testAbstractParentBeans() { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); parent.preInstantiateSingletons(); @@ -415,7 +428,8 @@ public final class XmlBeanFactoryTests { assertTrue(parent.getBean("inheritedTestBeanPrototype") instanceof TestBean); } - public @Test void testDependenciesMaterializeThis() throws Exception { + @Test + public void testDependenciesMaterializeThis() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(DEP_MATERIALIZE_CONTEXT); @@ -433,7 +447,8 @@ public final class XmlBeanFactoryTests { assertTrue(bos.dao == bop.dao); } - public @Test void testChildOverridesParentBean() throws Exception { + @Test + public void testChildOverridesParentBean() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -451,7 +466,8 @@ public final class XmlBeanFactoryTests { * Check that a prototype can't inherit from a bogus parent. * If a singleton does this the factory will fail to load. */ - public @Test void testBogusParentageFromParentFactory() throws Exception { + @Test + public void testBogusParentageFromParentFactory() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -472,7 +488,8 @@ public final class XmlBeanFactoryTests { * It's possible for a subclass singleton not to return independent * instances even if derived from a prototype */ - public @Test void testSingletonInheritsFromParentFactoryPrototype() throws Exception { + @Test + public void testSingletonInheritsFromParentFactoryPrototype() throws Exception { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -486,7 +503,8 @@ public final class XmlBeanFactoryTests { assertTrue(inherits2 == inherits); } - public @Test void testSingletonFromParent() { + @Test + public void testSingletonFromParent() { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); TestBean beanFromParent = (TestBean) parent.getBean("inheritedTestBeanSingleton"); @@ -496,7 +514,8 @@ public final class XmlBeanFactoryTests { assertTrue("singleton from parent and child is the same", beanFromParent == beanFromChild); } - public @Test void testNestedPropertyValue() { + @Test + public void testNestedPropertyValue() { DefaultListableBeanFactory parent = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(parent).loadBeanDefinitions(PARENT_CONTEXT); DefaultListableBeanFactory child = new DefaultListableBeanFactory(parent); @@ -505,7 +524,8 @@ public final class XmlBeanFactoryTests { assertEquals("name applied correctly", "myname", bean.getArray()[0].getName()); } - public @Test void testCircularReferences() { + @Test + public void testCircularReferences() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -522,7 +542,8 @@ public final class XmlBeanFactoryTests { assertTrue("Correct circular reference", complexEgo.getSpouse().getSpouse() == complexEgo); } - public @Test void testCircularReferenceWithFactoryBeanFirst() { + @Test + public void testCircularReferenceWithFactoryBeanFirst() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -532,7 +553,8 @@ public final class XmlBeanFactoryTests { assertTrue("Correct circular reference", complexEgo.getSpouse().getSpouse() == complexEgo); } - public @Test void testCircularReferenceWithTwoFactoryBeans() { + @Test + public void testCircularReferenceWithTwoFactoryBeans() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -543,7 +565,8 @@ public final class XmlBeanFactoryTests { assertTrue("Correct circular reference", ego3.getSpouse().getSpouse() == ego3); } - public @Test void testCircularReferencesWithNotAllowed() { + @Test + public void testCircularReferencesWithNotAllowed() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); xbf.setAllowCircularReferences(false); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); @@ -558,7 +581,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testCircularReferencesWithWrapping() { + @Test + public void testCircularReferencesWithWrapping() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); @@ -573,7 +597,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testCircularReferencesWithWrappingAndRawInjectionAllowed() { + @Test + public void testCircularReferencesWithWrappingAndRawInjectionAllowed() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); xbf.setAllowRawInjectionDespiteWrapping(true); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); @@ -593,7 +618,8 @@ public final class XmlBeanFactoryTests { assertTrue(!AopUtils.isAopProxy(david.getSpouse())); } - public @Test void testFactoryReferenceCircle() { + @Test + public void testFactoryReferenceCircle() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(FACTORY_CIRCLE_CONTEXT); TestBean tb = (TestBean) xbf.getBean("singletonFactory"); @@ -601,13 +627,15 @@ public final class XmlBeanFactoryTests { assertTrue(tb == db.getOtherTestBean()); } - public @Test void testFactoryReferenceWithDoublePrefix() { + @Test + public void testFactoryReferenceWithDoublePrefix() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(FACTORY_CIRCLE_CONTEXT); assertThat(xbf.getBean("&&singletonFactory"), instanceOf(DummyFactory.class)); } - public @Test void testComplexFactoryReferenceCircle() { + @Test + public void testComplexFactoryReferenceCircle() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(COMPLEX_FACTORY_CIRCLE_CONTEXT); xbf.getBean("proxy1"); @@ -618,7 +646,8 @@ public final class XmlBeanFactoryTests { assertEquals(5, xbf.getSingletonCount()); } - public @Test void testNoSuchFactoryBeanMethod() { + @Test + public void testNoSuchFactoryBeanMethod() { try { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(NO_SUCH_FACTORY_METHOD_CONTEXT); @@ -630,7 +659,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testInitMethodIsInvoked() throws Exception { + @Test + public void testInitMethodIsInvoked() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); DoubleInitializer in = (DoubleInitializer) xbf.getBean("init-method1"); @@ -641,7 +671,8 @@ public final class XmlBeanFactoryTests { /** * Test that if a custom initializer throws an exception, it's handled correctly */ - public @Test void testInitMethodThrowsException() { + @Test + public void testInitMethodThrowsException() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); try { @@ -655,7 +686,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testNoSuchInitMethod() throws Exception { + @Test + public void testNoSuchInitMethod() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); try { @@ -673,7 +705,8 @@ public final class XmlBeanFactoryTests { /** * Check that InitializingBean method is called first. */ - public @Test void testInitializingBeanAndInitMethod() throws Exception { + @Test + public void testInitializingBeanAndInitMethod() throws Exception { InitAndIB.constructed = false; DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); @@ -693,7 +726,8 @@ public final class XmlBeanFactoryTests { /** * Check that InitializingBean method is not called twice. */ - public @Test void testInitializingBeanAndSameInitMethod() throws Exception { + @Test + public void testInitializingBeanAndSameInitMethod() throws Exception { InitAndIB.constructed = false; DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INITIALIZERS_CONTEXT); @@ -710,7 +744,8 @@ public final class XmlBeanFactoryTests { assertTrue(iib.destroyed && !iib.customDestroyed); } - public @Test void testDefaultLazyInit() throws Exception { + @Test + public void testDefaultLazyInit() throws Exception { InitAndIB.constructed = false; DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(DEFAULT_LAZY_CONTEXT); @@ -725,7 +760,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testNoSuchXmlFile() throws Exception { + @Test + public void testNoSuchXmlFile() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(MISSING_CONTEXT); @@ -735,7 +771,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testInvalidXmlFile() throws Exception { + @Test + public void testInvalidXmlFile() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(INVALID_CONTEXT); @@ -745,7 +782,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testUnsatisfiedObjectDependencyCheck() throws Exception { + @Test + public void testUnsatisfiedObjectDependencyCheck() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_OBJECT_DEP_CONTEXT); @@ -756,7 +794,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testUnsatisfiedSimpleDependencyCheck() throws Exception { + @Test + public void testUnsatisfiedSimpleDependencyCheck() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_SIMPLE_DEP_CONTEXT); @@ -767,7 +806,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testSatisfiedObjectDependencyCheck() throws Exception { + @Test + public void testSatisfiedObjectDependencyCheck() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(SATISFIED_OBJECT_DEP_CONTEXT); DependenciesBean a = (DependenciesBean) xbf.getBean("a"); @@ -775,14 +815,16 @@ public final class XmlBeanFactoryTests { assertEquals(xbf, a.getBeanFactory()); } - public @Test void testSatisfiedSimpleDependencyCheck() throws Exception { + @Test + public void testSatisfiedSimpleDependencyCheck() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(SATISFIED_SIMPLE_DEP_CONTEXT); DependenciesBean a = (DependenciesBean) xbf.getBean("a"); assertEquals(a.getAge(), 33); } - public @Test void testUnsatisfiedAllDependencyCheck() throws Exception { + @Test + public void testUnsatisfiedAllDependencyCheck() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(UNSATISFIED_ALL_DEP_CONTEXT); @@ -793,7 +835,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testSatisfiedAllDependencyCheck() throws Exception { + @Test + public void testSatisfiedAllDependencyCheck() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(SATISFIED_ALL_DEP_CONTEXT); DependenciesBean a = (DependenciesBean) xbf.getBean("a"); @@ -802,7 +845,8 @@ public final class XmlBeanFactoryTests { assertNotNull(a.getSpouse()); } - public @Test void testAutowire() throws Exception { + @Test + public void testAutowire() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(AUTOWIRE_CONTEXT); TestBean spouse = new TestBean("kerry", 0); @@ -810,7 +854,8 @@ public final class XmlBeanFactoryTests { doTestAutowire(xbf); } - public @Test void testAutowireWithParent() throws Exception { + @Test + public void testAutowireWithParent() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(AUTOWIRE_CONTEXT); DefaultListableBeanFactory lbf = new DefaultListableBeanFactory(); @@ -871,7 +916,8 @@ public final class XmlBeanFactoryTests { assertTrue(appCtx.containsBean("jenny")); } - public @Test void testAutowireWithDefault() throws Exception { + @Test + public void testAutowireWithDefault() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(DEFAULT_AUTOWIRE_CONTEXT); @@ -893,7 +939,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testAutowireByConstructor() throws Exception { + @Test + public void testAutowireByConstructor() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorDependenciesBean rod1 = (ConstructorDependenciesBean) xbf.getBean("rod1"); @@ -930,7 +977,8 @@ public final class XmlBeanFactoryTests { assertEquals(null, rod.getName()); } - public @Test void testAutowireByConstructorWithSimpleValues() throws Exception { + @Test + public void testAutowireByConstructorWithSimpleValues() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); @@ -959,7 +1007,8 @@ public final class XmlBeanFactoryTests { assertTrue(rod6.destroyed); } - public @Test void testRelatedCausesFromConstructorResolution() { + @Test + public void testRelatedCausesFromConstructorResolution() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); @@ -973,7 +1022,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testConstructorArgResolution() { + @Test + public void testConstructorArgResolution() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); TestBean kerry1 = (TestBean) xbf.getBean("kerry1"); @@ -1021,7 +1071,8 @@ public final class XmlBeanFactoryTests { assertEquals(29, rod17.getAge()); } - public @Test void testPrototypeWithExplicitArguments() { + @Test + public void testPrototypeWithExplicitArguments() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); SimpleConstructorArgBean cd1 = (SimpleConstructorArgBean) xbf.getBean("rod18"); @@ -1036,14 +1087,16 @@ public final class XmlBeanFactoryTests { assertEquals(97, cd5.getAge()); } - public @Test void testConstructorArgWithSingleMatch() { + @Test + public void testConstructorArgWithSingleMatch() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); File file = (File) xbf.getBean("file"); assertEquals(File.separator + "test", file.getPath()); } - public @Test void testThrowsExceptionOnTooManyArguments() throws Exception { + @Test + public void testThrowsExceptionOnTooManyArguments() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); try { @@ -1054,7 +1107,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testThrowsExceptionOnAmbiguousResolution() throws Exception { + @Test + public void testThrowsExceptionOnAmbiguousResolution() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); try { @@ -1065,43 +1119,53 @@ public final class XmlBeanFactoryTests { } } - public @Test void testDependsOn() { + @Test + public void testDependsOn() { doTestDependencies(DEP_DEPENDSON_CONTEXT, 1); } - public @Test void testDependsOnInInnerBean() { + @Test + public void testDependsOnInInnerBean() { doTestDependencies(DEP_DEPENDSON_INNER_CONTEXT, 4); } - public @Test void testDependenciesThroughConstructorArguments() { + @Test + public void testDependenciesThroughConstructorArguments() { doTestDependencies(DEP_CARG_CONTEXT, 1); } - public @Test void testDependenciesThroughConstructorArgumentAutowiring() { + @Test + public void testDependenciesThroughConstructorArgumentAutowiring() { doTestDependencies(DEP_CARG_AUTOWIRE_CONTEXT, 1); } - public @Test void testDependenciesThroughConstructorArgumentsInInnerBean() { + @Test + public void testDependenciesThroughConstructorArgumentsInInnerBean() { doTestDependencies(DEP_CARG_INNER_CONTEXT, 1); } - public @Test void testDependenciesThroughProperties() { + @Test + public void testDependenciesThroughProperties() { doTestDependencies(DEP_PROP, 1); } - public @Test void testDependenciesThroughPropertiesWithInTheMiddle() { + @Test + public void testDependenciesThroughPropertiesWithInTheMiddle() { doTestDependencies(DEP_PROP_MIDDLE_CONTEXT, 1); } - public @Test void testDependenciesThroughPropertyAutowiringByName() { + @Test + public void testDependenciesThroughPropertyAutowiringByName() { doTestDependencies(DEP_PROP_ABN_CONTEXT, 1); } - public @Test void testDependenciesThroughPropertyAutowiringByType() { + @Test + public void testDependenciesThroughPropertyAutowiringByType() { doTestDependencies(DEP_PROP_ABT_CONTEXT, 1); } - public @Test void testDependenciesThroughPropertiesInInnerBean() { + @Test + public void testDependenciesThroughPropertiesInInnerBean() { doTestDependencies(DEP_PROP_INNER_CONTEXT, 1); } @@ -1132,7 +1196,8 @@ public final class XmlBeanFactoryTests { * bean def is being parsed, 'cos everything on a bean def is now lazy, but * must rather only be picked up when the bean is instantiated. */ - public @Test void testClassNotFoundWithDefaultBeanClassLoader() { + @Test + public void testClassNotFoundWithDefaultBeanClassLoader() { DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(factory).loadBeanDefinitions(CLASS_NOT_FOUND_CONTEXT); // cool, no errors, so the rubbish class name in the bean def was not resolved @@ -1147,7 +1212,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testClassNotFoundWithNoBeanClassLoader() { + @Test + public void testClassNotFoundWithNoBeanClassLoader() { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf); reader.setBeanClassLoader(null); @@ -1155,7 +1221,8 @@ public final class XmlBeanFactoryTests { assertEquals("WhatALotOfRubbish", bf.getBeanDefinition("classNotFound").getBeanClassName()); } - public @Test void testResourceAndInputStream() throws IOException { + @Test + public void testResourceAndInputStream() throws IOException { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RESOURCE_CONTEXT); // comes from "resourceImport.xml" @@ -1178,7 +1245,8 @@ public final class XmlBeanFactoryTests { assertEquals("test", writer.toString()); } - public @Test void testClassPathResourceWithImport() { + @Test + public void testClassPathResourceWithImport() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RESOURCE_CONTEXT); // comes from "resourceImport.xml" @@ -1187,7 +1255,8 @@ public final class XmlBeanFactoryTests { xbf.getBean("resource2", ResourceTestBean.class); } - public @Test void testUrlResourceWithImport() { + @Test + public void testUrlResourceWithImport() { URL url = getClass().getResource(RESOURCE_CONTEXT.getPath()); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new UrlResource(url)); @@ -1197,7 +1266,8 @@ public final class XmlBeanFactoryTests { xbf.getBean("resource2", ResourceTestBean.class); } - public @Test void testFileSystemResourceWithImport() throws URISyntaxException { + @Test + public void testFileSystemResourceWithImport() throws URISyntaxException { String file = getClass().getResource(RESOURCE_CONTEXT.getPath()).toURI().getPath(); DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(new FileSystemResource(file)); @@ -1207,7 +1277,8 @@ public final class XmlBeanFactoryTests { xbf.getBean("resource2", ResourceTestBean.class); } - public @Test void testRecursiveImport() { + @Test + public void testRecursiveImport() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(RECURSIVE_IMPORT_CONTEXT); @@ -1220,7 +1291,8 @@ public final class XmlBeanFactoryTests { } - public @Test void testLookupOverrideMethodsWithSetterInjection() { + @Test + public void testLookupOverrideMethodsWithSetterInjection() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(OVERRIDES_CONTEXT); @@ -1285,7 +1357,8 @@ public final class XmlBeanFactoryTests { assertSame(dave1, dave2); } - public @Test void testReplaceMethodOverrideWithSetterInjection() { + @Test + public void testReplaceMethodOverrideWithSetterInjection() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(DELEGATION_OVERRIDES_CONTEXT); @@ -1332,7 +1405,8 @@ public final class XmlBeanFactoryTests { assertEquals(s2, dos.lastArg); } - public @Test void testLookupOverrideOneMethodWithConstructorInjection() { + @Test + public void testLookupOverrideOneMethodWithConstructorInjection() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(CONSTRUCTOR_OVERRIDES_CONTEXT); @@ -1355,7 +1429,8 @@ public final class XmlBeanFactoryTests { fm1.getTestBean(), fm2.getTestBean()); } - public @Test void testRejectsOverrideOfBogusMethodName() { + @Test + public void testRejectsOverrideOfBogusMethodName() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); try { @@ -1372,7 +1447,8 @@ public final class XmlBeanFactoryTests { /** * Assert the presence of this bug until we resolve it. */ - public @Test void testSerializabilityOfMethodReplacer() throws Exception { + @Test + public void testSerializabilityOfMethodReplacer() throws Exception { try { BUGtestSerializableMethodReplacerAndSuperclass(); fail(); @@ -1395,7 +1471,8 @@ public final class XmlBeanFactoryTests { assertEquals("Method replace still works after serialization and deserialization", backwards, s.replaceMe(forwards)); } - public @Test void testInnerBeanInheritsScopeFromConcreteChildDefinition() { + @Test + public void testInnerBeanInheritsScopeFromConcreteChildDefinition() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(OVERRIDES_CONTEXT); @@ -1404,7 +1481,8 @@ public final class XmlBeanFactoryTests { assertTrue(jenny.getFriends().iterator().next() instanceof TestBean); } - public @Test void testConstructorArgWithSingleSimpleTypeMatch() { + @Test + public void testConstructorArgWithSingleSimpleTypeMatch() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); @@ -1415,7 +1493,8 @@ public final class XmlBeanFactoryTests { assertTrue(bean2.isSingleBoolean()); } - public @Test void testConstructorArgWithDoubleSimpleTypeMatch() { + @Test + public void testConstructorArgWithDoubleSimpleTypeMatch() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); @@ -1428,7 +1507,8 @@ public final class XmlBeanFactoryTests { assertEquals("A String", bean2.getTestString()); } - public @Test void testDoubleBooleanAutowire() { + @Test + public void testDoubleBooleanAutowire() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); DoubleBooleanConstructorBean bean = (DoubleBooleanConstructorBean) xbf.getBean("beanWithDoubleBoolean"); @@ -1436,7 +1516,8 @@ public final class XmlBeanFactoryTests { assertEquals(Boolean.FALSE, bean.boolean2); } - public @Test void testDoubleBooleanAutowireWithIndex() { + @Test + public void testDoubleBooleanAutowireWithIndex() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); DoubleBooleanConstructorBean bean = (DoubleBooleanConstructorBean) xbf.getBean("beanWithDoubleBooleanAndIndex"); @@ -1444,21 +1525,24 @@ public final class XmlBeanFactoryTests { assertEquals(Boolean.TRUE, bean.boolean2); } - public @Test void testLenientDependencyMatching() { + @Test + public void testLenientDependencyMatching() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); LenientDependencyTestBean bean = (LenientDependencyTestBean) xbf.getBean("lenientDependencyTestBean"); assertTrue(bean.tb instanceof DerivedTestBean); } - public @Test void testLenientDependencyMatchingFactoryMethod() { + @Test + public void testLenientDependencyMatchingFactoryMethod() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); LenientDependencyTestBean bean = (LenientDependencyTestBean) xbf.getBean("lenientDependencyTestBeanFactoryMethod"); assertTrue(bean.tb instanceof DerivedTestBean); } - public @Test void testNonLenientDependencyMatching() { + @Test + public void testNonLenientDependencyMatching() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBean"); @@ -1474,7 +1558,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testNonLenientDependencyMatchingFactoryMethod() { + @Test + public void testNonLenientDependencyMatchingFactoryMethod() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("lenientDependencyTestBeanFactoryMethod"); @@ -1490,7 +1575,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testJavaLangStringConstructor() { + @Test + public void testJavaLangStringConstructor() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("string"); @@ -1499,7 +1585,8 @@ public final class XmlBeanFactoryTests { assertEquals("test", str); } - public @Test void testCustomStringConstructor() { + @Test + public void testCustomStringConstructor() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("stringConstructor"); @@ -1508,7 +1595,8 @@ public final class XmlBeanFactoryTests { assertEquals("test", tb.name); } - public @Test void testPrimitiveConstructorArray() { + @Test + public void testPrimitiveConstructorArray() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArray"); @@ -1517,7 +1605,8 @@ public final class XmlBeanFactoryTests { assertEquals(1, ((int[]) bean.array)[0]); } - public @Test void testIndexedPrimitiveConstructorArray() { + @Test + public void testIndexedPrimitiveConstructorArray() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("indexedConstructorArray"); @@ -1526,7 +1615,8 @@ public final class XmlBeanFactoryTests { assertEquals(1, ((int[]) bean.array)[0]); } - public @Test void testStringConstructorArrayNoType() { + @Test + public void testStringConstructorArrayNoType() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); ConstructorArrayTestBean bean = (ConstructorArrayTestBean) xbf.getBean("constructorArrayNoType"); @@ -1534,7 +1624,8 @@ public final class XmlBeanFactoryTests { assertEquals(0, ((String[]) bean.array).length); } - public @Test void testStringConstructorArrayNoTypeNonLenient() { + @Test + public void testStringConstructorArrayNoTypeNonLenient() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(CONSTRUCTOR_ARG_CONTEXT); AbstractBeanDefinition bd = (AbstractBeanDefinition) xbf.getBeanDefinition("constructorArrayNoType"); @@ -1544,7 +1635,8 @@ public final class XmlBeanFactoryTests { assertEquals(0, ((String[]) bean.array).length); } - public @Test void testWithDuplicateName() throws Exception { + @Test + public void testWithDuplicateName() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAMES_CONTEXT); @@ -1555,7 +1647,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testWithDuplicateNameInAlias() throws Exception { + @Test + public void testWithDuplicateNameInAlias() throws Exception { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); try { new XmlBeanDefinitionReader(xbf).loadBeanDefinitions(TEST_WITH_DUP_NAME_IN_ALIAS_CONTEXT); @@ -1566,7 +1659,8 @@ public final class XmlBeanFactoryTests { } } - public @Test void testOverrideMethodByArgTypeAttribute() { + @Test + public void testOverrideMethodByArgTypeAttribute() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(DELEGATION_OVERRIDES_CONTEXT); @@ -1575,7 +1669,8 @@ public final class XmlBeanFactoryTests { assertEquals("should replace", "cba", oom.replaceMe("abc")); } - public @Test void testOverrideMethodByArgTypeElement() { + @Test + public void testOverrideMethodByArgTypeElement() { DefaultListableBeanFactory xbf = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(xbf); reader.loadBeanDefinitions(DELEGATION_OVERRIDES_CONTEXT); From fd831bc19e493e64fc5c2f823428ea07fd5f50b6 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 6 Feb 2013 14:29:06 -0800 Subject: [PATCH 188/311] Add testMany test to TestGroup.PERFORMANCE --- .../springframework/aop/framework/AbstractAopProxyTests.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java index 9fd4e9fa07..b9e0a9eaae 100644 --- a/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java +++ b/spring-context/src/test/java/org/springframework/aop/framework/AbstractAopProxyTests.java @@ -62,6 +62,8 @@ import org.springframework.aop.support.Pointcuts; import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor; import org.springframework.aop.target.HotSwappableTargetSource; import org.springframework.aop.target.SingletonTargetSource; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; import org.springframework.tests.TimeStamped; import org.springframework.tests.aop.advice.CountingAfterReturningAdvice; import org.springframework.tests.aop.advice.CountingBeforeAdvice; @@ -170,6 +172,7 @@ public abstract class AbstractAopProxyTests { */ @Test public void testManyProxies() { + Assume.group(TestGroup.PERFORMANCE); int howMany = 10000; StopWatch sw = new StopWatch(); sw.start("Create " + howMany + " proxies"); From d3969de101e018515b715f32e1e189a8fabda97c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 7 Feb 2013 14:11:24 +0100 Subject: [PATCH 189/311] Allow for ordering of mixed AspectJ before/after advices Issue: SPR-9438 --- .../AspectJPrecedenceComparator.java | 21 +++++-------------- .../AspectJPrecedenceComparatorTests.java | 11 +++++----- 2 files changed, 11 insertions(+), 21 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java index 0dd176354e..31fdb83f7d 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,6 @@ class AspectJPrecedenceComparator implements Comparator { private static final int HIGHER_PRECEDENCE = -1; private static final int SAME_PRECEDENCE = 0; private static final int LOWER_PRECEDENCE = 1; - private static final int NOT_COMPARABLE = 0; private final Comparator advisorComparator; @@ -85,21 +84,11 @@ class AspectJPrecedenceComparator implements Comparator { Advisor advisor1 = (Advisor) o1; Advisor advisor2 = (Advisor) o2; - - boolean oneOrOtherIsAfterAdvice = - (AspectJAopUtils.isAfterAdvice(advisor1) || AspectJAopUtils.isAfterAdvice(advisor2)); - boolean oneOrOtherIsBeforeAdvice = - (AspectJAopUtils.isBeforeAdvice(advisor1) || AspectJAopUtils.isBeforeAdvice(advisor2)); - if (oneOrOtherIsAfterAdvice && oneOrOtherIsBeforeAdvice) { - return NOT_COMPARABLE; - } - else { - int advisorPrecedence = this.advisorComparator.compare(advisor1, advisor2); - if (advisorPrecedence == SAME_PRECEDENCE && declaredInSameAspect(advisor1, advisor2)) { - advisorPrecedence = comparePrecedenceWithinAspect(advisor1, advisor2); - } - return advisorPrecedence; + int advisorPrecedence = this.advisorComparator.compare(advisor1, advisor2); + if (advisorPrecedence == SAME_PRECEDENCE && declaredInSameAspect(advisor1, advisor2)) { + advisorPrecedence = comparePrecedenceWithinAspect(advisor1, advisor2); } + return advisorPrecedence; } private int comparePrecedenceWithinAspect(Advisor advisor1, Advisor advisor2) { diff --git a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java index 08d95808ed..96313821a3 100644 --- a/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java +++ b/spring-aop/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJPrecedenceComparatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,11 @@ package org.springframework.aop.aspectj.autoproxy; -import static org.junit.Assert.*; - import java.lang.reflect.Method; import org.junit.Before; import org.junit.Test; + import org.springframework.aop.Advisor; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.BeforeAdvice; @@ -35,11 +34,13 @@ import org.springframework.aop.aspectj.AspectJMethodBeforeAdvice; import org.springframework.aop.aspectj.AspectJPointcutAdvisor; import org.springframework.aop.support.DefaultPointcutAdvisor; +import static org.junit.Assert.*; + /** * @author Adrian Colyer * @author Chris Beams */ -public final class AspectJPrecedenceComparatorTests { +public class AspectJPrecedenceComparatorTests { private static final int HIGH_PRECEDENCE_ADVISOR_ORDER = 100; private static final int LOW_PRECEDENCE_ADVISOR_ORDER = 200; @@ -89,7 +90,7 @@ public final class AspectJPrecedenceComparatorTests { public void testSameAspectOneOfEach() { Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect"); Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect"); - assertEquals("advisor1 and advisor2 not comparable", 0, this.comparator.compare(advisor1, advisor2)); + assertEquals("advisor1 and advisor2 not comparable", 1, this.comparator.compare(advisor1, advisor2)); } @Test From 0d66df26da0ec220b67c0ac90f57b58b28fd77b8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 7 Feb 2013 15:27:43 +0100 Subject: [PATCH 190/311] "depends-on" attribute on lang namespace element actually respected at runtime now Issue: SPR-8625 --- .../config/ScriptBeanDefinitionParser.java | 12 ++++++++- .../groovy/GroovyScriptFactoryTests.java | 27 +++++++++---------- 2 files changed, 24 insertions(+), 15 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java b/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java index 23cfe64423..f12e4004bf 100644 --- a/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java +++ b/spring-context/src/main/java/org/springframework/scripting/config/ScriptBeanDefinitionParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionDefaults; import org.springframework.beans.factory.support.GenericBeanDefinition; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; +import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.beans.factory.xml.XmlReaderContext; import org.springframework.scripting.support.ScriptFactoryPostProcessor; @@ -64,6 +65,8 @@ class ScriptBeanDefinitionParser extends AbstractBeanDefinitionParser { private static final String DEPENDENCY_CHECK_ATTRIBUTE = "dependency-check"; + private static final String DEPENDS_ON_ATTRIBUTE = "depends-on"; + private static final String INIT_METHOD_ATTRIBUTE = "init-method"; private static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method"; @@ -138,6 +141,13 @@ class ScriptBeanDefinitionParser extends AbstractBeanDefinitionParser { String dependencyCheck = element.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE); bd.setDependencyCheck(parserContext.getDelegate().getDependencyCheck(dependencyCheck)); + // Parse depends-on list of bean names. + String dependsOn = element.getAttribute(DEPENDS_ON_ATTRIBUTE); + if (StringUtils.hasLength(dependsOn)) { + bd.setDependsOn(StringUtils.tokenizeToStringArray( + dependsOn, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS)); + } + // Retrieve the defaults for bean definitions within this parser context BeanDefinitionDefaults beanDefinitionDefaults = parserContext.getDelegate().getBeanDefinitionDefaults(); diff --git a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java index 96d3db7fdf..cca1625d3d 100644 --- a/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/scripting/groovy/GroovyScriptFactoryTests.java @@ -16,31 +16,22 @@ package org.springframework.scripting.groovy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; -import groovy.lang.DelegatingMetaClass; -import groovy.lang.GroovyObject; - import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Map; +import groovy.lang.DelegatingMetaClass; +import groovy.lang.GroovyObject; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; + import org.springframework.aop.support.AopUtils; import org.springframework.aop.target.dynamic.Refreshable; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.UnsatisfiedDependencyException; +import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.NestedRuntimeException; @@ -56,6 +47,12 @@ import org.springframework.scripting.support.ScriptFactoryPostProcessor; import org.springframework.stereotype.Component; import org.springframework.tests.Assume; import org.springframework.tests.TestGroup; +import org.springframework.tests.sample.beans.TestBean; +import org.springframework.util.ObjectUtils; + +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.mock; /** * @author Rob Harrop @@ -350,7 +347,9 @@ public class GroovyScriptFactoryTests { @Test public void testInlineScriptFromTag() throws Exception { - ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass()); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass()); + BeanDefinition bd = ctx.getBeanFactory().getBeanDefinition("calculator"); + assertTrue(ObjectUtils.containsElement(bd.getDependsOn(), "messenger")); Calculator calculator = (Calculator) ctx.getBean("calculator"); assertNotNull(calculator); assertFalse(calculator instanceof Refreshable); From 9ffbee332c242cb52310dad6b8653910e415bb16 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 7 Feb 2013 15:28:25 +0100 Subject: [PATCH 191/311] Fixed documentation for "depends-on" attribute --- .../scripting/config/spring-lang-2.5.xsd | 14 +++++++------- .../scripting/config/spring-lang-3.0.xsd | 14 +++++++------- .../scripting/config/spring-lang-3.1.xsd | 12 ++++++------ .../scripting/config/spring-lang-3.2.xsd | 12 ++++++------ 4 files changed, 26 insertions(+), 26 deletions(-) diff --git a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-2.5.xsd b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-2.5.xsd index ac7c317418..e628850389 100644 --- a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-2.5.xsd +++ b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-2.5.xsd @@ -82,7 +82,7 @@ @@ -137,13 +137,13 @@ diff --git a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.0.xsd b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.0.xsd index 574fb05b43..5a34213de7 100644 --- a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.0.xsd +++ b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.0.xsd @@ -82,7 +82,7 @@ @@ -127,13 +127,13 @@ diff --git a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.1.xsd b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.1.xsd index edce1324f4..54ae90e9e1 100644 --- a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.1.xsd +++ b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.1.xsd @@ -147,13 +147,13 @@ diff --git a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.2.xsd b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.2.xsd index 34e9775fe2..5bd66ded43 100644 --- a/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.2.xsd +++ b/spring-context/src/main/resources/org/springframework/scripting/config/spring-lang-3.2.xsd @@ -147,13 +147,13 @@ From e3c83bb7699f50641bdf9b673c9dc64b176ae399 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 7 Feb 2013 15:36:19 +0100 Subject: [PATCH 192/311] Minor javadoc and source layout polishing --- .../xml/BeanDefinitionDocumentReader.java | 27 ++++++++++--------- .../DefaultBeanDefinitionDocumentReader.java | 23 ++++++++-------- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java b/spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java index 37ef1b4090..ffe9d294d9 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionDocumentReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,11 @@ package org.springframework.beans.factory.xml; +import org.w3c.dom.Document; + import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.core.env.Environment; -import org.w3c.dom.Document; - /** * SPI for parsing an XML document that contains Spring bean definitions. * Used by XmlBeanDefinitionReader for actually parsing a DOM document. @@ -38,20 +38,21 @@ import org.w3c.dom.Document; public interface BeanDefinitionDocumentReader { /** - * Read bean definitions from the given DOM document, - * and register them with the given bean factory. + * Set the Environment to use when reading bean definitions. + *

Used for evaluating profile information to determine whether a + * {@code } document/element should be included or ignored. + */ + void setEnvironment(Environment environment); + + /** + * Read bean definitions from the given DOM document and + * register them with the registry in the given reader context. * @param doc the DOM document - * @param readerContext the current context of the reader. Includes the resource being parsed + * @param readerContext the current context of the reader + * (includes the target registry and the resource being parsed) * @throws BeanDefinitionStoreException in case of parsing errors */ void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) throws BeanDefinitionStoreException; - /** - * Set the Environment to use when reading bean definitions. Used for evaluating - * profile information to determine whether a {@code } document/element should - * be included or omitted. - */ - void setEnvironment(Environment environment); - } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java b/spring-beans/src/main/java/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java index 9900aa1651..a422d5b4fc 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/xml/DefaultBeanDefinitionDocumentReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,16 +72,15 @@ public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocume public static final String RESOURCE_ATTRIBUTE = "resource"; - /** @see org.springframework.context.annotation.Profile */ public static final String PROFILE_ATTRIBUTE = "profile"; protected final Log logger = LogFactory.getLog(getClass()); - private XmlReaderContext readerContext; - private Environment environment; + private XmlReaderContext readerContext; + private BeanDefinitionParserDelegate delegate; @@ -104,13 +103,12 @@ public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocume */ public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { this.readerContext = readerContext; - logger.debug("Loading bean definitions"); Element root = doc.getDocumentElement(); - doRegisterBeanDefinitions(root); } + /** * Register each bean definition within the given root {@code } element. * @throws IllegalStateException if {@code elements will cause recursion in this method. In + // Any nested elements will cause recursion in this method. In // order to propagate and preserve default-* attributes correctly, // keep track of the current (parent) delegate, which may be null. Create // the new (child) delegate with a reference to the parent for fallback purposes, // then ultimately reset this.delegate back to its original (parent) reference. // this behavior emulates a stack of delegates without actually necessitating one. BeanDefinitionParserDelegate parent = this.delegate; - this.delegate = createHelper(readerContext, root, parent); + this.delegate = createHelper(this.readerContext, root, parent); preProcessXml(root); parseBeanDefinitions(root, this.delegate); @@ -143,7 +142,9 @@ public class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocume this.delegate = parent; } - protected BeanDefinitionParserDelegate createHelper(XmlReaderContext readerContext, Element root, BeanDefinitionParserDelegate parentDelegate) { + protected BeanDefinitionParserDelegate createHelper( + XmlReaderContext readerContext, Element root, BeanDefinitionParserDelegate parentDelegate) { + BeanDefinitionParserDelegate delegate = new BeanDefinitionParserDelegate(readerContext, environment); delegate.initDefaults(root, parentDelegate); return delegate; From 2aaa66f86b10e8146bae9518e4139dd33913b1f7 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 7 Feb 2013 22:02:40 +0100 Subject: [PATCH 193/311] Allow for ordering of mixed AspectJ before/after advices Issue: SPR-9438 --- .../AspectJAwareAdvisorAutoProxyCreator.java | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java index dbfcbd380e..271d961088 100644 --- a/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java +++ b/spring-aop/src/main/java/org/springframework/aop/aspectj/autoproxy/AspectJAwareAdvisorAutoProxyCreator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,8 @@ package org.springframework.aop.aspectj.autoproxy; +import java.util.ArrayList; import java.util.Comparator; -import java.util.LinkedList; import java.util.List; import org.aopalliance.aop.Advice; @@ -67,29 +67,24 @@ public class AspectJAwareAdvisorAutoProxyCreator extends AbstractAdvisorAutoProx @Override @SuppressWarnings("unchecked") protected List sortAdvisors(List advisors) { - // build list for sorting List partiallyComparableAdvisors = - new LinkedList(); + new ArrayList(advisors.size()); for (Advisor element : advisors) { partiallyComparableAdvisors.add( new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR)); } - - // sort it List sorted = PartialOrder.sort(partiallyComparableAdvisors); - if (sorted == null) { - // TODO: work harder to give a better error message here. - throw new IllegalArgumentException("Advice precedence circularity error"); + if (sorted != null) { + List result = new ArrayList(advisors.size()); + for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) { + result.add(pcAdvisor.getAdvisor()); + } + return result; } - - // extract results again - List result = new LinkedList(); - for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) { - result.add(pcAdvisor.getAdvisor()); + else { + return super.sortAdvisors(advisors); } - - return result; } /** From 7bbb4ec7aff9ca171f2d34f747d7e0d96a6ce1b0 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 7 Feb 2013 13:35:31 -0800 Subject: [PATCH 194/311] Fix Assert.instanceOf exception message Update the exception message used when Assert.instanceOf fails such that it expects the provided message to end with '.'. This reverts commit 5874383ef081bb52a872dd49d63e5b542fbf20ca which caused the implementation to be at odds with the JavaDoc and the previous release. The updated code also has the benefit of protecting against a null message. Issue: SPR-10269 --- .../java/org/springframework/util/Assert.java | 7 +++--- .../org/springframework/util/AssertTests.java | 23 ++++++++++++++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/Assert.java b/spring-core/src/main/java/org/springframework/util/Assert.java index 05c1c4babe..193d461a05 100644 --- a/spring-core/src/main/java/org/springframework/util/Assert.java +++ b/spring-core/src/main/java/org/springframework/util/Assert.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -334,8 +334,9 @@ public abstract class Assert { public static void isInstanceOf(Class type, Object obj, String message) { notNull(type, "Type to check against must not be null"); if (!type.isInstance(obj)) { - throw new IllegalArgumentException(message + - ". Object of class [" + (obj != null ? obj.getClass().getName() : "null") + + throw new IllegalArgumentException( + (StringUtils.hasLength(message) ? message + " " : "") + + "Object of class [" + (obj != null ? obj.getClass().getName() : "null") + "] must be an instance of " + type); } } diff --git a/spring-core/src/test/java/org/springframework/util/AssertTests.java b/spring-core/src/test/java/org/springframework/util/AssertTests.java index 744b492f61..0dfe86f1dc 100644 --- a/spring-core/src/test/java/org/springframework/util/AssertTests.java +++ b/spring-core/src/test/java/org/springframework/util/AssertTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,9 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; /** * Unit tests for the {@link Assert} class. @@ -36,6 +38,9 @@ import org.junit.Test; */ public class AssertTests { + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Test(expected = IllegalArgumentException.class) public void instanceOf() { final Set set = new HashSet(); @@ -43,6 +48,22 @@ public class AssertTests { Assert.isInstanceOf(HashMap.class, set); } + @Test + public void instanceOfNoMessage() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Object of class [java.lang.Object] must be an instance " + + "of interface java.util.Set"); + Assert.isInstanceOf(Set.class, new Object(), null); + } + + @Test + public void instanceOfMessage() throws Exception { + thrown.expect(IllegalArgumentException.class); + thrown.expectMessage("Custom message. Object of class [java.lang.Object] must " + + "be an instance of interface java.util.Set"); + Assert.isInstanceOf(Set.class, new Object(), "Custom message."); + } + @Test public void isNullDoesNotThrowExceptionIfArgumentIsNullWithMessage() { Assert.isNull(null, "Bla"); From b3c9a11bd1141f644859eb0023f4d6f4ae0c9910 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Thu, 7 Feb 2013 23:22:30 +0100 Subject: [PATCH 195/311] Folded a FactoryBean-specific check into predictBeanType now This change means that we effectively revert SPR-8954's code change in favor of the isFactoryBean implementation simply relying on predictBeanType to sort it out, filtering a post-processed predictedType for FactoryBean applicability. Issue: SPR-9177 Issue: SPR-9143 --- .../AbstractAutowireCapableBeanFactory.java | 9 +- .../factory/support/AbstractBeanFactory.java | 14 +- .../beans/factory/support/Spr8954Tests.java | 31 +++- .../ConfigurationClassSpr8954Tests.java | 132 ++++++++++++++++++ 4 files changed, 173 insertions(+), 13 deletions(-) create mode 100644 spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassSpr8954Tests.java diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index c112676ea1..9d11eeb520 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -586,9 +586,10 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; - Class processedType = ibp.predictBeanType(beanClass, beanName); - if (processedType != null) { - return processedType; + Class predictedType = ibp.predictBeanType(beanClass, beanName); + if (predictedType != null && (typesToMatch.length > 1 || + !FactoryBean.class.equals(typesToMatch[0]) || FactoryBean.class.isAssignableFrom(predictedType))) { + return predictedType; } } } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java index 6ec60e6e61..9e97ba2faf 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -497,18 +497,21 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp // Retrieve corresponding bean definition. RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); + Class[] typesToMatch = (FactoryBean.class.equals(typeToMatch) ? + new Class[] {typeToMatch} : new Class[] {FactoryBean.class, typeToMatch}); + // Check decorated bean definition, if any: We assume it'll be easier // to determine the decorated bean's type than the proxy's type. BeanDefinitionHolder dbd = mbd.getDecoratedDefinition(); if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) { RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd); - Class targetClass = predictBeanType(dbd.getBeanName(), tbd, FactoryBean.class, typeToMatch); + Class targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch); if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) { return typeToMatch.isAssignableFrom(targetClass); } } - Class beanClass = predictBeanType(beanName, mbd, FactoryBean.class, typeToMatch); + Class beanClass = predictBeanType(beanName, mbd, typesToMatch); if (beanClass == null) { return false; } @@ -1332,9 +1335,8 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp * @param mbd the corresponding bean definition */ protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) { - Class predictedType = predictBeanType(beanName, mbd, FactoryBean.class); - return (predictedType != null && FactoryBean.class.isAssignableFrom(predictedType)) || - (mbd.hasBeanClass() && FactoryBean.class.isAssignableFrom(mbd.getBeanClass())); + Class beanClass = predictBeanType(beanName, mbd, FactoryBean.class); + return (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)); } /** diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java index 5c1368c461..411f538045 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/Spr8954Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,8 @@ import static org.junit.Assert.*; import java.util.Map; import org.junit.Test; + +import org.springframework.beans.BeansException; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -49,6 +51,8 @@ public class Spr8954Tests { assertThat(bf.getBean("foo"), instanceOf(Foo.class)); assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); + assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + @SuppressWarnings("rawtypes") Map fbBeans = bf.getBeansOfType(FactoryBean.class); assertThat(1, equalTo(fbBeans.size())); @@ -59,6 +63,25 @@ public class Spr8954Tests { assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); } + @Test + public void findsBeansByTypeIfNotInstantiated() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + bf.registerBeanDefinition("foo", new RootBeanDefinition(FooFactoryBean.class)); + bf.addBeanPostProcessor(new PredictingBPP()); + + assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + + @SuppressWarnings("rawtypes") + Map fbBeans = bf.getBeansOfType(FactoryBean.class); + assertThat(1, equalTo(fbBeans.size())); + assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); + + Map aiBeans = bf.getBeansOfType(AnInterface.class); + assertThat(1, equalTo(aiBeans.size())); + assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); + } + + static class FooFactoryBean implements FactoryBean, AnInterface { @Override @@ -84,7 +107,9 @@ public class Spr8954Tests { } interface PredictedType { + } + static class PredictedTypeImpl implements PredictedType { } static class PredictingBPP extends InstantiationAwareBeanPostProcessorAdapter { @@ -92,8 +117,8 @@ public class Spr8954Tests { @Override public Class predictBeanType(Class beanClass, String beanName) { return FactoryBean.class.isAssignableFrom(beanClass) ? - PredictedType.class : - super.predictBeanType(beanClass, beanName); + PredictedType.class : null; } } + } diff --git a/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassSpr8954Tests.java b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassSpr8954Tests.java new file mode 100644 index 0000000000..1a7a5b1b33 --- /dev/null +++ b/spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassSpr8954Tests.java @@ -0,0 +1,132 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.context.annotation; + +import java.util.Map; + +import org.junit.Test; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.beans.factory.support.RootBeanDefinition; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +/** + * Unit tests for SPR-8954, in which a custom {@link InstantiationAwareBeanPostProcessor} + * forces the predicted type of a FactoryBean, effectively preventing retrieval of the + * bean from calls to #getBeansOfType(FactoryBean.class). The implementation of + * {@link AbstractBeanFactory#isFactoryBean(String, RootBeanDefinition)} now ensures + * that not only the predicted bean type is considered, but also the original bean + * definition's beanClass. + * + * @author Chris Beams + * @author Oliver Gierke + */ +public class ConfigurationClassSpr8954Tests { + + @Test + public void repro() { + AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext(); + bf.registerBeanDefinition("fooConfig", new RootBeanDefinition(FooConfig.class)); + bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); + bf.refresh(); + + assertThat(bf.getBean("foo"), instanceOf(Foo.class)); + assertThat(bf.getBean("&foo"), instanceOf(FooFactoryBean.class)); + + assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + + @SuppressWarnings("rawtypes") + Map fbBeans = bf.getBeansOfType(FactoryBean.class); + assertThat(1, equalTo(fbBeans.size())); + assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); + + Map aiBeans = bf.getBeansOfType(AnInterface.class); + assertThat(1, equalTo(aiBeans.size())); + assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); + } + + @Test + public void findsBeansByTypeIfNotInstantiated() { + AnnotationConfigApplicationContext bf = new AnnotationConfigApplicationContext(); + bf.registerBeanDefinition("fooConfig", new RootBeanDefinition(FooConfig.class)); + bf.getBeanFactory().addBeanPostProcessor(new PredictingBPP()); + bf.refresh(); + + assertThat(bf.isTypeMatch("&foo", FactoryBean.class), is(true)); + + @SuppressWarnings("rawtypes") + Map fbBeans = bf.getBeansOfType(FactoryBean.class); + assertThat(1, equalTo(fbBeans.size())); + assertThat("&foo", equalTo(fbBeans.keySet().iterator().next())); + + Map aiBeans = bf.getBeansOfType(AnInterface.class); + assertThat(1, equalTo(aiBeans.size())); + assertThat("&foo", equalTo(aiBeans.keySet().iterator().next())); + } + + + static class FooConfig { + + @Bean FooFactoryBean foo() { + return new FooFactoryBean(); + } + } + + static class FooFactoryBean implements FactoryBean, AnInterface { + + @Override + public Foo getObject() throws Exception { + return new Foo(); + } + + @Override + public Class getObjectType() { + return Foo.class; + } + + @Override + public boolean isSingleton() { + return true; + } + } + + interface AnInterface { + } + + static class Foo { + } + + interface PredictedType { + } + + static class PredictedTypeImpl implements PredictedType { + } + + static class PredictingBPP extends InstantiationAwareBeanPostProcessorAdapter { + + @Override + public Class predictBeanType(Class beanClass, String beanName) { + return FactoryBean.class.isAssignableFrom(beanClass) ? + PredictedType.class : null; + } + } + +} From 9255d3038ff4bfbc7530eec74e551613ebd03725 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 00:58:39 +0100 Subject: [PATCH 196/311] @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support Issue: SPR-8067 --- .../scheduling/annotation/Scheduled.java | 27 +++- .../ScheduledAnnotationBeanPostProcessor.java | 152 ++++++++++++------ .../scheduling/config/IntervalTask.java | 9 +- .../support/CronSequenceGenerator.java | 43 +++-- ...duledAnnotationBeanPostProcessorTests.java | 114 ++++++++++--- 5 files changed, 255 insertions(+), 90 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java index dea788ce08..383e4adc5d 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java +++ b/spring-context/src/main/java/org/springframework/scheduling/annotation/Scheduled.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,18 +64,41 @@ public @interface Scheduled { */ long fixedDelay() default -1; + /** + * Execute the annotated method with a fixed period between the end + * of the last invocation and the start of the next. + * @return the delay in milliseconds as a String value, e.g. a placeholder + * @since 3.2.2 + */ + String fixedDelayString() default ""; + /** * Execute the annotated method with a fixed period between invocations. * @return the period in milliseconds */ long fixedRate() default -1; + /** + * Execute the annotated method with a fixed period between invocations. + * @return the period in milliseconds as a String value, e.g. a placeholder + * @since 3.2.2 + */ + String fixedRateString() default ""; + /** * Number of milliseconds to delay before the first execution of a * {@link #fixedRate()} or {@link #fixedDelay()} task. * @return the initial delay in milliseconds * @since 3.2 */ - long initialDelay() default 0; + long initialDelay() default -1; + + /** + * Number of milliseconds to delay before the first execution of a + * {@link #fixedRate()} or {@link #fixedDelay()} task. + * @return the initial delay in milliseconds as a String value, e.g. a placeholder + * @since 3.2.2 + */ + String initialDelayString() default ""; } diff --git a/spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java index f5f236d2f9..754afc5bd6 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java +++ b/spring-context/src/main/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.scheduling.annotation; import java.lang.reflect.Method; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; @@ -111,53 +110,115 @@ public class ScheduledAnnotationBeanPostProcessor public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { Scheduled annotation = AnnotationUtils.getAnnotation(method, Scheduled.class); if (annotation != null) { - Assert.isTrue(void.class.equals(method.getReturnType()), - "Only void-returning methods may be annotated with @Scheduled."); - Assert.isTrue(method.getParameterTypes().length == 0, - "Only no-arg methods may be annotated with @Scheduled."); - if (AopUtils.isJdkDynamicProxy(bean)) { - try { - // found a @Scheduled method on the target class for this JDK proxy -> is it - // also present on the proxy itself? - method = bean.getClass().getMethod(method.getName(), method.getParameterTypes()); + try { + Assert.isTrue(void.class.equals(method.getReturnType()), + "Only void-returning methods may be annotated with @Scheduled"); + Assert.isTrue(method.getParameterTypes().length == 0, + "Only no-arg methods may be annotated with @Scheduled"); + if (AopUtils.isJdkDynamicProxy(bean)) { + try { + // found a @Scheduled method on the target class for this JDK proxy -> is it + // also present on the proxy itself? + method = bean.getClass().getMethod(method.getName(), method.getParameterTypes()); + } + catch (SecurityException ex) { + ReflectionUtils.handleReflectionException(ex); + } + catch (NoSuchMethodException ex) { + throw new IllegalStateException(String.format( + "@Scheduled method '%s' found on bean target class '%s', " + + "but not found in any interface(s) for bean JDK proxy. Either " + + "pull the method up to an interface or switch to subclass (CGLIB) " + + "proxies by setting proxy-target-class/proxyTargetClass " + + "attribute to 'true'", method.getName(), targetClass.getSimpleName())); + } } - catch (SecurityException ex) { - ReflectionUtils.handleReflectionException(ex); + Runnable runnable = new ScheduledMethodRunnable(bean, method); + boolean processedSchedule = false; + String errorMessage = "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required"; + // Determine initial delay + long initialDelay = annotation.initialDelay(); + String initialDelayString = annotation.initialDelayString(); + if (!"".equals(initialDelayString)) { + Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both"); + if (embeddedValueResolver != null) { + initialDelayString = embeddedValueResolver.resolveStringValue(initialDelayString); + } + try { + initialDelay = Integer.parseInt(initialDelayString); + } + catch (NumberFormatException ex) { + throw new IllegalArgumentException( + "Invalid initialDelayString value \"" + initialDelayString + "\" - cannot parse into integer"); + } } - catch (NoSuchMethodException ex) { - throw new IllegalStateException(String.format( - "@Scheduled method '%s' found on bean target class '%s', " + - "but not found in any interface(s) for bean JDK proxy. Either " + - "pull the method up to an interface or switch to subclass (CGLIB) " + - "proxies by setting proxy-target-class/proxyTargetClass " + - "attribute to 'true'", method.getName(), targetClass.getSimpleName())); + // Check cron expression + String cron = annotation.cron(); + if (!"".equals(cron)) { + Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers"); + processedSchedule = true; + if (embeddedValueResolver != null) { + cron = embeddedValueResolver.resolveStringValue(cron); + } + registrar.addCronTask(new CronTask(runnable, cron)); } - } - Runnable runnable = new ScheduledMethodRunnable(bean, method); - boolean processedSchedule = false; - String errorMessage = "Exactly one of the 'cron', 'fixedDelay', or 'fixedRate' attributes is required."; - String cron = annotation.cron(); - if (!"".equals(cron)) { - processedSchedule = true; - if (embeddedValueResolver != null) { - cron = embeddedValueResolver.resolveStringValue(cron); + // At this point we don't need to differentiate between initial delay set or not anymore + if (initialDelay < 0) { + initialDelay = 0; } - registrar.addCronTask(new CronTask(runnable, cron)); + // Check fixed delay + long fixedDelay = annotation.fixedDelay(); + if (fixedDelay >= 0) { + Assert.isTrue(!processedSchedule, errorMessage); + processedSchedule = true; + registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay)); + } + String fixedDelayString = annotation.fixedDelayString(); + if (!"".equals(fixedDelayString)) { + Assert.isTrue(!processedSchedule, errorMessage); + processedSchedule = true; + if (embeddedValueResolver != null) { + fixedDelayString = embeddedValueResolver.resolveStringValue(fixedDelayString); + } + try { + fixedDelay = Integer.parseInt(fixedDelayString); + } + catch (NumberFormatException ex) { + throw new IllegalArgumentException( + "Invalid fixedDelayString value \"" + fixedDelayString + "\" - cannot parse into integer"); + } + registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay)); + } + // Check fixed rate + long fixedRate = annotation.fixedRate(); + if (fixedRate >= 0) { + Assert.isTrue(!processedSchedule, errorMessage); + processedSchedule = true; + registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay)); + } + String fixedRateString = annotation.fixedRateString(); + if (!"".equals(fixedRateString)) { + Assert.isTrue(!processedSchedule, errorMessage); + processedSchedule = true; + if (embeddedValueResolver != null) { + fixedRateString = embeddedValueResolver.resolveStringValue(fixedRateString); + } + try { + fixedRate = Integer.parseInt(fixedRateString); + } + catch (NumberFormatException ex) { + throw new IllegalArgumentException( + "Invalid fixedRateString value \"" + fixedRateString + "\" - cannot parse into integer"); + } + registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay)); + } + // Check whether we had any attribute set + Assert.isTrue(processedSchedule, errorMessage); } - long initialDelay = annotation.initialDelay(); - long fixedDelay = annotation.fixedDelay(); - if (fixedDelay >= 0) { - Assert.isTrue(!processedSchedule, errorMessage); - processedSchedule = true; - registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay)); + catch (IllegalArgumentException ex) { + throw new IllegalStateException( + "Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage()); } - long fixedRate = annotation.fixedRate(); - if (fixedRate >= 0) { - Assert.isTrue(!processedSchedule, errorMessage); - processedSchedule = true; - registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay)); - } - Assert.isTrue(processedSchedule, errorMessage); } } }); @@ -168,18 +229,14 @@ public class ScheduledAnnotationBeanPostProcessor if (event.getApplicationContext() != this.applicationContext) { return; } - Map configurers = this.applicationContext.getBeansOfType(SchedulingConfigurer.class); - if (this.scheduler != null) { this.registrar.setScheduler(this.scheduler); } - for (SchedulingConfigurer configurer : configurers.values()) { configurer.configureTasks(this.registrar); } - if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) { Map schedulers = new HashMap(); schedulers.putAll(applicationContext.getBeansOfType(TaskScheduler.class)); @@ -199,7 +256,6 @@ public class ScheduledAnnotationBeanPostProcessor "configureTasks() callback. Found the following beans: " + schedulers.keySet()); } } - this.registrar.afterPropertiesSet(); } diff --git a/spring-context/src/main/java/org/springframework/scheduling/config/IntervalTask.java b/spring-context/src/main/java/org/springframework/scheduling/config/IntervalTask.java index 4b39927e8f..567f9fdbfe 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/config/IntervalTask.java +++ b/spring-context/src/main/java/org/springframework/scheduling/config/IntervalTask.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -44,8 +44,8 @@ public class IntervalTask extends Task { */ public IntervalTask(Runnable runnable, long interval, long initialDelay) { super(runnable); - this.initialDelay = initialDelay; this.interval = interval; + this.initialDelay = initialDelay; } /** @@ -59,10 +59,11 @@ public class IntervalTask extends Task { public long getInterval() { - return interval; + return this.interval; } public long getInitialDelay() { - return initialDelay; + return this.initialDelay; } + } diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java index b3530ebf78..5f5cf4e280 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -69,6 +69,7 @@ public class CronSequenceGenerator { private final TimeZone timeZone; + /** * Construct a {@link CronSequenceGenerator} from the pattern provided. * @param expression a space-separated list of time fields @@ -81,6 +82,7 @@ public class CronSequenceGenerator { parse(expression); } + /** * Get the next {@link Date} in the sequence matching the Cron pattern and * after the value provided. The return value will have a whole number of @@ -135,7 +137,8 @@ public class CronSequenceGenerator { int updateMinute = findNext(this.minutes, minute, calendar, Calendar.MINUTE, Calendar.HOUR_OF_DAY, resets); if (minute == updateMinute) { resets.add(Calendar.MINUTE); - } else { + } + else { doNext(calendar, dot); } @@ -143,7 +146,8 @@ public class CronSequenceGenerator { int updateHour = findNext(this.hours, hour, calendar, Calendar.HOUR_OF_DAY, Calendar.DAY_OF_WEEK, resets); if (hour == updateHour) { resets.add(Calendar.HOUR_OF_DAY); - } else { + } + else { doNext(calendar, dot); } @@ -152,7 +156,8 @@ public class CronSequenceGenerator { int updateDayOfMonth = findNextDay(calendar, this.daysOfMonth, dayOfMonth, daysOfWeek, dayOfWeek, resets); if (dayOfMonth == updateDayOfMonth) { resets.add(Calendar.DAY_OF_MONTH); - } else { + } + else { doNext(calendar, dot); } @@ -160,7 +165,8 @@ public class CronSequenceGenerator { int updateMonth = findNext(this.months, month, calendar, Calendar.MONTH, Calendar.YEAR, resets); if (month != updateMonth) { if (calendar.get(Calendar.YEAR) - dot > 4) { - throw new IllegalStateException("Invalid cron expression led to runaway search for next trigger"); + throw new IllegalArgumentException("Invalid cron expression \"" + this.expression + + "\" led to runaway search for next trigger"); } doNext(calendar, dot); } @@ -181,7 +187,7 @@ public class CronSequenceGenerator { reset(calendar, resets); } if (count >= max) { - throw new IllegalStateException("Overflow in day for expression=" + this.expression); + throw new IllegalArgumentException("Overflow in day for expression \"" + this.expression + "\""); } return dayOfMonth; } @@ -222,7 +228,8 @@ public class CronSequenceGenerator { } } - // Parsing logic invoked by the constructor. + + // Parsing logic invoked by the constructor /** * Parse the given pattern expression. @@ -230,8 +237,8 @@ public class CronSequenceGenerator { private void parse(String expression) throws IllegalArgumentException { String[] fields = StringUtils.tokenizeToStringArray(expression, " "); if (fields.length != 6) { - throw new IllegalArgumentException(String.format("" - + "cron expression must consist of 6 fields (found %d in %s)", fields.length, expression)); + throw new IllegalArgumentException(String.format( + "Cron expression must consist of 6 fields (found %d in \"%s\")", fields.length, expression)); } setNumberHits(this.seconds, fields[0], 0, 60); setNumberHits(this.minutes, fields[1], 0, 60); @@ -296,10 +303,12 @@ public class CronSequenceGenerator { // Not an incrementer so it must be a range (possibly empty) int[] range = getRange(field, min, max); bits.set(range[0], range[1] + 1); - } else { + } + else { String[] split = StringUtils.delimitedListToStringArray(field, "/"); if (split.length > 2) { - throw new IllegalArgumentException("Incrementer has more than two fields: " + field); + throw new IllegalArgumentException("Incrementer has more than two fields: '" + + field + "' in expression \"" + this.expression + "\""); } int[] range = getRange(split[0], min, max); if (!split[0].contains("-")) { @@ -322,19 +331,23 @@ public class CronSequenceGenerator { } if (!field.contains("-")) { result[0] = result[1] = Integer.valueOf(field); - } else { + } + else { String[] split = StringUtils.delimitedListToStringArray(field, "-"); if (split.length > 2) { - throw new IllegalArgumentException("Range has more than two fields: " + field); + throw new IllegalArgumentException("Range has more than two fields: '" + + field + "' in expression \"" + this.expression + "\""); } result[0] = Integer.valueOf(split[0]); result[1] = Integer.valueOf(split[1]); } if (result[0] >= max || result[1] >= max) { - throw new IllegalArgumentException("Range exceeds maximum (" + max + "): " + field); + throw new IllegalArgumentException("Range exceeds maximum (" + max + "): '" + + field + "' in expression \"" + this.expression + "\""); } if (result[0] < min || result[1] < min) { - throw new IllegalArgumentException("Range less than minimum (" + min + "): " + field); + throw new IllegalArgumentException("Range less than minimum (" + min + "): '" + + field + "' in expression \"" + this.expression + "\""); } return result; } diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java index e100da3d47..91bf0f697e 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Properties; import org.junit.Test; + import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.config.BeanDefinition; @@ -52,8 +53,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { public void fixedDelayTask() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); - BeanDefinition targetDefinition = new RootBeanDefinition( - ScheduledAnnotationBeanPostProcessorTests.FixedDelayTestBean.class); + BeanDefinition targetDefinition = new RootBeanDefinition(FixedDelayTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); @@ -106,8 +106,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { public void fixedRateTaskWithInitialDelay() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); - BeanDefinition targetDefinition = new RootBeanDefinition( - ScheduledAnnotationBeanPostProcessorTests.FixedRateWithInitialDelayTestBean.class); + BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateWithInitialDelayTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); @@ -162,8 +161,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { public void metaAnnotationWithFixedRate() { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); - BeanDefinition targetDefinition = new RootBeanDefinition( - ScheduledAnnotationBeanPostProcessorTests.MetaAnnotationFixedRateTestBean.class); + BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationFixedRateTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); @@ -211,7 +209,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { } @Test - public void propertyPlaceholderWithCronExpression() { + public void propertyPlaceholderWithCron() { String businessHoursCronExpression = "0 0 9-17 * * MON-FRI"; StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); @@ -219,8 +217,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { Properties properties = new Properties(); properties.setProperty("schedules.businessHours", businessHoursCronExpression); placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties); - BeanDefinition targetDefinition = new RootBeanDefinition( - ScheduledAnnotationBeanPostProcessorTests.PropertyPlaceholderTestBean.class); + BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithCronTestBean.class); context.registerBeanDefinition("placeholder", placeholderDefinition); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); @@ -242,6 +239,70 @@ public class ScheduledAnnotationBeanPostProcessorTests { assertEquals(businessHoursCronExpression, task.getExpression()); } + @Test + public void propertyPlaceholderWithFixedDelay() { + StaticApplicationContext context = new StaticApplicationContext(); + BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); + BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); + Properties properties = new Properties(); + properties.setProperty("fixedDelay", "5000"); + properties.setProperty("initialDelay", "1000"); + placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties); + BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedDelayTestBean.class); + context.registerBeanDefinition("placeholder", placeholderDefinition); + context.registerBeanDefinition("postProcessor", processorDefinition); + context.registerBeanDefinition("target", targetDefinition); + context.refresh(); + Object postProcessor = context.getBean("postProcessor"); + Object target = context.getBean("target"); + ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) + new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); + @SuppressWarnings("unchecked") + List fixedDelayTasks = (List) + new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks"); + assertEquals(1, fixedDelayTasks.size()); + IntervalTask task = fixedDelayTasks.get(0); + ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); + Object targetObject = runnable.getTarget(); + Method targetMethod = runnable.getMethod(); + assertEquals(target, targetObject); + assertEquals("fixedDelay", targetMethod.getName()); + assertEquals(1000L, task.getInitialDelay()); + assertEquals(5000L, task.getInterval()); + } + + @Test + public void propertyPlaceholderWithFixedRate() { + StaticApplicationContext context = new StaticApplicationContext(); + BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); + BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); + Properties properties = new Properties(); + properties.setProperty("fixedRate", "3000"); + properties.setProperty("initialDelay", "1000"); + placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties); + BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedRateTestBean.class); + context.registerBeanDefinition("placeholder", placeholderDefinition); + context.registerBeanDefinition("postProcessor", processorDefinition); + context.registerBeanDefinition("target", targetDefinition); + context.refresh(); + Object postProcessor = context.getBean("postProcessor"); + Object target = context.getBean("target"); + ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) + new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); + @SuppressWarnings("unchecked") + List fixedRateTasks = (List) + new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); + assertEquals(1, fixedRateTasks.size()); + IntervalTask task = fixedRateTasks.get(0); + ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); + Object targetObject = runnable.getTarget(); + Method targetMethod = runnable.getMethod(); + assertEquals(target, targetObject); + assertEquals("fixedRate", targetMethod.getName()); + assertEquals(1000L, task.getInitialDelay()); + assertEquals(3000L, task.getInterval()); + } + @Test public void propertyPlaceholderForMetaAnnotation() { String businessHoursCronExpression = "0 0 9-17 * * MON-FRI"; @@ -285,7 +346,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { context.refresh(); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = BeanCreationException.class) public void invalidCron() throws Throwable { StaticApplicationContext context = new StaticApplicationContext(); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); @@ -293,12 +354,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { ScheduledAnnotationBeanPostProcessorTests.InvalidCronTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); - try { - context.refresh(); - fail("expected exception"); - } catch (BeanCreationException ex) { - throw ex.getRootCause(); - } + context.refresh(); } @Test(expected = BeanCreationException.class) @@ -342,7 +398,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { static class FixedRateWithInitialDelayTestBean { - @Scheduled(initialDelay=1000, fixedRate=3000) + @Scheduled(fixedRate=3000, initialDelay=1000) public void fixedRate() { } } @@ -395,13 +451,13 @@ public class ScheduledAnnotationBeanPostProcessorTests { } - @Scheduled(fixedRate = 5000) + @Scheduled(fixedRate=5000) @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) private static @interface EveryFiveSeconds {} - @Scheduled(cron = "0 0 * * * ?") + @Scheduled(cron="0 0 * * * ?") @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) private static @interface Hourly {} @@ -423,7 +479,7 @@ public class ScheduledAnnotationBeanPostProcessorTests { } - static class PropertyPlaceholderTestBean { + static class PropertyPlaceholderWithCronTestBean { @Scheduled(cron = "${schedules.businessHours}") public void x() { @@ -431,7 +487,23 @@ public class ScheduledAnnotationBeanPostProcessorTests { } - @Scheduled(cron = "${schedules.businessHours}") + static class PropertyPlaceholderWithFixedDelayTestBean { + + @Scheduled(fixedDelayString="${fixedDelay}", initialDelayString="${initialDelay}") + public void fixedDelay() { + } + } + + + static class PropertyPlaceholderWithFixedRateTestBean { + + @Scheduled(fixedRateString="${fixedRate}", initialDelayString="${initialDelay}") + public void fixedRate() { + } + } + + + @Scheduled(cron="${schedules.businessHours}") @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) private static @interface BusinessHours {} From f9bac48d84bf1c632410aae10e4e2a70a0fbeb7c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 00:59:45 +0100 Subject: [PATCH 197/311] Further preparations for 3.2.2 --- src/dist/changelog.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index d033dfbc53..7cd00264a9 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -6,10 +6,13 @@ http://www.springsource.org Changes in version 3.2.2 (2013-03-07) -------------------------------------- -* official support for Hibernate 4.2 +* official support for Hibernate 4.2 (SPR-10255) * ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) * ConfigurationClassPostProcessor allows for overriding of scoped-proxy bean definitions (SPR-10265) +* "depends-on" attribute on lang namespace element actually respected at runtime now (SPR-8625) +* allow for ordering of mixed AspectJ before/after advices (SPR-9438) * added "maximumAutoGrowSize" property to SpelParserConfiguration (SPR-10229) +* @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support (SPR-8067) * SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) From 0058503cf0d0bd552d9938c467dd83a287831997 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 01:13:08 +0100 Subject: [PATCH 198/311] @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support Issue: SPR-8067 --- .../springframework/scheduling/support/CronTriggerTests.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java index 49574ae29d..a99bffa1ed 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -487,7 +487,7 @@ public class CronTriggerTests { assertEquals(calendar.getTime(), date = trigger.nextExecutionTime(context2)); } - @Test(expected=IllegalStateException.class) + @Test(expected = IllegalArgumentException.class) public void testNonExistentSpecificDate() throws Exception { // TODO: maybe try and detect this as a special case in parser? CronTrigger trigger = new CronTrigger("0 0 0 31 6 *", timeZone); From 584e79c677e69853a983667521a20b66331d52a6 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 7 Feb 2013 17:22:09 -0800 Subject: [PATCH 199/311] Promote use of @PostConstruct and @PreDestroy Update reference documentation to promote the use of the JSR-250 @PostConstruct and @PreDestroy annotations. Issue: SPR-8493 --- src/reference/docbook/beans-customizing.xml | 27 +++++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/reference/docbook/beans-customizing.xml b/src/reference/docbook/beans-customizing.xml index acca5514a7..9e5c4284b9 100644 --- a/src/reference/docbook/beans-customizing.xml +++ b/src/reference/docbook/beans-customizing.xml @@ -13,18 +13,25 @@
Lifecycle callbacks - - To interact with the container's management of the bean lifecycle, you can implement the Spring InitializingBean and DisposableBean interfaces. The container calls afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform certain actions upon initialization and destruction of - your beans. You can also achieve the same integration with the container - without coupling your classes to Spring interfaces through the use of - init-method and destroy method object definition metadata. + your beans. + + + The JSR-250 @PostConstruct and + @PreDestroy annotations are generally + considered best practice for receiving lifecycle callbacks in a modern + Spring application. Using these annotations means that your beans are not + coupled to Spring specific interfaces. For details see + . + If you don't want to use the JSR-250 annotations but you are still + looking to remove coupling consider the use of init-method and destroy-method + object definition metadata. + Internally, the Spring Framework uses BeanPostProcessor implementations to @@ -57,7 +64,9 @@ It is recommended that you do not use the InitializingBean interface because it - unnecessarily couples the code to Spring. Alternatively, specify a POJO + unnecessarily couples the code to Spring. Alternatively, use the + + @PostConstruct annotation or specify a POJO initialization method. In the case of XML-based configuration metadata, you use the init-method attribute to specify the name of the method that has a void no-argument signature. For example, the @@ -99,7 +108,9 @@ It is recommended that you do not use the DisposableBean callback interface because - it unnecessarily couples the code to Spring. Alternatively, specify a + it unnecessarily couples the code to Spring. Alternatively, use the + + @PreDestroy annotation or specify a generic method that is supported by bean definitions. With XML-based configuration metadata, you use the destroy-method attribute on the <bean/>. For example, the From 89c3d03083cff186ad34979d61e88c74ae33635a Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 16:08:05 +0100 Subject: [PATCH 200/311] @Async's qualifier works for target class annotations behind a JDK proxy as well Also optimized AsyncExecutionAspectSupport's Executor-per-Method caching to use a ConcurrentHashMap. Issue: SPR-10274 --- .../AsyncExecutionAspectSupport.java | 33 +++++----- .../AsyncExecutionInterceptor.java | 20 ++++--- .../AnnotationAsyncExecutionInterceptor.java | 6 +- .../annotation/AsyncAnnotationAdvisor.java | 31 ++++------ .../annotation/AsyncExecutionTests.java | 60 +++++++++++++++++++ 5 files changed, 104 insertions(+), 46 deletions(-) diff --git a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java index 96237b86d1..7fbfbf5604 100644 --- a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java +++ b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionAspectSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,8 @@ package org.springframework.aop.interceptor; import java.lang.reflect.Method; -import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import org.springframework.beans.BeansException; @@ -45,7 +45,7 @@ import org.springframework.util.StringUtils; */ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware { - private final Map executors = new HashMap(); + private final Map executors = new ConcurrentHashMap(16); private Executor defaultExecutor; @@ -59,7 +59,7 @@ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware { * @param defaultExecutor the executor to use when executing asynchronous methods */ public AsyncExecutionAspectSupport(Executor defaultExecutor) { - this.setExecutor(defaultExecutor); + this.defaultExecutor = defaultExecutor; } @@ -90,24 +90,25 @@ public abstract class AsyncExecutionAspectSupport implements BeanFactoryAware { * @return the executor to use (never {@code null}) */ protected AsyncTaskExecutor determineAsyncExecutor(Method method) { - if (!this.executors.containsKey(method)) { - Executor executor = this.defaultExecutor; + AsyncTaskExecutor executor = this.executors.get(method); + if (executor == null) { + Executor executorToUse = this.defaultExecutor; String qualifier = getExecutorQualifier(method); if (StringUtils.hasLength(qualifier)) { - Assert.notNull(this.beanFactory, - "BeanFactory must be set on " + this.getClass().getSimpleName() + - " to access qualified executor [" + qualifier + "]"); - executor = BeanFactoryAnnotationUtils.qualifiedBeanOfType( + Assert.notNull(this.beanFactory, "BeanFactory must be set on " + getClass().getSimpleName() + + " to access qualified executor '" + qualifier + "'"); + executorToUse = BeanFactoryAnnotationUtils.qualifiedBeanOfType( this.beanFactory, Executor.class, qualifier); } - if (executor instanceof AsyncTaskExecutor) { - this.executors.put(method, (AsyncTaskExecutor) executor); - } - else if (executor != null) { - this.executors.put(method, new TaskExecutorAdapter(executor)); + else if (executorToUse == null) { + throw new IllegalStateException("No executor qualifier specified and no default executor set on " + + getClass().getSimpleName() + " either"); } + executor = (executorToUse instanceof AsyncTaskExecutor ? + (AsyncTaskExecutor) executorToUse : new TaskExecutorAdapter(executorToUse)); + this.executors.put(method, executor); } - return this.executors.get(method); + return executor; } /** diff --git a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java index 792639b1c6..daa23a3293 100644 --- a/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java +++ b/spring-aop/src/main/java/org/springframework/aop/interceptor/AsyncExecutionInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.aop.interceptor; import java.lang.reflect.Method; - import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.Future; @@ -25,8 +24,11 @@ import java.util.concurrent.Future; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.support.AopUtils; +import org.springframework.core.BridgeMethodResolver; import org.springframework.core.Ordered; import org.springframework.core.task.AsyncTaskExecutor; +import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** @@ -76,7 +78,11 @@ public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport * otherwise. */ public Object invoke(final MethodInvocation invocation) throws Throwable { - Future result = this.determineAsyncExecutor(invocation.getMethod()).submit( + Class targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); + Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass); + specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod); + + Future result = determineAsyncExecutor(specificMethod).submit( new Callable() { public Object call() throws Exception { try { @@ -91,6 +97,7 @@ public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport return null; } }); + if (Future.class.isAssignableFrom(invocation.getMethod().getReturnType())) { return result; } @@ -100,10 +107,9 @@ public class AsyncExecutionInterceptor extends AsyncExecutionAspectSupport } /** - * {@inheritDoc} - *

This implementation is a no-op for compatibility in Spring 3.1.2. Subclasses may - * override to provide support for extracting qualifier information, e.g. via an - * annotation on the given method. + * This implementation is a no-op for compatibility in Spring 3.1.2. + * Subclasses may override to provide support for extracting qualifier information, + * e.g. via an annotation on the given method. * @return always {@code null} * @see #determineAsyncExecutor(Method) * @since 3.1.2 diff --git a/spring-context/src/main/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptor.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptor.java index a9abadab85..542aa15e32 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptor.java +++ b/spring-context/src/main/java/org/springframework/scheduling/annotation/AnnotationAsyncExecutionInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,7 +39,7 @@ public class AnnotationAsyncExecutionInterceptor extends AsyncExecutionIntercept /** * Create a new {@code AnnotationAsyncExecutionInterceptor} with the given executor. * @param defaultExecutor the executor to be used by default if no more specific - * executor has been qualified at the method level using {@link Async#value()}. + * executor has been qualified at the method level using {@link Async#value()} */ public AnnotationAsyncExecutionInterceptor(Executor defaultExecutor) { super(defaultExecutor); @@ -64,7 +64,7 @@ public class AnnotationAsyncExecutionInterceptor extends AsyncExecutionIntercept if (async == null) { async = AnnotationUtils.findAnnotation(method.getDeclaringClass(), Async.class); } - return async == null ? null : async.value(); + return (async != null ? async.value() : null); } } diff --git a/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java b/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java index 873740c21c..35e57c59d2 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java +++ b/spring-context/src/main/java/org/springframework/scheduling/annotation/AsyncAnnotationAdvisor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import org.springframework.aop.Pointcut; import org.springframework.aop.support.AbstractPointcutAdvisor; import org.springframework.aop.support.ComposablePointcut; import org.springframework.aop.support.annotation.AnnotationMatchingPointcut; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.core.task.SimpleAsyncTaskExecutor; @@ -58,8 +57,6 @@ public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements B private Pointcut pointcut; - private BeanFactory beanFactory; - /** * Create a new {@code AsyncAnnotationAdvisor} for bean-style configuration. @@ -84,30 +81,15 @@ public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements B // If EJB 3.1 API not present, simply ignore. } this.advice = buildAdvice(executor); - this.setTaskExecutor(executor); this.pointcut = buildPointcut(asyncAnnotationTypes); } - /** - * Set the {@code BeanFactory} to be used when looking up executors by qualifier. - */ - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - delegateBeanFactory(beanFactory); - } - - public void delegateBeanFactory(BeanFactory beanFactory) { - if (this.advice instanceof AnnotationAsyncExecutionInterceptor) { - ((AnnotationAsyncExecutionInterceptor)this.advice).setBeanFactory(beanFactory); - } - } /** - * Specify the task executor to use for asynchronous methods. + * Specify the default task executor to use for asynchronous methods. */ public void setTaskExecutor(Executor executor) { this.advice = buildAdvice(executor); - delegateBeanFactory(this.beanFactory); } /** @@ -126,6 +108,15 @@ public class AsyncAnnotationAdvisor extends AbstractPointcutAdvisor implements B this.pointcut = buildPointcut(asyncAnnotationTypes); } + /** + * Set the {@code BeanFactory} to be used when looking up executors by qualifier. + */ + public void setBeanFactory(BeanFactory beanFactory) { + if (this.advice instanceof BeanFactoryAware) { + ((BeanFactoryAware) this.advice).setBeanFactory(beanFactory); + } + } + public Advice getAdvice() { return this.advice; diff --git a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java index f679713eb9..028f60c559 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/annotation/AsyncExecutionTests.java @@ -66,6 +66,21 @@ public class AsyncExecutionTests { assertEquals("20", future.get()); } + @Test + public void asyncMethodsThroughInterface() throws Exception { + originalThreadName = Thread.currentThread().getName(); + GenericApplicationContext context = new GenericApplicationContext(); + context.registerBeanDefinition("asyncTest", new RootBeanDefinition(SimpleAsyncMethodBean.class)); + context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class)); + context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class)); + context.refresh(); + SimpleInterface asyncTest = context.getBean("asyncTest", SimpleInterface.class); + asyncTest.doNothing(5); + asyncTest.doSomething(10); + Future future = asyncTest.returnSomething(20); + assertEquals("20", future.get()); + } + @Test public void asyncMethodsWithQualifier() throws Exception { originalThreadName = Thread.currentThread().getName(); @@ -86,6 +101,26 @@ public class AsyncExecutionTests { assertEquals("30", future2.get()); } + @Test + public void asyncMethodsWithQualifierThroughInterface() throws Exception { + originalThreadName = Thread.currentThread().getName(); + GenericApplicationContext context = new GenericApplicationContext(); + context.registerBeanDefinition("asyncTest", new RootBeanDefinition(SimpleAsyncMethodWithQualifierBean.class)); + context.registerBeanDefinition("autoProxyCreator", new RootBeanDefinition(DefaultAdvisorAutoProxyCreator.class)); + context.registerBeanDefinition("asyncAdvisor", new RootBeanDefinition(AsyncAnnotationAdvisor.class)); + context.registerBeanDefinition("e0", new RootBeanDefinition(ThreadPoolTaskExecutor.class)); + context.registerBeanDefinition("e1", new RootBeanDefinition(ThreadPoolTaskExecutor.class)); + context.registerBeanDefinition("e2", new RootBeanDefinition(ThreadPoolTaskExecutor.class)); + context.refresh(); + SimpleInterface asyncTest = context.getBean("asyncTest", SimpleInterface.class); + asyncTest.doNothing(5); + asyncTest.doSomething(10); + Future future = asyncTest.returnSomething(20); + assertEquals("20", future.get()); + Future future2 = asyncTest.returnSomething2(30); + assertEquals("30", future2.get()); + } + @Test public void asyncClass() throws Exception { originalThreadName = Thread.currentThread().getName(); @@ -177,6 +212,18 @@ public class AsyncExecutionTests { } + public interface SimpleInterface { + + void doNothing(int i); + + void doSomething(int i); + + Future returnSomething(int i); + + Future returnSomething2(int i); + } + + public static class AsyncMethodBean { public void doNothing(int i) { @@ -196,6 +243,15 @@ public class AsyncExecutionTests { } + public static class SimpleAsyncMethodBean extends AsyncMethodBean implements SimpleInterface { + + @Override + public Future returnSomething2(int i) { + throw new UnsupportedOperationException(); + } + } + + @Async("e0") public static class AsyncMethodWithQualifierBean { @@ -224,6 +280,10 @@ public class AsyncExecutionTests { } + public static class SimpleAsyncMethodWithQualifierBean extends AsyncMethodWithQualifierBean implements SimpleInterface { + } + + @Async("e2") @Retention(RetentionPolicy.RUNTIME) public @interface MyAsync { From af8e6255e2ff2dfcda1822b807a18bd5f92c39a8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 21:13:04 +0100 Subject: [PATCH 201/311] Refined CronSequenceGenerator's rounding up of seconds to address second-specific cron expressions Issue: SPR-9459 --- .../support/CronSequenceGenerator.java | 25 ++++++++-- .../support/CronSequenceGeneratorTests.java | 48 +++++++++++++++++++ .../scheduling/support/CronTriggerTests.java | 5 +- 3 files changed, 72 insertions(+), 6 deletions(-) create mode 100644 spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java index 5f5cf4e280..68d127c72f 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronSequenceGenerator.java @@ -71,7 +71,19 @@ public class CronSequenceGenerator { /** - * Construct a {@link CronSequenceGenerator} from the pattern provided. + * Construct a {@link CronSequenceGenerator} from the pattern provided, + * using the default {@link TimeZone}. + * @param expression a space-separated list of time fields + * @throws IllegalArgumentException if the pattern cannot be parsed + * @see java.util.TimeZone#getDefault() + */ + public CronSequenceGenerator(String expression) { + this(expression, TimeZone.getDefault()); + } + + /** + * Construct a {@link CronSequenceGenerator} from the pattern provided, + * using the specified {@link TimeZone}. * @param expression a space-separated list of time fields * @param timeZone the TimeZone to use for generated trigger times * @throws IllegalArgumentException if the pattern cannot be parsed @@ -114,12 +126,17 @@ public class CronSequenceGenerator { calendar.setTimeZone(this.timeZone); calendar.setTime(date); - // Truncate to the next whole second - calendar.add(Calendar.SECOND, 1); + // First, just reset the milliseconds and try to calculate from there... calendar.set(Calendar.MILLISECOND, 0); - + long originalTimestamp = calendar.getTimeInMillis(); doNext(calendar, calendar.get(Calendar.YEAR)); + if (calendar.getTimeInMillis() == originalTimestamp) { + // We arrived at the original timestamp - round up to the next whole second and try again... + calendar.add(Calendar.SECOND, 1); + doNext(calendar, calendar.get(Calendar.YEAR)); + } + return calendar.getTime(); } diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java new file mode 100644 index 0000000000..491706f9e3 --- /dev/null +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronSequenceGeneratorTests.java @@ -0,0 +1,48 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.scheduling.support; + +import java.util.Date; + +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * @author Juergen Hoeller + */ +public class CronSequenceGeneratorTests { + + @Test + public void testAt50Seconds() { + assertEquals(new Date(2012, 6, 2, 1, 0), + new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53, 50))); + } + + @Test + public void testAt0Seconds() { + assertEquals(new Date(2012, 6, 2, 1, 0), + new CronSequenceGenerator("*/15 * 1-4 * * *").next(new Date(2012, 6, 1, 9, 53))); + } + + @Test + public void testAt0Minutes() { + assertEquals(new Date(2012, 6, 2, 1, 0), + new CronSequenceGenerator("0 */2 1-4 * * *").next(new Date(2012, 6, 1, 9, 0))); + } + +} diff --git a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java index a99bffa1ed..90acc959b3 100644 --- a/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java +++ b/spring-context/src/test/java/org/springframework/scheduling/support/CronTriggerTests.java @@ -41,7 +41,7 @@ import static org.junit.Assert.*; @RunWith(Parameterized.class) public class CronTriggerTests { - private Calendar calendar = new GregorianCalendar(); + private final Calendar calendar = new GregorianCalendar(); private final Date date; @@ -49,8 +49,8 @@ public class CronTriggerTests { public CronTriggerTests(Date date, TimeZone timeZone) { - this.timeZone = timeZone; this.date = date; + this.timeZone = timeZone; } @Parameters @@ -66,6 +66,7 @@ public class CronTriggerTests { calendar.set(Calendar.MILLISECOND, 0); } + @Before public void setUp() { calendar.setTimeZone(timeZone); From f57bc1aaaafa0ccb94cfef57e34cf8aa099ade6f Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 22:25:26 +0100 Subject: [PATCH 202/311] MappingJackson(2)JsonView allows subclasses to access the ObjectMapper and to override content writing Issue: SPR-7619 --- .../view/json/MappingJackson2JsonView.java | 101 ++++++++++------- .../view/json/MappingJacksonJsonView.java | 104 +++++++++++------- 2 files changed, 126 insertions(+), 79 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java index 7510ab304e..29c670a138 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJackson2JsonView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package org.springframework.web.servlet.view.json; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; @@ -27,7 +28,6 @@ import javax.servlet.http.HttpServletResponse; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -48,13 +48,15 @@ import org.springframework.web.servlet.view.AbstractView; * @author Jeremy Grelle * @author Arjen Poutsma * @author Rossen Stoyanchev + * @author Juergen Hoeller * @since 3.1.2 * @see org.springframework.http.converter.json.MappingJackson2HttpMessageConverter */ public class MappingJackson2JsonView extends AbstractView { /** - * Default content type. Overridable as bean property. + * Default content type: "application/json". + * Overridable through {@link #setContentType}. */ public static final String DEFAULT_CONTENT_TYPE = "application/json"; @@ -75,8 +77,9 @@ public class MappingJackson2JsonView extends AbstractView { private boolean updateContentLength = false; + /** - * Construct a new {@code JacksonJsonView}, setting the content type to {@code application/json}. + * Construct a new {@code MappingJackson2JsonView}, setting the content type to {@code application/json}. */ public MappingJackson2JsonView() { setContentType(DEFAULT_CONTENT_TYPE); @@ -85,13 +88,11 @@ public class MappingJackson2JsonView extends AbstractView { /** - * Sets the {@code ObjectMapper} for this view. - * If not set, a default {@link ObjectMapper#ObjectMapper() ObjectMapper} is used. - *

Setting a custom-configured {@code ObjectMapper} is one way to take further control - * of the JSON serialization process. For example, an extended {@code SerializerFactory} - * can be configured that provides custom serializers for specific types. The other option - * for refining the serialization process is to use Jackson's provided annotations on the - * types to be serialized, in which case a custom-configured ObjectMapper is unnecessary. + * Set the {@code ObjectMapper} for this view. + * If not set, a default {@link ObjectMapper#ObjectMapper() ObjectMapper} will be used. + *

Setting a custom-configured {@code ObjectMapper} is one way to take further control of + * the JSON serialization process. The other option is to use Jackson's provided annotations + * on the types to be serialized, in which case a custom-configured ObjectMapper is unnecessary. */ public void setObjectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "'objectMapper' must not be null"); @@ -99,14 +100,15 @@ public class MappingJackson2JsonView extends AbstractView { configurePrettyPrint(); } - private void configurePrettyPrint() { - if (this.prettyPrint != null) { - this.objectMapper.configure(SerializationFeature.INDENT_OUTPUT, this.prettyPrint); - } + /** + * Return the {@code ObjectMapper} for this view. + */ + public final ObjectMapper getObjectMapper() { + return this.objectMapper; } /** - * Set the {@code JsonEncoding} for this converter. + * Set the {@code JsonEncoding} for this view. * By default, {@linkplain JsonEncoding#UTF8 UTF-8} is used. */ public void setEncoding(JsonEncoding encoding) { @@ -114,9 +116,16 @@ public class MappingJackson2JsonView extends AbstractView { this.encoding = encoding; } + /** + * Return the {@code JsonEncoding} for this view. + */ + public final JsonEncoding getEncoding() { + return this.encoding; + } + /** * Indicates whether the JSON output by this view should be prefixed with "{} && ". - * Default is false. + * Default is {@code false}. *

Prefixing the JSON string in this manner is used to help prevent JSON Hijacking. * The prefix renders the string syntactically invalid as a script so that it cannot be hijacked. * This prefix does not affect the evaluation of JSON, but if JSON validation is performed @@ -127,12 +136,11 @@ public class MappingJackson2JsonView extends AbstractView { } /** - * Whether to use the {@link DefaultPrettyPrinter} when writing JSON. + * Whether to use the default pretty printer when writing JSON. * This is a shortcut for setting up an {@code ObjectMapper} as follows: *

 	 * ObjectMapper mapper = new ObjectMapper();
 	 * mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
-	 * converter.setObjectMapper(mapper);
 	 * 
*

The default value is {@code false}. */ @@ -141,6 +149,12 @@ public class MappingJackson2JsonView extends AbstractView { configurePrettyPrint(); } + private void configurePrettyPrint() { + if (this.prettyPrint != null) { + this.objectMapper.configure(SerializationFeature.INDENT_OUTPUT, this.prettyPrint); + } + } + /** * Set the attribute in the model that should be rendered by this view. * When set, all other model attributes will be ignored. @@ -160,7 +174,7 @@ public class MappingJackson2JsonView extends AbstractView { /** * Return the attributes in the model that should be rendered by this view. */ - public Set getModelKeys() { + public final Set getModelKeys() { return this.modelKeys; } @@ -179,7 +193,7 @@ public class MappingJackson2JsonView extends AbstractView { * @deprecated use {@link #getModelKeys()} instead */ @Deprecated - public Set getRenderedAttributes() { + public final Set getRenderedAttributes() { return this.modelKeys; } @@ -212,6 +226,7 @@ public class MappingJackson2JsonView extends AbstractView { this.updateContentLength = updateContentLength; } + @Override protected void prepareResponse(HttpServletRequest request, HttpServletResponse response) { setResponseContentType(request, response); @@ -227,34 +242,21 @@ public class MappingJackson2JsonView extends AbstractView { protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { - OutputStream stream = this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream(); - + OutputStream stream = (this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream()); Object value = filterModel(model); - JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding); - - // A workaround for JsonGenerators not applying serialization features - // https://github.com/FasterXML/jackson-databind/issues/12 - if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) { - generator.useDefaultPrettyPrinter(); - } - - if (this.prefixJson) { - generator.writeRaw("{} && "); - } - this.objectMapper.writeValue(generator, value); - + writeContent(stream, value, this.prefixJson); if (this.updateContentLength) { writeToResponse(response, (ByteArrayOutputStream) stream); } } /** - * Filters out undesired attributes from the given model. + * Filter out undesired attributes from the given model. * The return value can be either another {@link Map} or a single value object. *

The default implementation removes {@link BindingResult} instances and entries * not included in the {@link #setRenderedAttributes renderedAttributes} property. * @param model the model, as passed on to {@link #renderMergedOutputModel} - * @return the object to be rendered + * @return the value to be rendered */ protected Object filterModel(Map model) { Map result = new HashMap(model.size()); @@ -267,4 +269,27 @@ public class MappingJackson2JsonView extends AbstractView { return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result); } + /** + * Write the actual JSON content to the stream. + * @param stream the output stream to use + * @param value the value to be rendered, as returned from {@link #filterModel} + * @param prefixJson whether the JSON output by this view should be prefixed + * with "{} && " (as indicated through {@link #setPrefixJson}) + * @throws IOException if writing failed + */ + protected void writeContent(OutputStream stream, Object value, boolean prefixJson) throws IOException { + JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding); + + // A workaround for JsonGenerators not applying serialization features + // https://github.com/FasterXML/jackson-databind/issues/12 + if (this.objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT)) { + generator.useDefaultPrettyPrinter(); + } + + if (prefixJson) { + generator.writeRaw("{} && "); + } + this.objectMapper.writeValue(generator, value); + } + } diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJacksonJsonView.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJacksonJsonView.java index 5b97da49a8..ef0ad59d99 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJacksonJsonView.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/json/MappingJacksonJsonView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ package org.springframework.web.servlet.view.json; import java.io.ByteArrayOutputStream; +import java.io.IOException; import java.io.OutputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -30,15 +30,13 @@ import org.codehaus.jackson.JsonEncoding; import org.codehaus.jackson.JsonGenerator; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; -import org.codehaus.jackson.map.SerializerFactory; + import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.AbstractView; -import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; - /** * Spring MVC {@link View} that renders JSON content by serializing the model for the current request * using Jackson's {@link ObjectMapper}. @@ -50,13 +48,15 @@ import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; * @author Jeremy Grelle * @author Arjen Poutsma * @author Rossen Stoyanchev + * @author Juergen Hoeller * @since 3.0 * @see org.springframework.http.converter.json.MappingJacksonHttpMessageConverter */ public class MappingJacksonJsonView extends AbstractView { /** - * Default content type. Overridable as bean property. + * Default content type: "application/json". + * Overridable through {@link #setContentType}. */ public static final String DEFAULT_CONTENT_TYPE = "application/json"; @@ -77,8 +77,9 @@ public class MappingJacksonJsonView extends AbstractView { private boolean updateContentLength = false; + /** - * Construct a new {@code JacksonJsonView}, setting the content type to {@code application/json}. + * Construct a new {@code MappingJacksonJsonView}, setting the content type to {@code application/json}. */ public MappingJacksonJsonView() { setContentType(DEFAULT_CONTENT_TYPE); @@ -87,13 +88,11 @@ public class MappingJacksonJsonView extends AbstractView { /** - * Sets the {@code ObjectMapper} for this view. - * If not set, a default {@link ObjectMapper#ObjectMapper() ObjectMapper} is used. - *

Setting a custom-configured {@code ObjectMapper} is one way to take further control - * of the JSON serialization process. For example, an extended {@link SerializerFactory} - * can be configured that provides custom serializers for specific types. The other option - * for refining the serialization process is to use Jackson's provided annotations on the - * types to be serialized, in which case a custom-configured ObjectMapper is unnecessary. + * Set the {@code ObjectMapper} for this view. + * If not set, a default {@link ObjectMapper#ObjectMapper() ObjectMapper} will be used. + *

Setting a custom-configured {@code ObjectMapper} is one way to take further control of + * the JSON serialization process. The other option is to use Jackson's provided annotations + * on the types to be serialized, in which case a custom-configured ObjectMapper is unnecessary. */ public void setObjectMapper(ObjectMapper objectMapper) { Assert.notNull(objectMapper, "'objectMapper' must not be null"); @@ -101,14 +100,15 @@ public class MappingJacksonJsonView extends AbstractView { configurePrettyPrint(); } - private void configurePrettyPrint() { - if (this.prettyPrint != null) { - this.objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, this.prettyPrint); - } + /** + * Return the {@code ObjectMapper} for this view. + */ + public final ObjectMapper getObjectMapper() { + return this.objectMapper; } /** - * Set the {@code JsonEncoding} for this converter. + * Set the {@code JsonEncoding} for this view. * By default, {@linkplain JsonEncoding#UTF8 UTF-8} is used. */ public void setEncoding(JsonEncoding encoding) { @@ -116,9 +116,16 @@ public class MappingJacksonJsonView extends AbstractView { this.encoding = encoding; } + /** + * Return the {@code JsonEncoding} for this view. + */ + public final JsonEncoding getEncoding() { + return this.encoding; + } + /** * Indicates whether the JSON output by this view should be prefixed with "{} && ". - * Default is false. + * Default is {@code false}. *

Prefixing the JSON string in this manner is used to help prevent JSON Hijacking. * The prefix renders the string syntactically invalid as a script so that it cannot be hijacked. * This prefix does not affect the evaluation of JSON, but if JSON validation is performed @@ -129,12 +136,11 @@ public class MappingJacksonJsonView extends AbstractView { } /** - * Whether to use the {@link DefaultPrettyPrinter} when writing JSON. + * Whether to use the default pretty printer when writing JSON. * This is a shortcut for setting up an {@code ObjectMapper} as follows: *

 	 * ObjectMapper mapper = new ObjectMapper();
 	 * mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
-	 * converter.setObjectMapper(mapper);
 	 * 
*

The default value is {@code false}. */ @@ -143,6 +149,12 @@ public class MappingJacksonJsonView extends AbstractView { configurePrettyPrint(); } + private void configurePrettyPrint() { + if (this.prettyPrint != null) { + this.objectMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, this.prettyPrint); + } + } + /** * Set the attribute in the model that should be rendered by this view. * When set, all other model attributes will be ignored. @@ -162,7 +174,7 @@ public class MappingJacksonJsonView extends AbstractView { /** * Return the attributes in the model that should be rendered by this view. */ - public Set getModelKeys() { + public final Set getModelKeys() { return this.modelKeys; } @@ -181,7 +193,7 @@ public class MappingJacksonJsonView extends AbstractView { * @deprecated use {@link #getModelKeys()} instead */ @Deprecated - public Set getRenderedAttributes() { + public final Set getRenderedAttributes() { return this.modelKeys; } @@ -230,34 +242,21 @@ public class MappingJacksonJsonView extends AbstractView { protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { - OutputStream stream = this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream(); - + OutputStream stream = (this.updateContentLength ? createTemporaryOutputStream() : response.getOutputStream()); Object value = filterModel(model); - JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding); - - // A workaround for JsonGenerators not applying serialization features - // https://github.com/FasterXML/jackson-databind/issues/12 - if (this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) { - generator.useDefaultPrettyPrinter(); - } - - if (this.prefixJson) { - generator.writeRaw("{} && "); - } - this.objectMapper.writeValue(generator, value); - + writeContent(stream, value, this.prefixJson); if (this.updateContentLength) { writeToResponse(response, (ByteArrayOutputStream) stream); } } /** - * Filters out undesired attributes from the given model. + * Filter out undesired attributes from the given model. * The return value can be either another {@link Map} or a single value object. *

The default implementation removes {@link BindingResult} instances and entries * not included in the {@link #setRenderedAttributes renderedAttributes} property. * @param model the model, as passed on to {@link #renderMergedOutputModel} - * @return the object to be rendered + * @return the value to be rendered */ protected Object filterModel(Map model) { Map result = new HashMap(model.size()); @@ -270,4 +269,27 @@ public class MappingJacksonJsonView extends AbstractView { return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result); } + /** + * Write the actual JSON content to the stream. + * @param stream the output stream to use + * @param value the value to be rendered, as returned from {@link #filterModel} + * @param prefixJson whether the JSON output by this view should be prefixed + * with "{} && " (as indicated through {@link #setPrefixJson}) + * @throws IOException if writing failed + */ + protected void writeContent(OutputStream stream, Object value, boolean prefixJson) throws IOException { + JsonGenerator generator = this.objectMapper.getJsonFactory().createJsonGenerator(stream, this.encoding); + + // A workaround for JsonGenerators not applying serialization features + // https://github.com/FasterXML/jackson-databind/issues/12 + if (this.objectMapper.getSerializationConfig().isEnabled(SerializationConfig.Feature.INDENT_OUTPUT)) { + generator.useDefaultPrettyPrinter(); + } + + if (prefixJson) { + generator.writeRaw("{} && "); + } + this.objectMapper.writeValue(generator, value); + } + } From 9881517f618d468095d83f8b3cb38619fc846ca2 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 8 Feb 2013 22:26:03 +0100 Subject: [PATCH 203/311] Further enhancements for 3.2.2 --- src/dist/changelog.txt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 7cd00264a9..b7e6c0e9df 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -12,14 +12,17 @@ Changes in version 3.2.2 (2013-03-07) * "depends-on" attribute on lang namespace element actually respected at runtime now (SPR-8625) * allow for ordering of mixed AspectJ before/after advices (SPR-9438) * added "maximumAutoGrowSize" property to SpelParserConfiguration (SPR-10229) +* support 'unless' expression for cache veto (SPR-8871) +* @Async's qualifier works for target class annotations behind a JDK proxy as well (SPR-10274) * @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support (SPR-8067) +* refined CronSequenceGenerator's rounding up of seconds to address second-specific cron expressions (SPR-9459) * SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) * marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) +* MappingJackson(2)JsonView allows subclasses to access the ObjectMapper and to override content writing (SPR-7619) * consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) -* support 'unless' expression for cache veto (SPR-8871) Changes in version 3.2.1 (2013-01-24) From 3fa6723748e10cc3322735cce2da239d5e1a5a28 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sat, 9 Feb 2013 16:59:38 +0100 Subject: [PATCH 204/311] Added useful query variants without parameters to NamedParameterJdbcTemplate, for convenience in DAOs Also deprecated NamedParameterJdbcTemplate's queryForInt/Long operations in favor of queryForObject. Issue: SPR-10256 Issue: SPR-10257 --- .../namedparam/EmptySqlParameterSource.java | 49 +++++ .../NamedParameterJdbcOperations.java | 79 +++++++- .../NamedParameterJdbcTemplate.java | 22 ++- .../NamedParameterJdbcTemplateTests.java | 172 ++++++++++++++---- 4 files changed, 273 insertions(+), 49 deletions(-) create mode 100644 spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/EmptySqlParameterSource.java diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/EmptySqlParameterSource.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/EmptySqlParameterSource.java new file mode 100644 index 0000000000..a0b525f0dc --- /dev/null +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/EmptySqlParameterSource.java @@ -0,0 +1,49 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.core.namedparam; + +/** + * A simple empty implementation of the {@link SqlParameterSource} interface. + * + * @author Juergen Hoeller + * @since 3.2.2 + */ +public class EmptySqlParameterSource implements SqlParameterSource { + + /** + * A shared instance of {@link EmptySqlParameterSource}. + */ + public static final EmptySqlParameterSource INSTANCE = new EmptySqlParameterSource(); + + + public boolean hasValue(String paramName) { + return false; + } + + public Object getValue(String paramName) throws IllegalArgumentException { + throw new IllegalArgumentException("This SqlParameterSource is empty"); + } + + public int getSqlType(String paramName) { + return TYPE_UNKNOWN; + } + + public String getTypeName(String paramName) { + return null; + } + +} diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java index a7f5c9f7c9..91e20f3fcd 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -88,6 +88,21 @@ public interface NamedParameterJdbcOperations { T execute(String sql, Map paramMap, PreparedStatementCallback action) throws DataAccessException; + /** + * Execute a JDBC data access operation, implemented as callback action + * working on a JDBC PreparedStatement. This allows for implementing arbitrary + * data access operations on a single Statement, within Spring's managed + * JDBC environment: that is, participating in Spring-managed transactions + * and converting JDBC SQLExceptions into Spring's DataAccessException hierarchy. + *

The callback action can return a result object, for example a + * domain object or a collection of domain objects. + * @param sql SQL to execute + * @param action callback object that specifies the action + * @return a result object returned by the action, or {@code null} + * @throws DataAccessException if there is any problem + */ + T execute(String sql, PreparedStatementCallback action) throws DataAccessException; + /** * Query given SQL to create a prepared statement from SQL and a list * of arguments to bind to the query, reading the ResultSet with a @@ -115,6 +130,19 @@ public interface NamedParameterJdbcOperations { T query(String sql, Map paramMap, ResultSetExtractor rse) throws DataAccessException; + /** + * Query given SQL to create a prepared statement from SQL, + * reading the ResultSet with a ResultSetExtractor. + *

Note: In contrast to the JdbcOperations method with the same signature, + * this query variant always uses a PreparedStatement. It is effectively + * equivalent to a query call with an empty parameter Map. + * @param sql SQL query to execute + * @param rse object that will extract results + * @return an arbitrary result object, as returned by the ResultSetExtractor + * @throws org.springframework.dao.DataAccessException if the query fails + */ + T query(String sql, ResultSetExtractor rse) throws DataAccessException; + /** * Query given SQL to create a prepared statement from SQL and a list of * arguments to bind to the query, reading the ResultSet on a per-row basis @@ -139,6 +167,18 @@ public interface NamedParameterJdbcOperations { */ void query(String sql, Map paramMap, RowCallbackHandler rch) throws DataAccessException; + /** + * Query given SQL to create a prepared statement from SQL, + * reading the ResultSet on a per-row basis with a RowCallbackHandler. + *

Note: In contrast to the JdbcOperations method with the same signature, + * this query variant always uses a PreparedStatement. It is effectively + * equivalent to a query call with an empty parameter Map. + * @param sql SQL query to execute + * @param rch object that will extract results, one row at a time + * @throws org.springframework.dao.DataAccessException if the query fails + */ + void query(String sql, RowCallbackHandler rch) throws DataAccessException; + /** * Query given SQL to create a prepared statement from SQL and a list * of arguments to bind to the query, mapping each row to a Java object @@ -166,6 +206,19 @@ public interface NamedParameterJdbcOperations { List query(String sql, Map paramMap, RowMapper rowMapper) throws DataAccessException; + /** + * Query given SQL to create a prepared statement from SQL, + * mapping each row to a Java object via a RowMapper. + *

Note: In contrast to the JdbcOperations method with the same signature, + * this query variant always uses a PreparedStatement. It is effectively + * equivalent to a query call with an empty parameter Map. + * @param sql SQL query to execute + * @param rowMapper object that will map one object per row + * @return the result List, containing mapped objects + * @throws org.springframework.dao.DataAccessException if the query fails + */ + List query(String sql, RowMapper rowMapper) throws DataAccessException; + /** * Query given SQL to create a prepared statement from SQL and a list * of arguments to bind to the query, mapping a single result row to a @@ -245,8 +298,7 @@ public interface NamedParameterJdbcOperations { * @param paramSource container of arguments to bind to the query * @return the result Map (one entry for each column, using the column name as the key) * @throws org.springframework.dao.IncorrectResultSizeDataAccessException - * if the query does not return exactly one row, or does not return exactly - * one column in that row + * if the query does not return exactly one row * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForMap(String) * @see org.springframework.jdbc.core.ColumnMapRowMapper @@ -266,8 +318,7 @@ public interface NamedParameterJdbcOperations { * (leaving it to the PreparedStatement to guess the corresponding SQL type) * @return the result Map (one entry for each column, using the column name as the key) * @throws org.springframework.dao.IncorrectResultSizeDataAccessException - * if the query does not return exactly one row, or does not return exactly - * one column in that row + * if the query does not return exactly one row * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForMap(String) * @see org.springframework.jdbc.core.ColumnMapRowMapper @@ -287,7 +338,9 @@ public interface NamedParameterJdbcOperations { * one column in that row * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForLong(String) + * @deprecated in favor of {@link #queryForObject(String, SqlParameterSource, Class)} */ + @Deprecated long queryForLong(String sql, SqlParameterSource paramSource) throws DataAccessException; /** @@ -304,7 +357,9 @@ public interface NamedParameterJdbcOperations { * one column in that row * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForLong(String) + * @deprecated in favor of {@link #queryForObject(String, Map, Class)} */ + @Deprecated long queryForLong(String sql, Map paramMap) throws DataAccessException; /** @@ -319,7 +374,9 @@ public interface NamedParameterJdbcOperations { * exactly one row, or does not return exactly one column in that row * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForInt(String) + * @deprecated in favor of {@link #queryForObject(String, SqlParameterSource, Class)} */ + @Deprecated int queryForInt(String sql, SqlParameterSource paramSource) throws DataAccessException; /** @@ -335,7 +392,9 @@ public interface NamedParameterJdbcOperations { * exactly one row, or does not return exactly one column in that row * @throws org.springframework.dao.DataAccessException if the query fails * @see org.springframework.jdbc.core.JdbcTemplate#queryForInt(String) + * @deprecated in favor of {@link #queryForObject(String, Map, Class)} */ + @Deprecated int queryForInt(String sql, Map paramMap) throws DataAccessException; /** @@ -378,8 +437,8 @@ public interface NamedParameterJdbcOperations { * list of arguments to bind to the query, expecting a result list. *

The results will be mapped to a List (one entry for each row) of * Maps (one entry for each column, using the column name as the key). - * Thus Each element in the list will be of the form returned by this interface's - * queryForMap() methods. + * Each element in the list will be of the form returned by this interface's + * {@code queryForMap} methods. * @param sql SQL query to execute * @param paramSource container of arguments to bind to the query * @return a List that contains a Map per row @@ -394,7 +453,7 @@ public interface NamedParameterJdbcOperations { *

The results will be mapped to a List (one entry for each row) of * Maps (one entry for each column, using the column name as the key). * Each element in the list will be of the form returned by this interface's - * queryForMap() methods. + * {@code queryForMap} methods. * @param sql SQL query to execute * @param paramMap map of parameters to bind to the query * (leaving it to the PreparedStatement to guess the corresponding SQL type) @@ -499,7 +558,7 @@ public interface NamedParameterJdbcOperations { * @param batchValues the array of Maps containing the batch of arguments for the query * @return an array containing the numbers of rows affected by each update in the batch */ - public int[] batchUpdate(String sql, Map[] batchValues); + int[] batchUpdate(String sql, Map[] batchValues); /** * Execute a batch using the supplied SQL statement with the batch of supplied arguments. @@ -507,6 +566,6 @@ public interface NamedParameterJdbcOperations { * @param batchArgs the array of {@link SqlParameterSource} containing the batch of arguments for the query * @return an array containing the numbers of rows affected by each update in the batch */ - public int[] batchUpdate(String sql, SqlParameterSource[] batchArgs); + int[] batchUpdate(String sql, SqlParameterSource[] batchArgs); } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java index 1abfdea3c2..d8258cefc9 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -137,6 +137,10 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations return execute(sql, new MapSqlParameterSource(paramMap), action); } + public T execute(String sql, PreparedStatementCallback action) throws DataAccessException { + return execute(sql, EmptySqlParameterSource.INSTANCE, action); + } + public T query(String sql, SqlParameterSource paramSource, ResultSetExtractor rse) throws DataAccessException { @@ -149,6 +153,10 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations return query(sql, new MapSqlParameterSource(paramMap), rse); } + public T query(String sql, ResultSetExtractor rse) throws DataAccessException { + return query(sql, EmptySqlParameterSource.INSTANCE, rse); + } + public void query(String sql, SqlParameterSource paramSource, RowCallbackHandler rch) throws DataAccessException { @@ -161,6 +169,10 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations query(sql, new MapSqlParameterSource(paramMap), rch); } + public void query(String sql, RowCallbackHandler rch) throws DataAccessException { + query(sql, EmptySqlParameterSource.INSTANCE, rch); + } + public List query(String sql, SqlParameterSource paramSource, RowMapper rowMapper) throws DataAccessException { @@ -173,6 +185,10 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations return query(sql, new MapSqlParameterSource(paramMap), rowMapper); } + public List query(String sql, RowMapper rowMapper) throws DataAccessException { + return query(sql, EmptySqlParameterSource.INSTANCE, rowMapper); + } + public T queryForObject(String sql, SqlParameterSource paramSource, RowMapper rowMapper) throws DataAccessException { @@ -206,20 +222,24 @@ public class NamedParameterJdbcTemplate implements NamedParameterJdbcOperations return queryForObject(sql, paramMap, new ColumnMapRowMapper()); } + @Deprecated public long queryForLong(String sql, SqlParameterSource paramSource) throws DataAccessException { Number number = queryForObject(sql, paramSource, Long.class); return (number != null ? number.longValue() : 0); } + @Deprecated public long queryForLong(String sql, Map paramMap) throws DataAccessException { return queryForLong(sql, new MapSqlParameterSource(paramMap)); } + @Deprecated public int queryForInt(String sql, SqlParameterSource paramSource) throws DataAccessException { Number number = queryForObject(sql, paramSource, Integer.class); return (number != null ? number.intValue() : 0); } + @Deprecated public int queryForInt(String sql, Map paramMap) throws DataAccessException { return queryForInt(sql, new MapSqlParameterSource(paramMap)); } diff --git a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java index 6564fe5ee7..c17c8bbc02 100644 --- a/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java +++ b/spring-jdbc/src/test/java/org/springframework/jdbc/core/namedparam/NamedParameterJdbcTemplateTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,6 @@ package org.springframework.jdbc.core.namedparam; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; @@ -36,13 +27,13 @@ import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; - import javax.sql.DataSource; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; + import org.springframework.dao.DataAccessException; import org.springframework.jdbc.Customer; import org.springframework.jdbc.core.JdbcOperations; @@ -53,6 +44,14 @@ import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.SqlParameterValue; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + /** * @author Rick Evans * @author Juergen Hoeller @@ -64,6 +63,8 @@ public class NamedParameterJdbcTemplateTests { "select id, forename from custmr where id = :id and country = :country"; private static final String SELECT_NAMED_PARAMETERS_PARSED = "select id, forename from custmr where id = ? and country = ?"; + private static final String SELECT_NO_PARAMETERS = + "select id, forename from custmr"; private static final String UPDATE_NAMED_PARAMETERS = "update seat_status set booking_id = null where performance_id = :perfId and price_band_id = :priceId"; @@ -161,33 +162,23 @@ public class NamedParameterJdbcTemplateTests { verify(connection).close(); } - @Test public void testUpdate() throws SQLException { - given(preparedStatement.executeUpdate()).willReturn(1); - - params.put("perfId", 1); - params.put("priceId", 1); - int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); - - assertEquals(1, rowsAffected); - verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); - verify(preparedStatement).setObject(1, 1); - verify(preparedStatement).setObject(2, 1); - verify(preparedStatement).close(); - verify(connection).close(); - } - @Test - public void testUpdateWithTypedParameters() throws SQLException { + public void testExecuteNoParameters() throws SQLException { given(preparedStatement.executeUpdate()).willReturn(1); - params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1)); - params.put("priceId", new SqlParameterValue(Types.INTEGER, 1)); - int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); + Object result = namedParameterTemplate.execute(SELECT_NO_PARAMETERS, + new PreparedStatementCallback() { + @Override + public Object doInPreparedStatement(PreparedStatement ps) + throws SQLException { + assertEquals(preparedStatement, ps); + ps.executeQuery(); + return "result"; + } + }); - assertEquals(1, rowsAffected); - verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); - verify(preparedStatement).setObject(1, 1, Types.DECIMAL); - verify(preparedStatement).setObject(2, 1, Types.INTEGER); + assertEquals("result", result); + verify(connection).prepareStatement(SELECT_NO_PARAMETERS); verify(preparedStatement).close(); verify(connection).close(); } @@ -222,6 +213,32 @@ public class NamedParameterJdbcTemplateTests { verify(connection).close(); } + @Test + public void testQueryWithResultSetExtractorNoParameters() throws SQLException { + given(resultSet.next()).willReturn(true); + given(resultSet.getInt("id")).willReturn(1); + given(resultSet.getString("forename")).willReturn("rod"); + + Customer cust = namedParameterTemplate.query(SELECT_NO_PARAMETERS, + new ResultSetExtractor() { + @Override + public Customer extractData(ResultSet rs) throws SQLException, + DataAccessException { + rs.next(); + Customer cust = new Customer(); + cust.setId(rs.getInt(COLUMN_NAMES[0])); + cust.setForename(rs.getString(COLUMN_NAMES[1])); + return cust; + } + }); + + assertTrue("Customer id was assigned correctly", cust.getId() == 1); + assertTrue("Customer forename was assigned correctly", cust.getForename().equals("rod")); + verify(connection).prepareStatement(SELECT_NO_PARAMETERS); + verify(preparedStatement).close(); + verify(connection).close(); + } + @Test public void testQueryWithRowCallbackHandler() throws SQLException { given(resultSet.next()).willReturn(true, false); @@ -251,6 +268,31 @@ public class NamedParameterJdbcTemplateTests { verify(connection).close(); } + @Test + public void testQueryWithRowCallbackHandlerNoParameters() throws SQLException { + given(resultSet.next()).willReturn(true, false); + given(resultSet.getInt("id")).willReturn(1); + given(resultSet.getString("forename")).willReturn("rod"); + + final List customers = new LinkedList(); + namedParameterTemplate.query(SELECT_NO_PARAMETERS, new RowCallbackHandler() { + @Override + public void processRow(ResultSet rs) throws SQLException { + Customer cust = new Customer(); + cust.setId(rs.getInt(COLUMN_NAMES[0])); + cust.setForename(rs.getString(COLUMN_NAMES[1])); + customers.add(cust); + } + }); + + assertEquals(1, customers.size()); + assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); + assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); + verify(connection).prepareStatement(SELECT_NO_PARAMETERS); + verify(preparedStatement).close(); + verify(connection).close(); + } + @Test public void testQueryWithRowMapper() throws SQLException { given(resultSet.next()).willReturn(true, false); @@ -279,6 +321,30 @@ public class NamedParameterJdbcTemplateTests { verify(connection).close(); } + @Test + public void testQueryWithRowMapperNoParameters() throws SQLException { + given(resultSet.next()).willReturn(true, false); + given(resultSet.getInt("id")).willReturn(1); + given(resultSet.getString("forename")).willReturn("rod"); + + List customers = namedParameterTemplate.query(SELECT_NO_PARAMETERS, + new RowMapper() { + @Override + public Customer mapRow(ResultSet rs, int rownum) throws SQLException { + Customer cust = new Customer(); + cust.setId(rs.getInt(COLUMN_NAMES[0])); + cust.setForename(rs.getString(COLUMN_NAMES[1])); + return cust; + } + }); + assertEquals(1, customers.size()); + assertTrue("Customer id was assigned correctly", customers.get(0).getId() == 1); + assertTrue("Customer forename was assigned correctly", customers.get(0).getForename().equals("rod")); + verify(connection).prepareStatement(SELECT_NO_PARAMETERS); + verify(preparedStatement).close(); + verify(connection).close(); + } + @Test public void testQueryForObjectWithRowMapper() throws SQLException { given(resultSet.next()).willReturn(true, false); @@ -307,8 +373,39 @@ public class NamedParameterJdbcTemplateTests { } @Test - public void testBatchUpdateWithPlainMap() throws Exception { + public void testUpdate() throws SQLException { + given(preparedStatement.executeUpdate()).willReturn(1); + params.put("perfId", 1); + params.put("priceId", 1); + int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); + + assertEquals(1, rowsAffected); + verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); + verify(preparedStatement).setObject(1, 1); + verify(preparedStatement).setObject(2, 1); + verify(preparedStatement).close(); + verify(connection).close(); + } + + @Test + public void testUpdateWithTypedParameters() throws SQLException { + given(preparedStatement.executeUpdate()).willReturn(1); + + params.put("perfId", new SqlParameterValue(Types.DECIMAL, 1)); + params.put("priceId", new SqlParameterValue(Types.INTEGER, 1)); + int rowsAffected = namedParameterTemplate.update(UPDATE_NAMED_PARAMETERS, params); + + assertEquals(1, rowsAffected); + verify(connection).prepareStatement(UPDATE_NAMED_PARAMETERS_PARSED); + verify(preparedStatement).setObject(1, 1, Types.DECIMAL); + verify(preparedStatement).setObject(2, 1, Types.INTEGER); + verify(preparedStatement).close(); + verify(connection).close(); + } + + @Test + public void testBatchUpdateWithPlainMap() throws Exception { @SuppressWarnings("unchecked") final Map[] ids = new Map[2]; ids[0] = Collections.singletonMap("id", 100); @@ -335,7 +432,7 @@ public class NamedParameterJdbcTemplateTests { @Test public void testBatchUpdateWithSqlParameterSource() throws Exception { - final SqlParameterSource[] ids = new SqlParameterSource[2]; + SqlParameterSource[] ids = new SqlParameterSource[2]; ids[0] = new MapSqlParameterSource("id", 100); ids[1] = new MapSqlParameterSource("id", 200); final int[] rowsAffected = new int[] { 1, 2 }; @@ -360,8 +457,7 @@ public class NamedParameterJdbcTemplateTests { @Test public void testBatchUpdateWithSqlParameterSourcePlusTypeInfo() throws Exception { - - final SqlParameterSource[] ids = new SqlParameterSource[2]; + SqlParameterSource[] ids = new SqlParameterSource[2]; ids[0] = new MapSqlParameterSource().addValue("id", 100, Types.NUMERIC); ids[1] = new MapSqlParameterSource().addValue("id", 200, Types.NUMERIC); final int[] rowsAffected = new int[] { 1, 2 }; From c1c27e7142e003f2784a237ce20ed8823c9717ee Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sat, 9 Feb 2013 17:06:30 +0100 Subject: [PATCH 205/311] Deprecated JdbcTemplate's queryForInt/Long operations in favor of queryForObject (following NamedParameterJdbcTemplate) Issue: SPR-10257 --- .../jdbc/core/JdbcOperations.java | 23 +++++++++++++++---- .../jdbc/core/JdbcTemplate.java | 8 ++++++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java index 8f5a9964cd..6db102fc64 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcOperations.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -133,7 +133,8 @@ public interface JdbcOperations { * object via a RowMapper. *

Uses a JDBC Statement, not a PreparedStatement. If you want to * execute a static query with a PreparedStatement, use the overloaded - * {@code queryForObject} method with {@code null} as argument array. + * {@link #queryForObject(String, RowMapper, Object...)} method with + * {@code null} as argument array. * @param sql SQL query to execute * @param rowMapper object that will map one object per row * @return the single mapped object @@ -148,7 +149,8 @@ public interface JdbcOperations { * Execute a query for a result object, given static SQL. *

Uses a JDBC Statement, not a PreparedStatement. If you want to * execute a static query with a PreparedStatement, use the overloaded - * {@code queryForObject} method with {@code null} as argument array. + * {@link #queryForObject(String, Class, Object...)} method with + * {@code null} as argument array. *

This method is useful for running static SQL with a known outcome. * The query is expected to be a single row/single column query; the returned * result will be directly mapped to the corresponding object type. @@ -166,7 +168,8 @@ public interface JdbcOperations { * Execute a query for a result Map, given static SQL. *

Uses a JDBC Statement, not a PreparedStatement. If you want to * execute a static query with a PreparedStatement, use the overloaded - * {@code queryForMap} method with {@code null} as argument array. + * {@link #queryForMap(String, Object...)} method with {@code null} + * as argument array. *

The query is expected to be a single row query; the result row will be * mapped to a Map (one entry for each column, using the column name as the key). * @param sql SQL query to execute @@ -194,7 +197,9 @@ public interface JdbcOperations { * exactly one row, or does not return exactly one column in that row * @throws DataAccessException if there is any problem executing the query * @see #queryForLong(String, Object[]) + * @deprecated in favor of {@link #queryForObject(String, Class)} */ + @Deprecated long queryForLong(String sql) throws DataAccessException; /** @@ -211,7 +216,9 @@ public interface JdbcOperations { * exactly one row, or does not return exactly one column in that row * @throws DataAccessException if there is any problem executing the query * @see #queryForInt(String, Object[]) + * @deprecated in favor of {@link #queryForObject(String, Class)} */ + @Deprecated int queryForInt(String sql) throws DataAccessException; /** @@ -712,7 +719,9 @@ public interface JdbcOperations { * @throws DataAccessException if the query fails * @see #queryForLong(String) * @see java.sql.Types + * @deprecated in favor of {@link #queryForObject(String, Object[], int[], Class)} )} */ + @Deprecated long queryForLong(String sql, Object[] args, int[] argTypes) throws DataAccessException; /** @@ -730,7 +739,9 @@ public interface JdbcOperations { * exactly one row, or does not return exactly one column in that row * @throws DataAccessException if the query fails * @see #queryForLong(String) + * @deprecated in favor of {@link #queryForObject(String, Class, Object[])} )} */ + @Deprecated long queryForLong(String sql, Object... args) throws DataAccessException; /** @@ -748,7 +759,9 @@ public interface JdbcOperations { * @throws DataAccessException if the query fails * @see #queryForInt(String) * @see java.sql.Types + * @deprecated in favor of {@link #queryForObject(String, Object[], int[], Class)} )} */ + @Deprecated int queryForInt(String sql, Object[] args, int[] argTypes) throws DataAccessException; /** @@ -766,7 +779,9 @@ public interface JdbcOperations { * exactly one row, or does not return exactly one column in that row * @throws DataAccessException if the query fails * @see #queryForInt(String) + * @deprecated in favor of {@link #queryForObject(String, Class, Object[])} )} */ + @Deprecated int queryForInt(String sql, Object... args) throws DataAccessException; /** diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java index 3f0085cebf..910d206872 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/JdbcTemplate.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -477,11 +477,13 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { return queryForObject(sql, getSingleColumnRowMapper(requiredType)); } + @Deprecated public long queryForLong(String sql) throws DataAccessException { Number number = queryForObject(sql, Long.class); return (number != null ? number.longValue() : 0); } + @Deprecated public int queryForInt(String sql) throws DataAccessException { Number number = queryForObject(sql, Integer.class); return (number != null ? number.intValue() : 0); @@ -757,21 +759,25 @@ public class JdbcTemplate extends JdbcAccessor implements JdbcOperations { return queryForObject(sql, args, getColumnMapRowMapper()); } + @Deprecated public long queryForLong(String sql, Object[] args, int[] argTypes) throws DataAccessException { Number number = queryForObject(sql, args, argTypes, Long.class); return (number != null ? number.longValue() : 0); } + @Deprecated public long queryForLong(String sql, Object... args) throws DataAccessException { Number number = queryForObject(sql, args, Long.class); return (number != null ? number.longValue() : 0); } + @Deprecated public int queryForInt(String sql, Object[] args, int[] argTypes) throws DataAccessException { Number number = queryForObject(sql, args, argTypes, Integer.class); return (number != null ? number.intValue() : 0); } + @Deprecated public int queryForInt(String sql, Object... args) throws DataAccessException { Number number = queryForObject(sql, args, Integer.class); return (number != null ? number.intValue() : 0); From a86a77ad8191e1b24669260e68e812420a6a9421 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sat, 9 Feb 2013 23:21:35 +0100 Subject: [PATCH 206/311] ConfigurationClassPostProcessor detects covariant return type mismatch, avoiding infinite recursion Issue: SPR-10261 --- .../ConfigurationClassEnhancer.java | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java index 99678159d3..37c74ce2a1 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/ConfigurationClassEnhancer.java @@ -17,17 +17,11 @@ package org.springframework.context.annotation; import java.lang.reflect.Method; +import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.springframework.cglib.proxy.Callback; -import org.springframework.cglib.proxy.CallbackFilter; -import org.springframework.cglib.proxy.Enhancer; -import org.springframework.cglib.proxy.MethodInterceptor; -import org.springframework.cglib.proxy.MethodProxy; -import org.springframework.cglib.proxy.NoOp; - import org.springframework.aop.scope.ScopedProxyFactoryBean; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.DisposableBean; @@ -35,6 +29,12 @@ import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.beans.factory.support.SimpleInstantiationStrategy; +import org.springframework.cglib.proxy.Callback; +import org.springframework.cglib.proxy.CallbackFilter; +import org.springframework.cglib.proxy.Enhancer; +import org.springframework.cglib.proxy.MethodInterceptor; +import org.springframework.cglib.proxy.MethodProxy; +import org.springframework.cglib.proxy.NoOp; import org.springframework.core.annotation.AnnotationUtils; import org.springframework.util.Assert; @@ -52,8 +52,8 @@ class ConfigurationClassEnhancer { private static final Log logger = LogFactory.getLog(ConfigurationClassEnhancer.class); - private static final Class[] CALLBACK_TYPES = { BeanMethodInterceptor.class, - DisposableBeanMethodInterceptor.class, NoOp.class }; + private static final Class[] CALLBACK_TYPES = {BeanMethodInterceptor.class, + DisposableBeanMethodInterceptor.class, NoOp.class}; private static final CallbackFilter CALLBACK_FILTER = new CallbackFilter() { public int accept(Method candidateMethod) { @@ -80,10 +80,8 @@ class ConfigurationClassEnhancer { public ConfigurationClassEnhancer(ConfigurableBeanFactory beanFactory) { Assert.notNull(beanFactory, "BeanFactory must not be null"); // 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 }; + this.callbackInstances = new Callback[] + {new BeanMethodInterceptor(beanFactory), DISPOSABLE_BEAN_METHOD_INTERCEPTOR, NoOp.INSTANCE}; } /** @@ -169,9 +167,8 @@ class ConfigurationClassEnhancer { } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { - return beanFactory.getBean(beanName); + return this.beanFactory.getBean(this.beanName); } - } @@ -209,19 +206,16 @@ class ConfigurationClassEnhancer { */ private static class BeanMethodInterceptor implements MethodInterceptor { - private static final Class[] CALLBACK_TYPES = { - GetObjectMethodInterceptor.class, NoOp.class }; + private static final Class[] CALLBACK_TYPES = {GetObjectMethodInterceptor.class, NoOp.class}; - private static final CallbackFilter CALLBACK_FITLER = new CallbackFilter() { + private static final CallbackFilter CALLBACK_FILTER = new CallbackFilter() { public int accept(Method method) { - return method.getName().equals("getObject") ? 0 : 1; + return (method.getName().equals("getObject") ? 0 : 1); } }; - private final ConfigurableBeanFactory beanFactory; - public BeanMethodInterceptor(ConfigurableBeanFactory beanFactory) { this.beanFactory = beanFactory; } @@ -229,7 +223,6 @@ class ConfigurationClassEnhancer { /** * Enhance a {@link Bean @Bean} method to check the supplied BeanFactory for the * existence of this bean object. - * * @throws Throwable as a catch-all for any exception that may be thrown when * invoking the super implementation of the proxied method i.e., the actual * {@code @Bean} method. @@ -255,8 +248,8 @@ class ConfigurationClassEnhancer { // 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 // is the same as that of referring to a FactoryBean within XML. See SPR-6602. - if (factoryContainsBean('&'+beanName) && factoryContainsBean(beanName)) { - Object factoryBean = this.beanFactory.getBean('&'+beanName); + if (factoryContainsBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName) && factoryContainsBean(beanName)) { + Object factoryBean = this.beanFactory.getBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName); if (factoryBean instanceof ScopedProxyFactoryBean) { // pass through - scoped proxy factory beans are a special case and should not // be further proxied @@ -267,9 +260,7 @@ class ConfigurationClassEnhancer { } } - boolean factoryIsCaller = beanMethod.equals(SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod()); - boolean factoryAlreadyContainsSingleton = this.beanFactory.containsSingleton(beanName); - if (factoryIsCaller && !factoryAlreadyContainsSingleton) { + if (isCurrentlyInvokedFactoryMethod(beanMethod) && !this.beanFactory.containsSingleton(beanName)) { // the factory is calling the bean method in order to instantiate and register the bean // (i.e. via a getBean() call) -> invoke the super implementation of the method to actually // create the bean instance. @@ -306,7 +297,7 @@ class ConfigurationClassEnhancer { } /** - * Check the beanFactory to see whether the bean named beanName already + * Check the BeanFactory to see whether the bean named beanName already * exists. Accounts for the fact that the requested bean may be "in creation", i.e.: * we're in the middle of servicing the initial request for this bean. From an enhanced * factory method's perspective, this means that the bean does not actually yet exist, @@ -319,9 +310,19 @@ class ConfigurationClassEnhancer { * @return whether beanName already exists in the factory */ private boolean factoryContainsBean(String beanName) { - boolean containsBean = this.beanFactory.containsBean(beanName); - boolean currentlyInCreation = this.beanFactory.isCurrentlyInCreation(beanName); - return (containsBean && !currentlyInCreation); + return (this.beanFactory.containsBean(beanName) && !this.beanFactory.isCurrentlyInCreation(beanName)); + } + + /** + * Check whether the given method corresponds to the container's currently invoked + * factory method. Compares method name and parameter types only in order to work + * around a potential problem with covariant return types (currently only known + * to happen on Groovy classes). + */ + private boolean isCurrentlyInvokedFactoryMethod(Method method) { + Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod(); + return (currentlyInvoked != null && method.getName().equals(currentlyInvoked.getName()) && + Arrays.equals(method.getParameterTypes(), currentlyInvoked.getParameterTypes())); } /** @@ -335,13 +336,12 @@ class ConfigurationClassEnhancer { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(fbClass); enhancer.setUseFactory(false); - enhancer.setCallbackFilter(CALLBACK_FITLER); + enhancer.setCallbackFilter(CALLBACK_FILTER); // 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); From 01c44c8bf68c0f0fa296792746eebb6f4a24e3ee Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 00:02:45 +0100 Subject: [PATCH 207/311] Further enhancements for 3.2.2 --- src/dist/changelog.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index b7e6c0e9df..370c5614bc 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -8,6 +8,7 @@ Changes in version 3.2.2 (2013-03-07) * official support for Hibernate 4.2 (SPR-10255) * ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) +* ConfigurationClassPostProcessor detects covariant return type mismatch, avoiding infinite recursion (SPR-10261) * ConfigurationClassPostProcessor allows for overriding of scoped-proxy bean definitions (SPR-10265) * "depends-on" attribute on lang namespace element actually respected at runtime now (SPR-8625) * allow for ordering of mixed AspectJ before/after advices (SPR-9438) @@ -17,6 +18,8 @@ Changes in version 3.2.2 (2013-03-07) * @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support (SPR-8067) * refined CronSequenceGenerator's rounding up of seconds to address second-specific cron expressions (SPR-9459) * SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) +* deprecated (NamedParameter)JdbcTemplate's queryForInt/Long operations in favor of queryForObject (SPR-10257) +* added useful query variants without parameters to NamedParameterJdbcTemplate, for convenience in DAOs (SPR-10256) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) From 1af28efe39d8b141f10779518e794d74d29972f1 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 18:06:50 +0100 Subject: [PATCH 208/311] @Transactional in AspectJ mode works with CallbackPreferringPlatformTransactionManager (WebSphere) as well Effectively, AbstractTransactionAspect got refactored into around advice, reusing former TransactionInterceptor code which now lives in slightly generalized form in TransactionAspectSupport, and using a workaround for rethrowing checked exceptions. Issue: SPR-9268 --- .../aspectj/AbstractTransactionAspect.aj | 63 ++++--- .../aspectj/AnnotationTransactionAspect.aj | 8 +- .../aspectj/TransactionAspectTests.java | 121 +++++++----- .../interceptor/TransactionAspectSupport.java | 176 +++++++++++++++--- .../interceptor/TransactionInterceptor.java | 129 ++----------- 5 files changed, 282 insertions(+), 215 deletions(-) diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj index 54bd4ef746..ec5e803a39 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj @@ -16,8 +16,6 @@ package org.springframework.transaction.aspectj; -import java.lang.reflect.Method; - import org.aspectj.lang.annotation.SuppressAjWarnings; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.transaction.interceptor.TransactionAspectSupport; @@ -42,45 +40,42 @@ import org.springframework.transaction.interceptor.TransactionAttributeSource; * * @author Rod Johnson * @author Ramnivas Laddad + * @author Juergen Hoeller * @since 2.0 */ public abstract aspect AbstractTransactionAspect extends TransactionAspectSupport { /** - * Construct object using the given transaction metadata retrieval strategy. + * Construct the aspect using the given transaction metadata retrieval strategy. * @param tas TransactionAttributeSource implementation, retrieving Spring - * transaction metadata for each joinpoint. Write the subclass to pass in null - * if it's intended to be configured by Setter Injection. + * transaction metadata for each joinpoint. Implement the subclass to pass in + * {@code null} if it is intended to be configured through Setter Injection. */ protected AbstractTransactionAspect(TransactionAttributeSource tas) { setTransactionAttributeSource(tas); } @SuppressAjWarnings("adviceDidNotMatch") - before(Object txObject) : transactionalMethodExecution(txObject) { + Object around(final Object txObject): transactionalMethodExecution(txObject) { MethodSignature methodSignature = (MethodSignature) thisJoinPoint.getSignature(); - Method method = methodSignature.getMethod(); - createTransactionIfNecessary(method, txObject.getClass()); - } - - @SuppressAjWarnings("adviceDidNotMatch") - after(Object txObject) throwing(Throwable t) : transactionalMethodExecution(txObject) { + // Adapt to TransactionAspectSupport's invokeWithinTransaction... try { - completeTransactionAfterThrowing(TransactionAspectSupport.currentTransactionInfo(), t); + return invokeWithinTransaction(methodSignature.getMethod(), txObject.getClass(), new InvocationCallback() { + public Object proceedWithInvocation() throws Throwable { + return proceed(txObject); + } + }); } - catch (Throwable t2) { - logger.error("Failed to close transaction after throwing in a transactional method", t2); + catch (RuntimeException ex) { + throw ex; + } + catch (Error err) { + throw err; + } + catch (Throwable thr) { + Rethrower.rethrow(thr); + throw new IllegalStateException("Should never get here", thr); } - } - - @SuppressAjWarnings("adviceDidNotMatch") - after(Object txObject) returning() : transactionalMethodExecution(txObject) { - commitTransactionAfterReturning(TransactionAspectSupport.currentTransactionInfo()); - } - - @SuppressAjWarnings("adviceDidNotMatch") - after(Object txObject) : transactionalMethodExecution(txObject) { - cleanupTransactionInfo(TransactionAspectSupport.currentTransactionInfo()); } /** @@ -90,4 +85,22 @@ public abstract aspect AbstractTransactionAspect extends TransactionAspectSuppor */ protected abstract pointcut transactionalMethodExecution(Object txObject); + + /** + * Ugly but safe workaround: We need to be able to propagate checked exceptions, + * despite AspectJ around advice supporting specifically declared exceptions only. + */ + private static class Rethrower { + + public static void rethrow(final Throwable exception) { + class CheckedExceptionRethrower { + @SuppressWarnings("unchecked") + private void rethrow(Throwable exception) throws T { + throw (T) exception; + } + } + new CheckedExceptionRethrower().rethrow(exception); + } + } + } diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj index 2ea8f9e3f5..026704ac08 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj @@ -49,16 +49,14 @@ public aspect AnnotationTransactionAspect extends AbstractTransactionAspect { } /** - * Matches the execution of any public method in a type with the - * Transactional annotation, or any subtype of a type with the - * Transactional annotation. + * Matches the execution of any public method in a type with the Transactional + * annotation, or any subtype of a type with the Transactional annotation. */ private pointcut executionOfAnyPublicMethodInAtTransactionalType() : execution(public * ((@Transactional *)+).*(..)) && within(@Transactional *); /** - * Matches the execution of any method with the - * Transactional annotation. + * Matches the execution of any method with the Transactional annotation. */ private pointcut executionOfTransactionalMethod() : execution(@Transactional * *(..)); diff --git a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java index 70892e3949..b69e861933 100644 --- a/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java +++ b/spring-aspects/src/test/java/org/springframework/transaction/aspectj/TransactionAspectTests.java @@ -16,19 +16,18 @@ package org.springframework.transaction.aspectj; -import java.lang.reflect.Method; - -import junit.framework.AssertionFailedError; - import org.springframework.test.AbstractDependencyInjectionSpringContextTests; import org.springframework.tests.transaction.CallCountingTransactionManager; import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.transaction.interceptor.TransactionAttribute; +import java.lang.reflect.Method; + /** * @author Rod Johnson * @author Ramnivas Laddad + * @author Juergen Hoeller */ public class TransactionAspectTests extends AbstractDependencyInjectionSpringContextTests { @@ -123,50 +122,63 @@ public class TransactionAspectTests extends AbstractDependencyInjectionSpringCon public void testDefaultCommitOnAnnotatedClass() throws Throwable { - testRollback(new TransactionOperationCallback() { - public Object performTransactionalOperation() throws Throwable { - return annotationOnlyOnClassWithNoInterface.echo(new Exception()); - } - }, false); + final Exception ex = new Exception(); + try { + testRollback(new TransactionOperationCallback() { + public Object performTransactionalOperation() throws Throwable { + return annotationOnlyOnClassWithNoInterface.echo(ex); + } + }, false); + fail("Should have thrown Exception"); + } + catch (Exception ex2) { + assertSame(ex, ex2); + } } public void testDefaultRollbackOnAnnotatedClass() throws Throwable { - testRollback(new TransactionOperationCallback() { - public Object performTransactionalOperation() throws Throwable { - return annotationOnlyOnClassWithNoInterface.echo(new RuntimeException()); - } - }, true); + final RuntimeException ex = new RuntimeException(); + try { + testRollback(new TransactionOperationCallback() { + public Object performTransactionalOperation() throws Throwable { + return annotationOnlyOnClassWithNoInterface.echo(ex); + } + }, true); + fail("Should have thrown RuntimeException"); + } + catch (RuntimeException ex2) { + assertSame(ex, ex2); + } } - public static class SubclassOfClassWithTransactionalAnnotation extends TransactionalAnnotationOnlyOnClassWithNoInterface { - } - public void testDefaultCommitOnSubclassOfAnnotatedClass() throws Throwable { - testRollback(new TransactionOperationCallback() { - public Object performTransactionalOperation() throws Throwable { - return new SubclassOfClassWithTransactionalAnnotation().echo(new Exception()); - } - }, false); - } - - public static class SubclassOfClassWithTransactionalMethodAnnotation extends MethodAnnotationOnClassWithNoInterface { + final Exception ex = new Exception(); + try { + testRollback(new TransactionOperationCallback() { + public Object performTransactionalOperation() throws Throwable { + return new SubclassOfClassWithTransactionalAnnotation().echo(ex); + } + }, false); + fail("Should have thrown Exception"); + } + catch (Exception ex2) { + assertSame(ex, ex2); + } } public void testDefaultCommitOnSubclassOfClassWithTransactionalMethodAnnotated() throws Throwable { - testRollback(new TransactionOperationCallback() { - public Object performTransactionalOperation() throws Throwable { - return new SubclassOfClassWithTransactionalMethodAnnotation().echo(new Exception()); - } - }, false); - } - - public static class ImplementsAnnotatedInterface implements ITransactional { - public Object echo(Throwable t) throws Throwable { - if (t != null) { - throw t; - } - return t; + final Exception ex = new Exception(); + try { + testRollback(new TransactionOperationCallback() { + public Object performTransactionalOperation() throws Throwable { + return new SubclassOfClassWithTransactionalMethodAnnotation().echo(ex); + } + }, false); + fail("Should have thrown Exception"); + } + catch (Exception ex2) { + assertSame(ex, ex2); } } @@ -221,18 +233,12 @@ public class TransactionAspectTests extends AbstractDependencyInjectionSpringCon assertEquals(0, txManager.begun); try { toc.performTransactionalOperation(); - assertEquals(1, txManager.commits); } - catch (Throwable caught) { - if (caught instanceof AssertionFailedError) { - return; - } + finally { + assertEquals(1, txManager.begun); + assertEquals(rollback ? 0 : 1, txManager.commits); + assertEquals(rollback ? 1 : 0, txManager.rollbacks); } - - if (rollback) { - assertEquals(1, txManager.rollbacks); - } - assertEquals(1, txManager.begun); } protected void testNotTransactional(TransactionOperationCallback toc, Throwable expected) throws Throwable { @@ -258,4 +264,23 @@ public class TransactionAspectTests extends AbstractDependencyInjectionSpringCon Object performTransactionalOperation() throws Throwable; } + + public static class SubclassOfClassWithTransactionalAnnotation extends TransactionalAnnotationOnlyOnClassWithNoInterface { + } + + + public static class SubclassOfClassWithTransactionalMethodAnnotation extends MethodAnnotationOnClassWithNoInterface { + } + + + public static class ImplementsAnnotatedInterface implements ITransactional { + + public Object echo(Throwable t) throws Throwable { + if (t != null) { + throw t; + } + return t; + } + } + } diff --git a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java index 9f9b9503dd..bcd2c77880 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java +++ b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionAspectSupport.java @@ -16,12 +16,8 @@ package org.springframework.transaction.interceptor; -import java.lang.reflect.Method; -import java.util.Properties; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; @@ -31,8 +27,13 @@ import org.springframework.transaction.NoTransactionException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager; +import org.springframework.transaction.support.TransactionCallback; import org.springframework.util.StringUtils; +import java.lang.reflect.Method; +import java.util.Properties; + /** * Base class for transactional aspects, such as the {@link TransactionInterceptor} * or an AspectJ aspect. @@ -231,6 +232,90 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init } + /** + * General delegate for around-advice-based subclasses, delegating to several other template + * methods on this class. Able to handle {@link CallbackPreferringPlatformTransactionManager} + * as well as regular {@link PlatformTransactionManager} implementations. + * @param method the Method being invoked + * @param targetClass the target class that we're invoking the method on + * @param invocation the callback to use for proceeding with the target invocation + * @return the return value of the method, if any + * @throws Throwable propagated from the target invocation + */ + protected Object invokeWithinTransaction(Method method, Class targetClass, final InvocationCallback invocation) + throws Throwable { + + // If the transaction attribute is null, the method is non-transactional. + final TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass); + final PlatformTransactionManager tm = determineTransactionManager(txAttr); + final String joinpointIdentification = methodIdentification(method, targetClass); + + if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) { + // Standard transaction demarcation with getTransaction and commit/rollback calls. + TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification); + Object retVal = null; + try { + // This is an around advice: Invoke the next interceptor in the chain. + // This will normally result in a target object being invoked. + retVal = invocation.proceedWithInvocation(); + } + catch (Throwable ex) { + // target invocation exception + completeTransactionAfterThrowing(txInfo, ex); + throw ex; + } + finally { + cleanupTransactionInfo(txInfo); + } + commitTransactionAfterReturning(txInfo); + return retVal; + } + + else { + // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in. + try { + Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, + new TransactionCallback() { + public Object doInTransaction(TransactionStatus status) { + TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); + try { + return invocation.proceedWithInvocation(); + } + catch (Throwable ex) { + if (txAttr.rollbackOn(ex)) { + // A RuntimeException: will lead to a rollback. + if (ex instanceof RuntimeException) { + throw (RuntimeException) ex; + } + else { + throw new ThrowableHolderException(ex); + } + } + else { + // A normal return value: will lead to a commit. + return new ThrowableHolder(ex); + } + } + finally { + cleanupTransactionInfo(txInfo); + } + } + }); + + // Check result: It might indicate a Throwable to rethrow. + if (result instanceof ThrowableHolder) { + throw ((ThrowableHolder) result).getThrowable(); + } + else { + return result; + } + } + catch (ThrowableHolderException ex) { + throw ex.getCause(); + } + } + } + /** * Determine the specific transaction manager to use for the given transaction. */ @@ -250,23 +335,6 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init } } - /** - * Create a transaction if necessary, based on the given method and class. - *

Performs a default TransactionAttribute lookup for the given method. - * @param method the method about to execute - * @param targetClass the class that the method is being invoked on - * @return a TransactionInfo object, whether or not a transaction was created. - * The {@code hasTransaction()} method on TransactionInfo can be used to - * tell if there was a transaction created. - * @see #getTransactionAttributeSource() - */ - protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) { - // If the transaction attribute is null, the method is non-transactional. - TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass); - PlatformTransactionManager tm = determineTransactionManager(txAttr); - return createTransactionIfNecessary(tm, txAttr, methodIdentification(method, targetClass)); - } - /** * Convenience method to return a String representation of this Method * for use in logging. Can be overridden in subclasses to provide a @@ -297,6 +365,26 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init return null; } + /** + * Create a transaction if necessary, based on the given method and class. + *

Performs a default TransactionAttribute lookup for the given method. + * @param method the method about to execute + * @param targetClass the class that the method is being invoked on + * @return a TransactionInfo object, whether or not a transaction was created. + * The {@code hasTransaction()} method on TransactionInfo can be used to + * tell if there was a transaction created. + * @see #getTransactionAttributeSource() + * @deprecated in favor of + * {@link #createTransactionIfNecessary(PlatformTransactionManager, TransactionAttribute, String)} + */ + @Deprecated + protected TransactionInfo createTransactionIfNecessary(Method method, Class targetClass) { + // If the transaction attribute is null, the method is non-transactional. + TransactionAttribute txAttr = getTransactionAttributeSource().getTransactionAttribute(method, targetClass); + PlatformTransactionManager tm = determineTransactionManager(txAttr); + return createTransactionIfNecessary(tm, txAttr, methodIdentification(method, targetClass)); + } + /** * Create a transaction if necessary based on the given TransactionAttribute. *

Allows callers to perform custom TransactionAttribute lookups through @@ -527,4 +615,50 @@ public abstract class TransactionAspectSupport implements BeanFactoryAware, Init } } + + /** + * Simple callback interface for proceeding with the target invocation. + * Concrete interceptors/aspects adapt this to their invocation mechanism. + */ + protected interface InvocationCallback { + + Object proceedWithInvocation() throws Throwable; + } + + + /** + * Internal holder class for a Throwable, used as a return value + * from a TransactionCallback (to be subsequently unwrapped again). + */ + private static class ThrowableHolder { + + private final Throwable throwable; + + public ThrowableHolder(Throwable throwable) { + this.throwable = throwable; + } + + public final Throwable getThrowable() { + return this.throwable; + } + } + + + /** + * Internal holder class for a Throwable, used as a RuntimeException to be + * thrown from a TransactionCallback (and subsequently unwrapped again). + */ + @SuppressWarnings("serial") + private static class ThrowableHolderException extends RuntimeException { + + public ThrowableHolderException(Throwable throwable) { + super(throwable); + } + + @Override + public String toString() { + return getCause().toString(); + } + } + } diff --git a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionInterceptor.java b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionInterceptor.java index 11f72759a7..db46387077 100644 --- a/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionInterceptor.java +++ b/spring-tx/src/main/java/org/springframework/transaction/interceptor/TransactionInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,22 +16,18 @@ package org.springframework.transaction.interceptor; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; +import org.springframework.aop.support.AopUtils; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.transaction.PlatformTransactionManager; + import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Properties; -import org.aopalliance.intercept.MethodInterceptor; -import org.aopalliance.intercept.MethodInvocation; - -import org.springframework.aop.support.AopUtils; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.CallbackPreferringPlatformTransactionManager; -import org.springframework.transaction.support.TransactionCallback; - /** * AOP Alliance MethodInterceptor for declarative transaction * management using the common Spring transaction infrastructure @@ -40,7 +36,7 @@ import org.springframework.transaction.support.TransactionCallback; *

Derives from the {@link TransactionAspectSupport} class which * contains the integration with Spring's underlying transaction API. * TransactionInterceptor simply calls the relevant superclass methods - * such as {@link #createTransactionIfNecessary} in the correct order. + * such as {@link #invokeWithinTransaction} in the correct order. * *

TransactionInterceptors are thread-safe. * @@ -94,76 +90,12 @@ public class TransactionInterceptor extends TransactionAspectSupport implements // as well as the method, which may be from an interface. Class targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); - // If the transaction attribute is null, the method is non-transactional. - final TransactionAttribute txAttr = - getTransactionAttributeSource().getTransactionAttribute(invocation.getMethod(), targetClass); - final PlatformTransactionManager tm = determineTransactionManager(txAttr); - final String joinpointIdentification = methodIdentification(invocation.getMethod(), targetClass); - - if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) { - // Standard transaction demarcation with getTransaction and commit/rollback calls. - TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification); - Object retVal = null; - try { - // This is an around advice: Invoke the next interceptor in the chain. - // This will normally result in a target object being invoked. - retVal = invocation.proceed(); + // Adapt to TransactionAspectSupport's invokeWithinTransaction... + return invokeWithinTransaction(invocation.getMethod(), targetClass, new InvocationCallback() { + public Object proceedWithInvocation() throws Throwable { + return invocation.proceed(); } - catch (Throwable ex) { - // target invocation exception - completeTransactionAfterThrowing(txInfo, ex); - throw ex; - } - finally { - cleanupTransactionInfo(txInfo); - } - commitTransactionAfterReturning(txInfo); - return retVal; - } - - else { - // It's a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in. - try { - Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, - new TransactionCallback() { - public Object doInTransaction(TransactionStatus status) { - TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status); - try { - return invocation.proceed(); - } - catch (Throwable ex) { - if (txAttr.rollbackOn(ex)) { - // A RuntimeException: will lead to a rollback. - if (ex instanceof RuntimeException) { - throw (RuntimeException) ex; - } - else { - throw new ThrowableHolderException(ex); - } - } - else { - // A normal return value: will lead to a commit. - return new ThrowableHolder(ex); - } - } - finally { - cleanupTransactionInfo(txInfo); - } - } - }); - - // Check result: It might indicate a Throwable to rethrow. - if (result instanceof ThrowableHolder) { - throw ((ThrowableHolder) result).getThrowable(); - } - else { - return result; - } - } - catch (ThrowableHolderException ex) { - throw ex.getCause(); - } - } + }); } @@ -195,39 +127,4 @@ public class TransactionInterceptor extends TransactionAspectSupport implements setBeanFactory((BeanFactory) ois.readObject()); } - - /** - * Internal holder class for a Throwable, used as a return value - * from a TransactionCallback (to be subsequently unwrapped again). - */ - private static class ThrowableHolder { - - private final Throwable throwable; - - public ThrowableHolder(Throwable throwable) { - this.throwable = throwable; - } - - public final Throwable getThrowable() { - return this.throwable; - } - } - - - /** - * Internal holder class for a Throwable, used as a RuntimeException to be - * thrown from a TransactionCallback (and subsequently unwrapped again). - */ - private static class ThrowableHolderException extends RuntimeException { - - public ThrowableHolderException(Throwable throwable) { - super(throwable); - } - - @Override - public String toString() { - return getCause().toString(); - } - } - } From 6a2ace739fa97dc25b41014944343d0c65e17c3a Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 21:09:00 +0100 Subject: [PATCH 209/311] Added "entityResolver", "classDescriptorResolver", "doctypes" and further properties to CastorMarshaller Also deprecated CastorMarshaller's "object" property in favor of "rootObject". Issue: SPR-8470 --- .../oxm/castor/CastorMarshaller.java | 461 +++++++++--------- .../oxm/castor/CastorUnmarshallerTests.java | 21 +- 2 files changed, 247 insertions(+), 235 deletions(-) diff --git a/spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java index 0405e8272e..131b782c87 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/castor/CastorMarshaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,16 +30,20 @@ import javax.xml.stream.XMLStreamWriter; import org.exolab.castor.mapping.Mapping; import org.exolab.castor.mapping.MappingException; +import org.exolab.castor.util.ObjectFactory; +import org.exolab.castor.xml.IDResolver; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.Marshaller; import org.exolab.castor.xml.ResolverException; import org.exolab.castor.xml.UnmarshalHandler; import org.exolab.castor.xml.Unmarshaller; import org.exolab.castor.xml.ValidationException; +import org.exolab.castor.xml.XMLClassDescriptorResolver; import org.exolab.castor.xml.XMLContext; import org.exolab.castor.xml.XMLException; import org.w3c.dom.Node; import org.xml.sax.ContentHandler; +import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; @@ -56,30 +60,30 @@ import org.springframework.oxm.XmlMappingException; import org.springframework.oxm.support.AbstractMarshaller; import org.springframework.oxm.support.SaxResourceUtils; import org.springframework.util.ObjectUtils; -import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; import org.springframework.util.xml.StaxUtils; /** - * Implementation of the {@code Marshaller} interface for Castor. By default, Castor does not require any further - * configuration, though setting target classes, target packages or providing a mapping file can be used to have more - * control over the behavior of Castor. + * Implementation of the {@code Marshaller} interface for Castor. By default, Castor does + * not require any further configuration, though setting target classes, target packages or + * providing a mapping file can be used to have more control over the behavior of Castor. * - *

If a target class is specified using {@code setTargetClass}, the {@code CastorMarshaller} can only be - * used to unmarshal XML that represents that specific class. If you want to unmarshal multiple classes, you have to - * provide a mapping file using {@code setMappingLocations}. + *

If a target class is specified using {@code setTargetClass}, the {@code CastorMarshaller} + * can only be used to unmarshal XML that represents that specific class. If you want to unmarshal + * multiple classes, you have to provide a mapping file using {@code setMappingLocations}. * - *

Due to limitations of Castor's API, it is required to set the encoding used for writing to output streams. It - * defaults to {@code UTF-8}. + *

Due to limitations of Castor's API, it is required to set the encoding used for + * writing to output streams. It defaults to {@code UTF-8}. * * @author Arjen Poutsma * @author Jakub Narloch + * @author Juergen Hoeller + * @since 3.0 * @see #setEncoding(String) * @see #setTargetClass(Class) * @see #setTargetPackages(String[]) * @see #setMappingLocation(Resource) * @see #setMappingLocations(Resource[]) - * @since 3.0 */ public class CastorMarshaller extends AbstractMarshaller implements InitializingBean, BeanClassLoaderAware { @@ -88,6 +92,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing */ public static final String DEFAULT_ENCODING = "UTF-8"; + private Resource[] mappingLocations; private String encoding = DEFAULT_ENCODING; @@ -98,47 +103,59 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing private boolean validating = false; - private boolean whitespacePreserve = false; - - private boolean ignoreExtraAttributes = true; - - private boolean ignoreExtraElements = false; - - private Map namespaceMappings; - - private XMLContext xmlContext; - private boolean suppressNamespaces = false; private boolean suppressXsiType = false; private boolean marshalAsDocument = true; - private String rootElement; - private boolean marshalExtendedType = true; + private String rootElement; + private String noNamespaceSchemaLocation; private String schemaLocation; private boolean useXSITypeAtRoot = false; - private Map processingInstructions; + private boolean whitespacePreserve = false; - private Map namespaceToPackageMapping; + private boolean ignoreExtraAttributes = true; - private ClassLoader classLoader; + private boolean ignoreExtraElements = false; - private Object root; + private Object rootObject; private boolean reuseObjects = false; private boolean clearCollections = false; + private Map castorProperties; + + private Map doctypes; + + private Map processingInstructions; + + private Map namespaceMappings; + + private Map namespaceToPackageMapping; + + private EntityResolver entityResolver; + + private XMLClassDescriptorResolver classDescriptorResolver; + + private IDResolver idResolver; + + private ObjectFactory objectFactory; + + private ClassLoader beanClassLoader; + + private XMLContext xmlContext; + + /** * Set the encoding to be used for stream access. - * * @see #DEFAULT_ENCODING */ public void setEncoding(String encoding) { @@ -146,7 +163,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Set the locations of the Castor XML Mapping files. + * Set the locations of the Castor XML mapping files. */ public void setMappingLocation(Resource mappingLocation) { this.mappingLocations = new Resource[]{mappingLocation}; @@ -190,8 +207,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Set whether this marshaller should validate in- and outgoing documents.

Default is {@code false}. - * + * Set whether this marshaller should validate in- and outgoing documents. + *

Default is {@code false}. * @see Marshaller#setValidation(boolean) */ public void setValidating(boolean validating) { @@ -199,55 +216,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Set whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace.

Default is - * {@code false}. - * - * @see org.exolab.castor.xml.Unmarshaller#setWhitespacePreserve(boolean) - */ - public void setWhitespacePreserve(boolean whitespacePreserve) { - this.whitespacePreserve = whitespacePreserve; - } - - /** - * Set whether the Castor {@link Unmarshaller} should ignore attributes that do not match a specific field.

Default - * is {@code true}: extra attributes are ignored. - * - * @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraAttributes(boolean) - */ - public void setIgnoreExtraAttributes(boolean ignoreExtraAttributes) { - this.ignoreExtraAttributes = ignoreExtraAttributes; - } - - /** - * Set whether the Castor {@link Unmarshaller} should ignore elements that do not match a specific field.

Default - * is - * {@code false}, extra attributes are flagged as an error. - * - * @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraElements(boolean) - */ - public void setIgnoreExtraElements(boolean ignoreExtraElements) { - this.ignoreExtraElements = ignoreExtraElements; - } - - /** - * Set the namespace mappings. Property names are interpreted as namespace prefixes; values are namespace URIs. - * - * @see org.exolab.castor.xml.Marshaller#setNamespaceMapping(String, String) - */ - public void setNamespaceMappings(Map namespaceMappings) { - this.namespaceMappings = namespaceMappings; - } - - /** - * Returns whether this marshaller should output namespaces. - */ - public boolean isSuppressNamespaces() { - return suppressNamespaces; - } - - /** - * Sets whether this marshaller should output namespaces. The default is {@code false}, i.e. namespaces are written. - * + * Sets whether this marshaller should output namespaces. + *

The default is {@code false}, i.e. namespaces are written. * @see org.exolab.castor.xml.Marshaller#setSuppressNamespaces(boolean) */ public void setSuppressNamespaces(boolean suppressNamespaces) { @@ -255,16 +225,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets whether this marshaller should output the xsi:type attribute. - */ - public boolean isSuppressXsiType() { - return suppressXsiType; - } - - /** - * Sets whether this marshaller should output the {@code xsi:type} attribute. The default is {@code false}, i.e. the - * {@code xsi:type} is written. - * + * Set whether this marshaller should output the {@code xsi:type} attribute. + *

The default is {@code false}, i.e. the {@code xsi:type} is written. * @see org.exolab.castor.xml.Marshaller#setSuppressXSIType(boolean) */ public void setSuppressXsiType(boolean suppressXsiType) { @@ -272,9 +234,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets whether this marshaller should output the xml declaration.

The default is {@code true}, the xml - * declaration will be written. - * + * Set whether this marshaller should output the xml declaration. + *

The default is {@code true}, the XML declaration will be written. * @see org.exolab.castor.xml.Marshaller#setMarshalAsDocument(boolean) */ public void setMarshalAsDocument(boolean marshalAsDocument) { @@ -282,18 +243,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets the name of the root element. - * - * @see org.exolab.castor.xml.Marshaller#setRootElement(String) - */ - public void setRootElement(String rootElement) { - this.rootElement = rootElement; - } - - /** - * Sets whether this marshaller should output for given type the {@code xsi:type} attribute.

The default is {@code - * true}, the {@code xsi:type} attribute will be written. - * + * Set whether this marshaller should output for given type the {@code xsi:type} attribute. + *

The default is {@code true}, the {@code xsi:type} attribute will be written. * @see org.exolab.castor.xml.Marshaller#setMarshalExtendedType(boolean) */ public void setMarshalExtendedType(boolean marshalExtendedType) { @@ -301,9 +252,16 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets the value of {@code xsi:noNamespaceSchemaLocation} attribute. When set, the {@code - * xsi:noNamespaceSchemaLocation} attribute will be written for the root element. - * + * Set the name of the root element. + * @see org.exolab.castor.xml.Marshaller#setRootElement(String) + */ + public void setRootElement(String rootElement) { + this.rootElement = rootElement; + } + + /** + * Set the value of {@code xsi:noNamespaceSchemaLocation} attribute. When set, the + * {@code xsi:noNamespaceSchemaLocation} attribute will be written for the root element. * @see org.exolab.castor.xml.Marshaller#setNoNamespaceSchemaLocation(String) */ public void setNoNamespaceSchemaLocation(String noNamespaceSchemaLocation) { @@ -311,9 +269,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets the value of {@code xsi:schemaLocation} attribute.When set, the {@code xsi:schemaLocation} attribute will be - * written for the root element. - * + * Set the value of {@code xsi:schemaLocation} attribute. When set, the + * {@code xsi:schemaLocation} attribute will be written for the root element. * @see org.exolab.castor.xml.Marshaller#setSchemaLocation(String) */ public void setSchemaLocation(String schemaLocation) { @@ -321,10 +278,9 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets whether this marshaller should output the {@code xsi:type} attribute for the root element. This can be useful - * when the type of the element can not be simply determined from the element name.

The default is {@code false}, - * the {@code xsi:type} attribute for the root element won't be written. - * + * Sets whether this marshaller should output the {@code xsi:type} attribute for the root element. + * This can be useful when the type of the element can not be simply determined from the element name. + *

The default is {@code false}: The {@code xsi:type} attribute for the root element won't be written. * @see org.exolab.castor.xml.Marshaller#setUseXSITypeAtRoot(boolean) */ public void setUseXSITypeAtRoot(boolean useXSITypeAtRoot) { @@ -332,38 +288,54 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets the processing instructions that will be used by during marshalling. Keys are the processing targets and - * values - * contain the processing data. - * - * @see org.exolab.castor.xml.Marshaller#addProcessingInstruction(String, String) + * Set whether the Castor {@link Unmarshaller} should preserve "ignorable" whitespace. + *

Default is {@code false}. + * @see org.exolab.castor.xml.Unmarshaller#setWhitespacePreserve(boolean) */ - public void setProcessingInstructions(Map processingInstructions) { - this.processingInstructions = processingInstructions; + public void setWhitespacePreserve(boolean whitespacePreserve) { + this.whitespacePreserve = whitespacePreserve; } /** - * Set the namespace to package mappings. Property names are represents the namespaces URI, values are packages. - * - * @see org.exolab.castor.xml.Marshaller#setNamespaceMapping(String, String) + * Set whether the Castor {@link Unmarshaller} should ignore attributes that do not match a specific field. + *

Default is {@code true}: Extra attributes are ignored. + * @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraAttributes(boolean) */ - public void setNamespaceToPackageMapping(Map namespaceToPackageMapping) { - this.namespaceToPackageMapping = namespaceToPackageMapping; + public void setIgnoreExtraAttributes(boolean ignoreExtraAttributes) { + this.ignoreExtraAttributes = ignoreExtraAttributes; } /** - * Sets the expected object for the unmarshaller, into which the source will be unmarshalled. - * + * Set whether the Castor {@link Unmarshaller} should ignore elements that do not match a specific field. + *

Default is {@code false}: Extra elements are flagged as an error. + * @see org.exolab.castor.xml.Unmarshaller#setIgnoreExtraElements(boolean) + */ + public void setIgnoreExtraElements(boolean ignoreExtraElements) { + this.ignoreExtraElements = ignoreExtraElements; + } + + /** + * Set the expected root object for the unmarshaller, into which the source will be unmarshalled. + * @see org.exolab.castor.xml.Unmarshaller#setObject(Object) + * @deprecated in favor of {@link #setRootObject} + */ + @Deprecated + public void setObject(Object root) { + this.rootObject = root; + } + + /** + * Set the expected root object for the unmarshaller, into which the source will be unmarshalled. * @see org.exolab.castor.xml.Unmarshaller#setObject(Object) */ - public void setObject(Object root) { - this.root = root; + public void setRootObject(Object root) { + this.rootObject = root; } /** - * Sets whether this unmarshaller should re-use objects. This will be only used when unmarshalling to existing - * object.

The default is {@code false}, which means that the objects won't be re-used. - * + * Set whether this unmarshaller should re-use objects. + * This will be only used when unmarshalling to an existing object. + *

The default is {@code false}, which means that the objects won't be re-used. * @see org.exolab.castor.xml.Unmarshaller#setReuseObjects(boolean) */ public void setReuseObjects(boolean reuseObjects) { @@ -371,39 +343,99 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Sets whether this unmarshaller should clear collections upon the first use.

The default is {@code false}, - * which means that marshaller won't clear collections. - * + * Sets whether this unmarshaller should clear collections upon the first use. + *

The default is {@code false} which means that marshaller won't clear collections. * @see org.exolab.castor.xml.Unmarshaller#setClearCollections(boolean) */ public void setClearCollections(boolean clearCollections) { this.clearCollections = clearCollections; } - public void setBeanClassLoader(ClassLoader classLoader) { - this.classLoader = classLoader; + /** + * Set Castor-specific properties for marshalling and unmarshalling. + * Each entry key is considered the property name and each value the property value. + * @see org.exolab.castor.xml.Marshaller#setProperty(String, String) + * @see org.exolab.castor.xml.Unmarshaller#setProperty(String, String) + */ + public void setCastorProperties(Map castorProperties) { + this.castorProperties = castorProperties; } - public final void afterPropertiesSet() throws CastorMappingException, IOException { - if (logger.isInfoEnabled()) { - if (!ObjectUtils.isEmpty(this.mappingLocations)) { - logger.info( - "Configured using [" + StringUtils.arrayToCommaDelimitedString(this.mappingLocations) + "]"); - } - if (!ObjectUtils.isEmpty(this.targetClasses)) { - logger.info("Configured for target classes " + StringUtils.arrayToCommaDelimitedString(targetClasses) + - "]"); - } - if (!ObjectUtils.isEmpty(this.targetPackages)) { - logger.info( - "Configured for target packages [" + StringUtils.arrayToCommaDelimitedString(targetPackages) + - "]"); - } - if (ObjectUtils.isEmpty(this.mappingLocations) && ObjectUtils.isEmpty(this.targetClasses) && - ObjectUtils.isEmpty(this.targetPackages)) { - logger.info("Using default configuration"); - } - } + /** + * Set the map containing document type definition for the marshaller. + * Each entry has system id as key and public id as value. + * @see org.exolab.castor.xml.Marshaller#setDoctype(String, String) + */ + public void setDoctypes(Map doctypes) { + this.doctypes = doctypes; + } + + /** + * Sets the processing instructions that will be used by during marshalling. + * Keys are the processing targets and values contain the processing data. + * @see org.exolab.castor.xml.Marshaller#addProcessingInstruction(String, String) + */ + public void setProcessingInstructions(Map processingInstructions) { + this.processingInstructions = processingInstructions; + } + + /** + * Set the namespace mappings. + * Property names are interpreted as namespace prefixes; values are namespace URIs. + * @see org.exolab.castor.xml.Marshaller#setNamespaceMapping(String, String) + */ + public void setNamespaceMappings(Map namespaceMappings) { + this.namespaceMappings = namespaceMappings; + } + + /** + * Set the namespace to package mappings. Property names are represents the namespaces URI, values are packages. + * @see org.exolab.castor.xml.Marshaller#setNamespaceMapping(String, String) + */ + public void setNamespaceToPackageMapping(Map namespaceToPackageMapping) { + this.namespaceToPackageMapping = namespaceToPackageMapping; + } + + /** + * Set the {@link EntityResolver} to be used during unmarshalling. + * This resolver will used to resolve system and public ids. + * @see org.exolab.castor.xml.Unmarshaller#setEntityResolver(EntityResolver) + */ + public void setEntityResolver(EntityResolver entityResolver) { + this.entityResolver = entityResolver; + } + + /** + * Set the {@link XMLClassDescriptorResolver} to be used during unmarshalling. + * This resolver will used to resolve class descriptors. + * @see org.exolab.castor.xml.Unmarshaller#setResolver(XMLClassDescriptorResolver) + */ + public void setClassDescriptorResolver(XMLClassDescriptorResolver classDescriptorResolver) { + this.classDescriptorResolver = classDescriptorResolver; + } + + /** + * Set the Castor {@link IDResolver} to be used during unmarshalling. + * @see org.exolab.castor.xml.Unmarshaller#setIDResolver(IDResolver) + */ + public void setIdResolver(IDResolver idResolver) { + this.idResolver = idResolver; + } + + /** + * Set the Castor {@link ObjectFactory} to be used during unmarshalling. + * @see org.exolab.castor.xml.Unmarshaller#setObjectFactory(ObjectFactory) + */ + public void setObjectFactory(ObjectFactory objectFactory) { + this.objectFactory = objectFactory; + } + + public void setBeanClassLoader(ClassLoader classLoader) { + this.beanClassLoader = classLoader; + } + + + public void afterPropertiesSet() throws CastorMappingException, IOException { try { this.xmlContext = createXMLContext(this.mappingLocations, this.targetClasses, this.targetPackages); } @@ -416,9 +448,8 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing } /** - * Create the Castor {@code XMLContext}. Subclasses can override this to create a custom context.

The default - * implementation loads mapping files if defined, or the target class or packages if defined. - * + * Create the Castor {@code XMLContext}. Subclasses can override this to create a custom context. + *

The default implementation loads mapping files if defined, or the target class or packages if defined. * @return the created resolver * @throws MappingException when the mapping file cannot be loaded * @throws IOException in case of I/O errors @@ -442,9 +473,15 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing if (!ObjectUtils.isEmpty(targetPackages)) { context.addPackages(targetPackages); } + if (this.castorProperties != null) { + for (Map.Entry property : this.castorProperties.entrySet()) { + context.setProperty(property.getKey(), property.getValue()); + } + } return context; } + /** * Returns {@code true} for all classes, i.e. Castor supports arbitrary classes. */ @@ -462,6 +499,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing @Override protected final void marshalSaxHandlers(Object graph, ContentHandler contentHandler, LexicalHandler lexicalHandler) throws XmlMappingException { + Marshaller marshaller = xmlContext.createMarshaller(); marshaller.setContentHandler(contentHandler); marshal(graph, marshaller); @@ -470,6 +508,7 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing @Override protected final void marshalOutputStream(Object graph, OutputStream outputStream) throws XmlMappingException, IOException { + marshalWriter(graph, new OutputStreamWriter(outputStream, encoding)); } @@ -502,42 +541,29 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing /** * Template method that allows for customizing of the given Castor {@link Marshaller}. - * - *

The default implementation invokes - *
    - *
  1. {@link Marshaller#setValidation(boolean)},
  2. - *
  3. {@link Marshaller#setSuppressNamespaces(boolean)},
  4. - *
  5. {@link Marshaller#setSuppressXSIType(boolean)},
  6. - *
  7. {@link Marshaller#setMarshalAsDocument(boolean)},
  8. - *
  9. {@link Marshaller#setRootElement(String)},
  10. - *
  11. {@link Marshaller#setMarshalExtendedType(boolean)},
  12. - *
  13. {@link Marshaller#setNoNamespaceSchemaLocation(String)},
  14. - *
  15. {@link Marshaller#setSchemaLocation(String)} and
  16. - *
  17. {@link Marshaller#setUseXSITypeAtRoot(boolean)}.
  18. - *
- * with the property set on this marshaller. - * It also calls {@link Marshaller#setNamespaceMapping(String, String)} - * with the {@linkplain #setNamespaceMappings(java.util.Map) namespace mappings} and - * {@link Marshaller#addProcessingInstruction(String, String)} with the - * {@linkplain #setProcessingInstructions(java.util.Map) processing instructions}. */ protected void customizeMarshaller(Marshaller marshaller) { marshaller.setValidation(this.validating); - marshaller.setSuppressNamespaces(isSuppressNamespaces()); - marshaller.setSuppressXSIType(isSuppressXsiType()); - marshaller.setMarshalAsDocument(marshalAsDocument); - marshaller.setRootElement(rootElement); - marshaller.setMarshalExtendedType(marshalExtendedType); - marshaller.setNoNamespaceSchemaLocation(noNamespaceSchemaLocation); - marshaller.setSchemaLocation(schemaLocation); - marshaller.setUseXSITypeAtRoot(useXSITypeAtRoot); - if (processingInstructions != null) { - for (Map.Entry processingInstruction : processingInstructions.entrySet()) { + marshaller.setSuppressNamespaces(this.suppressNamespaces); + marshaller.setSuppressXSIType(this.suppressXsiType); + marshaller.setMarshalAsDocument(this.marshalAsDocument); + marshaller.setMarshalExtendedType(this.marshalExtendedType); + marshaller.setRootElement(this.rootElement); + marshaller.setNoNamespaceSchemaLocation(this.noNamespaceSchemaLocation); + marshaller.setSchemaLocation(this.schemaLocation); + marshaller.setUseXSITypeAtRoot(this.useXSITypeAtRoot); + if (this.doctypes != null) { + for (Map.Entry doctype : this.doctypes.entrySet()) { + marshaller.setDoctype(doctype.getKey(), doctype.getValue()); + } + } + if (this.processingInstructions != null) { + for (Map.Entry processingInstruction : this.processingInstructions.entrySet()) { marshaller.addProcessingInstruction(processingInstruction.getKey(), processingInstruction.getValue()); } } if (this.namespaceMappings != null) { - for (Map.Entry entry : namespaceMappings.entrySet()) { + for (Map.Entry entry : this.namespaceMappings.entrySet()) { marshaller.setNamespaceMapping(entry.getKey(), entry.getValue()); } } @@ -619,48 +645,45 @@ public class CastorMarshaller extends AbstractMarshaller implements Initializing /** * Template method that allows for customizing of the given Castor {@link Unmarshaller}. - * - *

The default implementation invokes - *
    - *
  1. {@link Unmarshaller#setValidation(boolean)}, - *
  2. {@link Unmarshaller#setWhitespacePreserve(boolean)}, - *
  3. {@link Unmarshaller#setIgnoreExtraAttributes(boolean)}, - *
  4. {@link Unmarshaller#setIgnoreExtraElements(boolean)}, - *
  5. {@link Unmarshaller#setClassLoader(ClassLoader)}, - *
  6. {@link Unmarshaller#setObject(Object)}, - *
  7. {@link Unmarshaller#setReuseObjects(boolean)} and - *
  8. {@link Unmarshaller#setClearCollections(boolean)} - *
- * with the properties set on this marshaller. - * It also calls {@link Unmarshaller#addNamespaceToPackageMapping(String, String)} with the - * {@linkplain #setNamespaceMappings(java.util.Map) namespace to package mapping}. */ protected void customizeUnmarshaller(Unmarshaller unmarshaller) { unmarshaller.setValidation(this.validating); unmarshaller.setWhitespacePreserve(this.whitespacePreserve); unmarshaller.setIgnoreExtraAttributes(this.ignoreExtraAttributes); unmarshaller.setIgnoreExtraElements(this.ignoreExtraElements); - unmarshaller.setClassLoader(classLoader); - unmarshaller.setObject(root); - unmarshaller.setReuseObjects(reuseObjects); - unmarshaller.setClearCollections(clearCollections); - if (namespaceToPackageMapping != null) { - for (Map.Entry mapping : namespaceToPackageMapping.entrySet()) { + unmarshaller.setObject(this.rootObject); + unmarshaller.setReuseObjects(this.reuseObjects); + unmarshaller.setClearCollections(this.clearCollections); + if (this.namespaceToPackageMapping != null) { + for (Map.Entry mapping : this.namespaceToPackageMapping.entrySet()) { unmarshaller.addNamespaceToPackageMapping(mapping.getKey(), mapping.getValue()); } } - + if (this.entityResolver != null) { + unmarshaller.setEntityResolver(this.entityResolver); + } + if (this.classDescriptorResolver != null) { + unmarshaller.setResolver(this.classDescriptorResolver); + } + if (this.idResolver != null) { + unmarshaller.setIDResolver(this.idResolver); + } + if (this.objectFactory != null) { + unmarshaller.setObjectFactory(this.objectFactory); + } + if (this.beanClassLoader != null) { + unmarshaller.setClassLoader(this.beanClassLoader); + } } /** * Convert the given {@code XMLException} to an appropriate exception from the - * {@code org.springframework.oxm} hierarchy.

A boolean flag is used to indicate whether this exception - * occurs - * during marshalling or unmarshalling, since Castor itself does not make this distinction in its exception hierarchy. - * + * {@code org.springframework.oxm} hierarchy. + *

A boolean flag is used to indicate whether this exception occurs during marshalling or + * unmarshalling, since Castor itself does not make this distinction in its exception hierarchy. * @param ex Castor {@code XMLException} that occurred - * @param marshalling indicates whether the exception occurs during marshalling ({@code true}), or unmarshalling - * ({@code false}) + * @param marshalling indicates whether the exception occurs during marshalling ({@code true}), + * or unmarshalling ({@code false}) * @return the corresponding {@code XmlMappingException} */ protected XmlMappingException convertCastorException(XMLException ex, boolean marshalling) { diff --git a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java index 367b4aa5c1..585640893b 100644 --- a/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java +++ b/spring-oxm/src/test/java/org/springframework/oxm/castor/CastorUnmarshallerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,12 +30,9 @@ import org.springframework.oxm.MarshallingException; import org.springframework.oxm.Unmarshaller; import static org.hamcrest.CoreMatchers.*; - import static org.junit.Assert.*; /** - * Tests the {@link CastorMarshaller} class. - * * @author Arjen Poutsma * @author Jakub Narloch */ @@ -114,7 +111,6 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { @Test public void testWhitespacePreserveTrue() throws Exception { - getCastorUnmarshaller().setWhitespacePreserve(true); Object result = unmarshalFlights(); testFlights(result); @@ -122,7 +118,6 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { @Test public void testWhitespacePreserveFalse() throws Exception { - getCastorUnmarshaller().setWhitespacePreserve(false); Object result = unmarshalFlights(); testFlights(result); @@ -130,7 +125,6 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { @Test public void testIgnoreExtraAttributesTrue() throws Exception { - getCastorUnmarshaller().setIgnoreExtraAttributes(true); Object result = unmarshal(EXTRA_ATTRIBUTES_STRING); testFlights(result); @@ -146,7 +140,6 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { @Test @Ignore("Not working yet") public void testIgnoreExtraElementsTrue() throws Exception { - getCastorUnmarshaller().setIgnoreExtraElements(true); getCastorUnmarshaller().setValidating(false); Object result = unmarshal(EXTRA_ELEMENTS_STRING); @@ -161,22 +154,19 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { } @Test - public void testObject() throws Exception { - + public void testRootObject() throws Exception { Flights flights = new Flights(); - getCastorUnmarshaller().setObject(flights); + getCastorUnmarshaller().setRootObject(flights); Object result = unmarshalFlights(); - testFlights(result); assertSame("Result Flights is different object.", flights, result); } @Test public void testClearCollectionsTrue() throws Exception { - Flights flights = new Flights(); flights.setFlight(new Flight[]{new Flight()}); - getCastorUnmarshaller().setObject(flights); + getCastorUnmarshaller().setRootObject(flights); getCastorUnmarshaller().setClearCollections(true); Object result = unmarshalFlights(); @@ -188,10 +178,9 @@ public class CastorUnmarshallerTests extends AbstractUnmarshallerTests { @Test @Ignore("Fails on the builder server for some reason") public void testClearCollectionsFalse() throws Exception { - Flights flights = new Flights(); flights.setFlight(new Flight[]{new Flight(), null}); - getCastorUnmarshaller().setObject(flights); + getCastorUnmarshaller().setRootObject(flights); getCastorUnmarshaller().setClearCollections(false); Object result = unmarshalFlights(); From 9e9cdf5f1312a1d80b2809e68c6ce7883c0a3d8d Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 21:10:00 +0100 Subject: [PATCH 210/311] Removed unused XStreamUtils class; direct access to the xstream field in XStreamMarshaller --- .../oxm/xstream/XStreamMarshaller.java | 52 +++++++-------- .../oxm/xstream/XStreamUtils.java | 63 ------------------- 2 files changed, 24 insertions(+), 91 deletions(-) delete mode 100644 spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamUtils.java diff --git a/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java index b53c20a5b9..dd36d17b8b 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -114,7 +114,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin /** * Returns the XStream instance used by this marshaller. */ - public XStream getXStream() { + public final XStream getXStream() { return this.xstream; } @@ -125,7 +125,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin * @see XStream#NO_REFERENCES */ public void setMode(int mode) { - this.getXStream().setMode(mode); + this.xstream.setMode(mode); } /** @@ -137,10 +137,10 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin public void setConverters(ConverterMatcher[] converters) { for (int i = 0; i < converters.length; i++) { if (converters[i] instanceof Converter) { - this.getXStream().registerConverter((Converter) converters[i], i); + this.xstream.registerConverter((Converter) converters[i], i); } else if (converters[i] instanceof SingleValueConverter) { - this.getXStream().registerConverter((SingleValueConverter) converters[i], i); + this.xstream.registerConverter((SingleValueConverter) converters[i], i); } else { throw new IllegalArgumentException("Invalid ConverterMatcher [" + converters[i] + "]"); @@ -155,9 +155,8 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ public void setAliases(Map aliases) throws ClassNotFoundException { Map> classMap = toClassMap(aliases); - for (Map.Entry> entry : classMap.entrySet()) { - this.getXStream().alias(entry.getKey(), entry.getValue()); + this.xstream.alias(entry.getKey(), entry.getValue()); } } @@ -169,15 +168,13 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ public void setAliasesByType(Map aliases) throws ClassNotFoundException { Map> classMap = toClassMap(aliases); - for (Map.Entry> entry : classMap.entrySet()) { - this.getXStream().aliasType(entry.getKey(), entry.getValue()); + this.xstream.aliasType(entry.getKey(), entry.getValue()); } } private Map> toClassMap(Map map) throws ClassNotFoundException { Map> result = new LinkedHashMap>(map.size()); - for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); @@ -198,10 +195,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin } /** - * Sets a field alias/type map, consiting of field names - * @param aliases - * @throws ClassNotFoundException - * @throws NoSuchFieldException + * Set a field alias/type map, consiting of field names. * @see XStream#aliasField(String, Class, String) */ public void setFieldAliases(Map aliases) throws ClassNotFoundException, NoSuchFieldException { @@ -213,8 +207,9 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin String className = field.substring(0, idx); Class clazz = ClassUtils.forName(className, classLoader); String fieldName = field.substring(idx + 1); - this.getXStream().aliasField(alias, clazz, fieldName); - } else { + this.xstream.aliasField(alias, clazz, fieldName); + } + else { throw new IllegalArgumentException("Field name [" + field + "] does not contain '.'"); } } @@ -226,7 +221,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ public void setUseAttributeForTypes(Class[] types) { for (Class type : types) { - this.getXStream().useAttributeFor(type); + this.xstream.useAttributeFor(type); } } @@ -242,7 +237,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin for (Map.Entry entry : attributes.entrySet()) { if (entry.getKey() instanceof String) { if (entry.getValue() instanceof Class) { - this.getXStream().useAttributeFor((String) entry.getKey(), (Class) entry.getValue()); + this.xstream.useAttributeFor((String) entry.getKey(), (Class) entry.getValue()); } else { throw new IllegalArgumentException( @@ -253,14 +248,14 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin else if (entry.getKey() instanceof Class) { Class key = (Class) entry.getKey(); if (entry.getValue() instanceof String) { - this.getXStream().useAttributeFor(key, (String) entry.getValue()); + this.xstream.useAttributeFor(key, (String) entry.getValue()); } else if (entry.getValue() instanceof List) { List list = (List) entry.getValue(); for (Object o : list) { if (o instanceof String) { - this.getXStream().useAttributeFor(key, (String) o); + this.xstream.useAttributeFor(key, (String) o); } } } @@ -286,7 +281,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin for (Map.Entry, String> entry : implicitCollections.entrySet()) { String[] collectionFields = StringUtils.commaDelimitedListToStringArray(entry.getValue()); for (String collectionField : collectionFields) { - this.getXStream().addImplicitCollection(entry.getKey(), collectionField); + this.xstream.addImplicitCollection(entry.getKey(), collectionField); } } } @@ -300,7 +295,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin for (Map.Entry, String> entry : omittedFields.entrySet()) { String[] fields = StringUtils.commaDelimitedListToStringArray(entry.getValue()); for (String field : fields) { - this.getXStream().omitField(entry.getKey(), field); + this.xstream.omitField(entry.getKey(), field); } } } @@ -311,7 +306,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ public void setAnnotatedClass(Class annotatedClass) { Assert.notNull(annotatedClass, "'annotatedClass' must not be null"); - this.getXStream().processAnnotations(annotatedClass); + this.xstream.processAnnotations(annotatedClass); } /** @@ -320,7 +315,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ public void setAnnotatedClasses(Class[] annotatedClasses) { Assert.notEmpty(annotatedClasses, "'annotatedClasses' must not be empty"); - this.getXStream().processAnnotations(annotatedClasses); + this.xstream.processAnnotations(annotatedClasses); } /** @@ -330,7 +325,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin * @see XStream#autodetectAnnotations(boolean) */ public void setAutodetectAnnotations(boolean autodetectAnnotations) { - this.getXStream().autodetectAnnotations(autodetectAnnotations); + this.xstream.autodetectAnnotations(autodetectAnnotations); } /** @@ -363,7 +358,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin public final void afterPropertiesSet() throws Exception { - customizeXStream(getXStream()); + customizeXStream(this.xstream); } /** @@ -458,7 +453,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ private void marshal(Object graph, HierarchicalStreamWriter streamWriter) { try { - getXStream().marshal(graph, streamWriter); + this.xstream.marshal(graph, streamWriter); } catch (Exception ex) { throw convertXStreamException(ex, true); @@ -541,7 +536,7 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin */ private Object unmarshal(HierarchicalStreamReader streamReader) { try { - return getXStream().unmarshal(streamReader); + return this.xstream.unmarshal(streamReader); } catch (Exception ex) { throw convertXStreamException(ex, false); @@ -574,4 +569,5 @@ public class XStreamMarshaller extends AbstractMarshaller implements Initializin return new UncategorizedMappingException("Unknown XStream exception", ex); } } + } diff --git a/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamUtils.java b/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamUtils.java deleted file mode 100644 index 04f53b6973..0000000000 --- a/spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamUtils.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2002-2012 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.oxm.xstream; - -import com.thoughtworks.xstream.converters.ConversionException; -import com.thoughtworks.xstream.io.StreamException; -import com.thoughtworks.xstream.mapper.CannotResolveClassException; - -import org.springframework.oxm.MarshallingFailureException; -import org.springframework.oxm.UncategorizedMappingException; -import org.springframework.oxm.UnmarshallingFailureException; -import org.springframework.oxm.XmlMappingException; - -/** - * Generic utility methods for working with XStream. Mainly for internal use within the framework. - * - * @author Arjen Poutsma - * @author Juergen Hoeller - * @since 3.0 - */ -abstract class XStreamUtils { - - /** - * Convert the given XStream exception to an appropriate exception from the - * {@code org.springframework.oxm} hierarchy. - *

A boolean flag is used to indicate whether this exception occurs during marshalling or - * unmarshalling, since XStream itself does not make this distinction in its exception hierarchy. - * @param ex XStream exception that occured - * @param marshalling indicates whether the exception occurs during marshalling ({@code true}), - * or unmarshalling ({@code false}) - * @return the corresponding {@code XmlMappingException} - */ - public static XmlMappingException convertXStreamException(Exception ex, boolean marshalling) { - if (ex instanceof StreamException || ex instanceof CannotResolveClassException || - ex instanceof ConversionException) { - if (marshalling) { - return new MarshallingFailureException("XStream marshalling exception", ex); - } - else { - return new UnmarshallingFailureException("XStream unmarshalling exception", ex); - } - } - else { - // fallback - return new UncategorizedMappingException("Unknown XStream exception", ex); - } - } - -} From aa576e70be718413573486e1704f7e19aff9acdf Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 21:10:51 +0100 Subject: [PATCH 211/311] Fixed test class name --- ...ressionEvalutatorTest.java => ExpressionEvaluatorTests.java} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename spring-context/src/test/java/org/springframework/cache/interceptor/{ExpressionEvalutatorTest.java => ExpressionEvaluatorTests.java} (99%) diff --git a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java similarity index 99% rename from spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java rename to spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java index 0a664afac0..44762719bc 100644 --- a/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvalutatorTest.java +++ b/spring-context/src/test/java/org/springframework/cache/interceptor/ExpressionEvaluatorTests.java @@ -44,7 +44,7 @@ import edu.emory.mathcs.backport.java.util.Collections; * @author Costin Leau * @author Phillip Webb */ -public class ExpressionEvalutatorTest { +public class ExpressionEvaluatorTests { @Rule public ExpectedException thrown = ExpectedException.none(); From e9db7857990faf04ede61e973ad6422eb33ea915 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 21:10:58 +0100 Subject: [PATCH 212/311] Polishing --- .../scheduling/support/CronTrigger.java | 12 ++++++------ .../springframework/core/GenericTypeResolver.java | 3 +-- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java b/spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java index eca37982e6..94f6385a1a 100644 --- a/spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java +++ b/spring-context/src/main/java/org/springframework/scheduling/support/CronTrigger.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,12 @@ package org.springframework.scheduling.support; -import java.util.Date; -import java.util.TimeZone; - import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; +import java.util.Date; +import java.util.TimeZone; + /** * {@link Trigger} implementation for cron expressions. * Wraps a {@link CronSequenceGenerator}. @@ -41,7 +41,7 @@ public class CronTrigger implements Trigger { * following cron expression conventions */ public CronTrigger(String cronExpression) { - this(cronExpression, TimeZone.getDefault()); + this.sequenceGenerator = new CronSequenceGenerator(cronExpression); } /** @@ -89,7 +89,7 @@ public class CronTrigger implements Trigger { @Override public String toString() { - return sequenceGenerator.toString(); + return this.sequenceGenerator.toString(); } } diff --git a/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java b/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java index 3842a741c7..7d8045b51b 100644 --- a/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java +++ b/spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java @@ -369,8 +369,7 @@ public abstract class GenericTypeResolver { * all super types, enclosing types and interfaces. */ public static Map getTypeVariableMap(Class clazz) { - Map ref = typeVariableCache.get(clazz); - Map typeVariableMap = (ref != null ? ref : null); + Map typeVariableMap = typeVariableCache.get(clazz); if (typeVariableMap == null) { typeVariableMap = new HashMap(); From 00a3420c6f80d2ca20b08c4b4c2627b70f332e4e Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 21:11:13 +0100 Subject: [PATCH 213/311] CastorMarshaller etc --- src/dist/changelog.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 370c5614bc..6cbfe51eb7 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -17,11 +17,14 @@ Changes in version 3.2.2 (2013-03-07) * @Async's qualifier works for target class annotations behind a JDK proxy as well (SPR-10274) * @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support (SPR-8067) * refined CronSequenceGenerator's rounding up of seconds to address second-specific cron expressions (SPR-9459) +* @Transactional in AspectJ mode works with CallbackPreferringPlatformTransactionManager (WebSphere) as well (SPR-9268) * SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) * deprecated (NamedParameter)JdbcTemplate's queryForInt/Long operations in favor of queryForObject (SPR-10257) * added useful query variants without parameters to NamedParameterJdbcTemplate, for convenience in DAOs (SPR-10256) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) +* added "entityResolver", "classDescriptorResolver", "doctypes" and further properties to CastorMarshaller (SPR-8470) +* deprecated CastorMarshaller's "object" property in favor of "rootObject" (SPR-8470) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) * marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) * MappingJackson(2)JsonView allows subclasses to access the ObjectMapper and to override content writing (SPR-7619) From 2642cf2e05e7851acf4727c09b7c0d5dc71dcde4 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sun, 10 Feb 2013 00:12:36 -0800 Subject: [PATCH 214/311] Replace EasyMock with Mockito in spring-jms Issue: SPR-10126 --- build.gradle | 2 +- .../jms/config/JmsNamespaceHandlerTests.java | 53 +- .../JmsTransactionManagerTests.java | 361 +++------ .../SingleConnectionFactoryTests.java | 475 ++++-------- .../jms/core/JmsTemplate102Tests.java | 712 +++++++----------- .../jms/core/JmsTemplateTests.java | 486 +++++------- .../core/support/JmsGatewaySupportTests.java | 20 +- .../SimpleMessageListenerContainerTests.java | 427 ++++------- .../MessageListenerAdapter102Tests.java | 355 +++------ .../adapter/MessageListenerAdapterTests.java | 483 ++++-------- .../DefaultJmsActivationSpecFactoryTests.java | 14 +- .../jms/remoting/JmsInvokerTests.java | 75 +- .../SimpleMessageConverter102Tests.java | 60 +- .../support/SimpleMessageConverterTests.java | 162 ++-- .../MappingJackson2MessageConverterTests.java | 128 ++-- .../MappingJacksonMessageConverterTests.java | 126 ++-- .../MarshallingMessageConverterTests.java | 62 +- .../DynamicDestinationResolverTests.java | 54 +- .../JmsDestinationAccessorTests.java | 16 +- .../JndiDestinationResolverTests.java | 54 +- 20 files changed, 1385 insertions(+), 2740 deletions(-) diff --git a/build.gradle b/build.gradle index bf2977c699..b6e1b8a03f 100644 --- a/build.gradle +++ b/build.gradle @@ -69,7 +69,7 @@ configure(allprojects) { project -> testCompile("junit:junit:${junitVersion}") testCompile("org.hamcrest:hamcrest-all:1.3") testCompile("org.mockito:mockito-core:1.9.5") - if (project.name in ["spring", "spring-jms", + if (project.name in ["spring", "spring-orm-hibernate4", "spring-oxm", "spring-struts", "spring-test", "spring-test-mvc", "spring-tx", "spring-web", "spring-webmvc", "spring-webmvc-portlet", "spring-webmvc-tiles3"]) { diff --git a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java index 49cf841b4e..a8c89b525e 100644 --- a/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java @@ -16,20 +16,28 @@ package org.springframework.jms.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; + import javax.jms.ConnectionFactory; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Before; +import org.junit.Test; import org.springframework.beans.DirectFieldAccessor; -import org.springframework.tests.sample.beans.TestBean; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.parsing.ComponentDefinition; import org.springframework.beans.factory.parsing.CompositeComponentDefinition; @@ -42,6 +50,7 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jca.endpoint.GenericMessageEndpointManager; import org.springframework.jms.listener.DefaultMessageListenerContainer; import org.springframework.jms.listener.endpoint.JmsMessageEndpointManager; +import org.springframework.tests.sample.beans.TestBean; import org.springframework.util.ErrorHandler; /** @@ -49,7 +58,7 @@ import org.springframework.util.ErrorHandler; * @author Juergen Hoeller * @author Christian Dupuis */ -public class JmsNamespaceHandlerTests extends TestCase { +public class JmsNamespaceHandlerTests { private static final String DEFAULT_CONNECTION_FACTORY = "connectionFactory"; @@ -58,17 +67,18 @@ public class JmsNamespaceHandlerTests extends TestCase { private ToolingTestApplicationContext context; - @Override - protected void setUp() throws Exception { + @Before + public void setUp() throws Exception { this.context = new ToolingTestApplicationContext("jmsNamespaceHandlerTests.xml", getClass()); } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { this.context.close(); } + @Test public void testBeansCreated() { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); assertEquals("Context should contain 3 JMS listener containers", 3, containers.size()); @@ -77,6 +87,7 @@ public class JmsNamespaceHandlerTests extends TestCase { assertEquals("Context should contain 3 JCA endpoint containers", 3, containers.size()); } + @Test public void testContainerConfiguration() throws Exception { Map containers = context.getBeansOfType(DefaultMessageListenerContainer.class); ConnectionFactory defaultConnectionFactory = context.getBean(DEFAULT_CONNECTION_FACTORY, ConnectionFactory.class); @@ -102,6 +113,7 @@ public class JmsNamespaceHandlerTests extends TestCase { assertEquals("2 containers should have the explicit connectionFactory", 2, explicitConnectionFactoryCount); } + @Test public void testListeners() throws Exception { TestBean testBean1 = context.getBean("testBean1", TestBean.class); TestBean testBean2 = context.getBean("testBean2", TestBean.class); @@ -111,36 +123,28 @@ public class JmsNamespaceHandlerTests extends TestCase { assertNull(testBean2.getName()); assertNull(testBean3.message); - MockControl control1 = MockControl.createControl(TextMessage.class); - TextMessage message1 = (TextMessage) control1.getMock(); - control1.expectAndReturn(message1.getText(), "Test1"); - control1.replay(); + TextMessage message1 = mock(TextMessage.class); + given(message1.getText()).willReturn("Test1"); MessageListener listener1 = getListener("listener1"); listener1.onMessage(message1); assertEquals("Test1", testBean1.getName()); - control1.verify(); - MockControl control2 = MockControl.createControl(TextMessage.class); - TextMessage message2 = (TextMessage) control2.getMock(); - control2.expectAndReturn(message2.getText(), "Test2"); - control2.replay(); + TextMessage message2 = mock(TextMessage.class); + given(message2.getText()).willReturn("Test2"); MessageListener listener2 = getListener("listener2"); listener2.onMessage(message2); assertEquals("Test2", testBean2.getName()); - control2.verify(); - MockControl control3 = MockControl.createControl(TextMessage.class); - TextMessage message3 = (TextMessage) control3.getMock(); - control3.replay(); + TextMessage message3 = mock(TextMessage.class); MessageListener listener3 = getListener(DefaultMessageListenerContainer.class.getName() + "#0"); listener3.onMessage(message3); assertSame(message3, testBean3.message); - control3.verify(); } + @Test public void testErrorHandlers() { ErrorHandler expected = this.context.getBean("testErrorHandler", ErrorHandler.class); ErrorHandler errorHandler1 = getErrorHandler("listener1"); @@ -151,6 +155,7 @@ public class JmsNamespaceHandlerTests extends TestCase { assertNull(defaultErrorHandler); } + @Test public void testPhases() { int phase1 = getPhase("listener1"); int phase2 = getPhase("listener2"); @@ -182,6 +187,7 @@ public class JmsNamespaceHandlerTests extends TestCase { return ((Phased) container).getPhase(); } + @Test public void testComponentRegistration() { assertTrue("Parser should have registered a component named 'listener1'", context.containsComponentDefinition("listener1")); assertTrue("Parser should have registered a component named 'listener2'", context.containsComponentDefinition("listener2")); @@ -192,6 +198,7 @@ public class JmsNamespaceHandlerTests extends TestCase { context.containsComponentDefinition(JmsMessageEndpointManager.class.getName() + "#0")); } + @Test public void testSourceExtraction() { Iterator iterator = context.getRegisteredComponents(); while (iterator.hasNext()) { diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java index 78c0de6e9f..cd53ab37a3 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/JmsTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.jms.connection; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; @@ -30,9 +38,8 @@ import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.After; +import org.junit.Test; import org.springframework.jms.StubQueue; import org.springframework.jms.core.JmsTemplate; import org.springframework.jms.core.JmsTemplate102; @@ -50,30 +57,23 @@ import org.springframework.transaction.support.TransactionTemplate; * @author Juergen Hoeller * @since 26.07.2004 */ -public class JmsTransactionManagerTests extends TestCase { +public class JmsTransactionManagerTests { + @After + public void verifyTransactionSynchronizationManager() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + } + + + @Test public void testTransactionCommit() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -87,33 +87,19 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test public void testTransactionRollback() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.rollback(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -127,33 +113,19 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.rollback(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).rollback(); + verify(session).close(); + verify(con).close(); } + @Test public void testParticipatingTransactionWithCommit() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -180,33 +152,19 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test public void testParticipatingTransactionWithRollbackOnly() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.rollback(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -240,39 +198,21 @@ public class JmsTransactionManagerTests extends TestCase { // expected } - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).rollback(); + verify(session).close(); + verify(con).close(); } + @Test public void testSuspendedTransaction() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); + final ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + final Session session2 = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - con.createSession(false, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session2, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - session2.close(); - session2Control.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(2); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(con.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(session2); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -307,41 +247,21 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(session2).close(); + verify(con, times(2)).close(); } + @Test public void testTransactionSuspension() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - MockControl session2Control = MockControl.createControl(Session.class); - final Session session2 = (Session) session2Control.getMock(); + final ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + final Session session = mock(Session.class); + final Session session2 = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session2, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session2.commit(); - session2Control.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - session2.close(); - session2Control.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(2); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session, session2); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -376,48 +296,27 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session2).commit(); + verify(session).close(); + verify(session2).close(); + verify(con, times(2)).close(); } + @Test public void testTransactionCommitWithMessageProducer() throws JMSException { Destination dest = new StubQueue(); - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl producerControl = MockControl.createControl(MessageProducer.class); - MessageProducer producer = (MessageProducer) producerControl.getMock(); - MockControl messageControl = MockControl.createControl(Message.class); - final Message message = (Message) messageControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + Session session = mock(Session.class); + MessageProducer producer = mock(MessageProducer.class); + final Message message = mock(Message.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.createProducer(dest); - sessionControl.setReturnValue(producer, 1); - producer.send(message); - producerControl.setVoidCallable(1); - session.getTransacted(); - sessionControl.setReturnValue(true, 1); - session.commit(); - sessionControl.setVoidCallable(1); - producer.close(); - producerControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - producerControl.replay(); - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(session.createProducer(dest)).willReturn(producer); + given(session.getTransacted()).willReturn(true); JmsTransactionManager tm = new JmsTransactionManager(cf); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -430,34 +329,22 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - producerControl.verify(); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(producer).send(message); + verify(session).commit(); + verify(producer).close(); + verify(session).close(); + verify(con).close(); } + @Test + @Deprecated public void testTransactionCommit102WithQueue() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) sessionControl.getMock(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + final QueueSession session = mock(QueueSession.class); - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createQueueConnection()).willReturn(con); + given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager102(cf, false); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -471,33 +358,20 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } + @Test + @Deprecated public void testTransactionCommit102WithTopic() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - MockControl sessionControl = MockControl.createControl(TopicSession.class); - final TopicSession session = (TopicSession) sessionControl.getMock(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + final TopicSession session = mock(TopicSession.class); - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(session, 1); - session.commit(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - sessionControl.replay(); - conControl.replay(); - cfControl.replay(); + given(cf.createTopicConnection()).willReturn(con); + given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(session); JmsTransactionManager tm = new JmsTransactionManager102(cf, true); TransactionStatus ts = tm.getTransaction(new DefaultTransactionDefinition()); @@ -511,15 +385,8 @@ public class JmsTransactionManagerTests extends TestCase { }); tm.commit(ts); - sessionControl.verify(); - conControl.verify(); - cfControl.verify(); + verify(session).commit(); + verify(session).close(); + verify(con).close(); } - - @Override - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java index 19912ccc39..a1a40d51e4 100644 --- a/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/connection/SingleConnectionFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,14 @@ package org.springframework.jms.connection; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.ExceptionListener; @@ -28,27 +36,17 @@ import javax.jms.TopicConnection; import javax.jms.TopicConnectionFactory; import javax.jms.TopicSession; -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.Test; /** * @author Juergen Hoeller * @since 26.07.2004 */ -public class SingleConnectionFactoryTests extends TestCase { +public class SingleConnectionFactoryTests { + @Test public void testWithConnection() throws JMSException { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(Connection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); Connection con1 = scf.createConnection(); @@ -61,21 +59,15 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnection() throws JMSException { - MockControl conControl = MockControl.createControl(QueueConnection.class); - Connection con = (QueueConnection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(QueueConnection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); QueueConnection con1 = scf.createQueueConnection(); @@ -88,21 +80,15 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnection() throws JMSException { - MockControl conControl = MockControl.createControl(TopicConnection.class); - Connection con = (TopicConnection) conControl.getMock(); - - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - conControl.replay(); + Connection con = mock(TopicConnection.class); SingleConnectionFactory scf = new SingleConnectionFactory(con); TopicConnection con1 = scf.createTopicConnection(); @@ -115,26 +101,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithConnectionFactory() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -145,27 +123,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnectionFactoryAndJms11Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -176,27 +145,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithQueueConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createQueueConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createQueueConnection(); @@ -207,27 +167,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnectionFactoryAndJms11Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createConnection(); @@ -238,27 +189,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithTopicConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createTopicConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); Connection con1 = scf.createTopicConnection(); @@ -269,29 +211,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithConnectionFactoryAndClientId() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.setClientID("myId"); - conControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setClientId("myId"); @@ -303,32 +234,21 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).setClientID("myId"); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testWithConnectionFactoryAndExceptionListener() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); ExceptionListener listener = new ChainedExceptionListener(); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.setExceptionListener(listener); - conControl.setVoidCallable(1); - con.getExceptionListener(); - conControl.setReturnValue(listener, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.getExceptionListener()).willReturn(listener); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); @@ -343,18 +263,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).setExceptionListener(listener); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testWithConnectionFactoryAndReconnectOnException() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); TestConnection con = new TestConnection(); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setReconnectOnException(true); @@ -366,21 +286,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.start(); scf.destroy(); // should trigger actual close - cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); } + @Test public void testWithConnectionFactoryAndExceptionListenerAndReconnectOnException() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); TestConnection con = new TestConnection(); - TestExceptionListener listener = new TestExceptionListener(); - cf.createConnection(); - cfControl.setReturnValue(con, 2); - cfControl.replay(); + given(cf.createConnection()).willReturn(con); + TestExceptionListener listener = new TestExceptionListener(); SingleConnectionFactory scf = new SingleConnectionFactory(cf); scf.setExceptionListener(listener); scf.setReconnectOnException(true); @@ -392,29 +309,17 @@ public class SingleConnectionFactoryTests extends TestCase { con2.start(); scf.destroy(); // should trigger actual close - cfControl.verify(); assertEquals(2, con.getStartCount()); assertEquals(2, con.getCloseCount()); assertEquals(1, listener.getCount()); } + @Test public void testConnectionFactory102WithQueue() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createQueueConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory102(cf, false); QueueConnection con1 = scf.createQueueConnection(); @@ -425,27 +330,18 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testConnectionFactory102WithTopic() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); + given(cf.createTopicConnection()).willReturn(con); SingleConnectionFactory scf = new SingleConnectionFactory102(cf, true); TopicConnection con1 = scf.createTopicConnection(); @@ -456,45 +352,23 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); + verifyNoMoreInteractions(con); } + @Test public void testCachingConnectionFactory() throws JMSException { - MockControl cfControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory cf = (ConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txSessionControl = MockControl.createControl(Session.class); - Session txSession = (Session) txSessionControl.getMock(); - MockControl nonTxSessionControl = MockControl.createControl(Session.class); - Session nonTxSession = (Session) nonTxSessionControl.getMock(); + ConnectionFactory cf = mock(ConnectionFactory.class); + Connection con = mock(Connection.class); + Session txSession = mock(Session.class); + Session nonTxSession = mock(Session.class); - cf.createConnection(); - cfControl.setReturnValue(con, 1); - con.createSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(txSession, 1); - txSession.getTransacted(); - txSessionControl.setReturnValue(true, 1); - txSession.commit(); - txSessionControl.setVoidCallable(1); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + given(cf.createConnection()).willReturn(con); + given(con.createSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -516,47 +390,25 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).commit(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testCachingConnectionFactoryWithQueueConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(QueueConnectionFactory.class); - QueueConnectionFactory cf = (QueueConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(QueueConnection.class); - QueueConnection con = (QueueConnection) conControl.getMock(); - MockControl txSessionControl = MockControl.createControl(QueueSession.class); - QueueSession txSession = (QueueSession) txSessionControl.getMock(); - MockControl nonTxSessionControl = MockControl.createControl(QueueSession.class); - QueueSession nonTxSession = (QueueSession) nonTxSessionControl.getMock(); + QueueConnectionFactory cf = mock(QueueConnectionFactory.class); + QueueConnection con = mock(QueueConnection.class); + QueueSession txSession = mock(QueueSession.class); + QueueSession nonTxSession = mock(QueueSession.class); - cf.createQueueConnection(); - cfControl.setReturnValue(con, 1); - con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(txSession, 1); - txSession.getTransacted(); - txSessionControl.setReturnValue(true, 1); - txSession.rollback(); - txSessionControl.setVoidCallable(1); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + given(cf.createQueueConnection()).willReturn(con); + given(con.createQueueSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -578,45 +430,25 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).rollback(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } + @Test public void testCachingConnectionFactoryWithTopicConnectionFactoryAndJms102Usage() throws JMSException { - MockControl cfControl = MockControl.createControl(TopicConnectionFactory.class); - TopicConnectionFactory cf = (TopicConnectionFactory) cfControl.getMock(); - MockControl conControl = MockControl.createControl(TopicConnection.class); - TopicConnection con = (TopicConnection) conControl.getMock(); - MockControl txSessionControl = MockControl.createControl(TopicSession.class); - TopicSession txSession = (TopicSession) txSessionControl.getMock(); - MockControl nonTxSessionControl = MockControl.createControl(TopicSession.class); - TopicSession nonTxSession = (TopicSession) nonTxSessionControl.getMock(); + TopicConnectionFactory cf = mock(TopicConnectionFactory.class); + TopicConnection con = mock(TopicConnection.class); + TopicSession txSession = mock(TopicSession.class); + TopicSession nonTxSession = mock(TopicSession.class); - cf.createTopicConnection(); - cfControl.setReturnValue(con, 1); - con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE); - conControl.setReturnValue(txSession, 1); - txSession.getTransacted(); - txSessionControl.setReturnValue(true, 2); - txSession.close(); - txSessionControl.setVoidCallable(1); - con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); - conControl.setReturnValue(nonTxSession, 1); - nonTxSession.close(); - nonTxSessionControl.setVoidCallable(1); - con.start(); - conControl.setVoidCallable(1); - con.stop(); - conControl.setVoidCallable(1); - con.close(); - conControl.setVoidCallable(1); - - cfControl.replay(); - conControl.replay(); - txSessionControl.replay(); - nonTxSessionControl.replay(); + given(cf.createTopicConnection()).willReturn(con); + given(con.createTopicSession(true, Session.AUTO_ACKNOWLEDGE)).willReturn(txSession); + given(txSession.getTransacted()).willReturn(true); + given(con.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE)).willReturn(nonTxSession); CachingConnectionFactory scf = new CachingConnectionFactory(cf); scf.setReconnectOnException(false); @@ -638,10 +470,11 @@ public class SingleConnectionFactoryTests extends TestCase { con2.close(); // should be ignored scf.destroy(); // should trigger actual close - cfControl.verify(); - conControl.verify(); - txSessionControl.verify(); - nonTxSessionControl.verify(); + verify(txSession).close(); + verify(nonTxSession).close(); + verify(con).start(); + verify(con).stop(); + verify(con).close(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java index 12f01be2b5..cbf03b7aba 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplate102Tests.java @@ -16,6 +16,15 @@ package org.springframework.jms.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; @@ -39,9 +48,8 @@ import javax.jms.TopicSubscriber; import javax.naming.Context; import javax.naming.NamingException; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.InvalidClientIDException; import org.springframework.jms.InvalidDestinationException; import org.springframework.jms.InvalidSelectorException; @@ -65,105 +73,54 @@ import org.springframework.jndi.JndiTemplate; * @author Andre Biryukov * @author Mark Pollack */ -public class JmsTemplate102Tests extends TestCase { +public class JmsTemplate102Tests { - private Context mockJndiContext; - private MockControl mockJndiControl; - - private MockControl queueConnectionFactoryControl; - private QueueConnectionFactory mockQueueConnectionFactory; - - private MockControl queueConnectionControl; - private QueueConnection mockQueueConnection; - - private MockControl queueSessionControl; - private QueueSession mockQueueSession; - - private MockControl queueControl; - private Queue mockQueue; - - private MockControl topicConnectionFactoryControl; - private TopicConnectionFactory mockTopicConnectionFactory; - - private MockControl topicConnectionControl; - private TopicConnection mockTopicConnection; - - private MockControl topicSessionControl; - private TopicSession mockTopicSession; - - private MockControl topicControl; - private Topic mockTopic; + private Context jndiContext; + private QueueConnectionFactory queueConnectionFactory; + private QueueConnection queueConnection; + private QueueSession queueSession; + private Queue queue; + private TopicConnectionFactory topicConnectionFactory; + private TopicConnection topicConnection; + private TopicSession topicSession; + private Topic topic; private int deliveryMode = DeliveryMode.PERSISTENT; private int priority = 9; private int timeToLive = 10000; - /** - * Create the mock objects for testing. - */ - @Override - protected void setUp() throws Exception { - mockJndiControl = MockControl.createControl(Context.class); - mockJndiContext = (Context) this.mockJndiControl.getMock(); - + @Before + public void setUpMocks() throws Exception { + jndiContext = mock(Context.class); createMockForQueues(); createMockForTopics(); - - mockJndiContext.close(); - mockJndiControl.replay(); } private void createMockForTopics() throws JMSException, NamingException { - topicConnectionFactoryControl = MockControl.createControl(TopicConnectionFactory.class); - mockTopicConnectionFactory = (TopicConnectionFactory) topicConnectionFactoryControl.getMock(); + topicConnectionFactory = mock(TopicConnectionFactory.class); + topicConnection = mock(TopicConnection.class); + topic = mock(Topic.class); + topicSession = mock(TopicSession.class); - topicConnectionControl = MockControl.createControl(TopicConnection.class); - mockTopicConnection = (TopicConnection) topicConnectionControl.getMock(); - - topicControl = MockControl.createControl(Topic.class); - mockTopic = (Topic) topicControl.getMock(); - - topicSessionControl = MockControl.createControl(TopicSession.class); - mockTopicSession = (TopicSession) topicSessionControl.getMock(); - - mockTopicConnectionFactory.createTopicConnection(); - topicConnectionFactoryControl.setReturnValue(mockTopicConnection); - topicConnectionFactoryControl.replay(); - - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - topicConnectionControl.setReturnValue(mockTopicSession); - mockTopicSession.getTransacted(); - topicSessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testTopic"); - mockJndiControl.setReturnValue(mockTopic); + given(topicConnectionFactory.createTopicConnection()).willReturn(topicConnection); + given(topicConnection.createTopicSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(topicSession); + given(topicSession.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testTopic")).willReturn(topic); } private void createMockForQueues() throws JMSException, NamingException { - queueConnectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class); - mockQueueConnectionFactory = (QueueConnectionFactory) queueConnectionFactoryControl.getMock(); + queueConnectionFactory = mock(QueueConnectionFactory.class); + queueConnection = mock(QueueConnection.class); + queue = mock(Queue.class); + queueSession = mock(QueueSession.class); - queueConnectionControl = MockControl.createControl(QueueConnection.class); - mockQueueConnection = (QueueConnection) queueConnectionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - queueSessionControl = MockControl.createControl(QueueSession.class); - mockQueueSession = (QueueSession) queueSessionControl.getMock(); - - mockQueueConnectionFactory.createQueueConnection(); - queueConnectionFactoryControl.setReturnValue(mockQueueConnection); - queueConnectionFactoryControl.replay(); - - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - queueConnectionControl.setReturnValue(mockQueueSession); - mockQueueSession.getTransacted(); - queueSessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testQueue"); - mockJndiControl.setReturnValue(mockQueue); + given(queueConnectionFactory.createQueueConnection()).willReturn(queueConnection); + given(queueConnection.createQueueSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(queueSession); + given(queueSession.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testQueue")).willReturn(queue); } private JmsTemplate102 createTemplate() { @@ -172,7 +129,7 @@ public class JmsTemplate102Tests extends TestCase { destMan.setJndiTemplate(new JndiTemplate() { @Override protected Context createInitialContext() { - return mockJndiContext; + return jndiContext; } }); template.setDestinationResolver(destMan); @@ -189,21 +146,13 @@ public class JmsTemplate102Tests extends TestCase { } + @Test public void testTopicSessionCallback() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicSessionControl.replay(); - topicConnectionControl.replay(); - template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { @@ -212,39 +161,24 @@ public class JmsTemplate102Tests extends TestCase { } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the execute(ProducerCallback) using a topic. */ + @Test public void testTopicProducerCallback() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); + TopicPublisher topicPublisher = mock(TopicPublisher.class); - mockTopicSession.createPublisher(null); - topicSessionControl.setReturnValue(mockTopicPublisher); - - mockTopicPublisher.getPriority(); - topicPublisherControl.setReturnValue(4); - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicPublisherControl.replay(); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(null)).willReturn(topicPublisher); + given(topicPublisher.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -255,45 +189,27 @@ public class JmsTemplate102Tests extends TestCase { } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the execute(ProducerCallback) using a topic. */ + @Test public void testTopicProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); + TopicPublisher topicPublisher = mock(TopicPublisher.class); - mockTopicSession.createPublisher(null); - topicSessionControl.setReturnValue(mockTopicPublisher); - - mockTopicPublisher.setDisableMessageID(true); - topicPublisherControl.setVoidCallable(1); - mockTopicPublisher.setDisableMessageTimestamp(true); - topicPublisherControl.setVoidCallable(1); - mockTopicPublisher.getPriority(); - topicPublisherControl.setReturnValue(4); - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - topicPublisherControl.replay(); - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(null)).willReturn(topicPublisher); + given(topicPublisher.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -304,30 +220,24 @@ public class JmsTemplate102Tests extends TestCase { } }); - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); + verify(topicPublisher).setDisableMessageID(true); + verify(topicPublisher).setDisableMessageTimestamp(true); + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); } /** * Test the method execute(SessionCallback action) with using the * point to point domain as specified by the value of isPubSubDomain = false. */ + @Test public void testQueueSessionCallback() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSessionControl.replay(); - queueConnectionControl.replay(); - template.execute(new SessionCallback() { @Override public Object doInJms(Session session) throws JMSException { @@ -336,39 +246,24 @@ public class JmsTemplate102Tests extends TestCase { } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSession).close(); + verify(queueConnection).close(); } /** * Test the method execute(ProducerCallback) with a Queue. */ + @Test public void testQueueProducerCallback() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain. - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); - mockQueueSession.createSender(null); - queueSessionControl.setReturnValue(mockQueueSender); - - mockQueueSender.getPriority(); - queueSenderControl.setReturnValue(4); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(queueSession.createSender(null)).willReturn(queueSender); + given(queueSender.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -380,42 +275,24 @@ public class JmsTemplate102Tests extends TestCase { } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } + @Test public void testQueueProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate102 template = createTemplate(); // Point-to-Point (queues) are the default domain. - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); template.afterPropertiesSet(); - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); - mockQueueSession.createSender(null); - queueSessionControl.setReturnValue(mockQueueSender); - - mockQueueSender.setDisableMessageID(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.setDisableMessageTimestamp(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.getPriority(); - queueSenderControl.setReturnValue(4); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + given(queueSession.createSender(null)).willReturn(queueSender); + given(queueSender.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -426,19 +303,22 @@ public class JmsTemplate102Tests extends TestCase { } }); - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); + verify(queueSender).setDisableMessageID(true); + verify(queueSender).setDisableMessageTimestamp(true); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } /** * Test the setting of the JmsTemplate properties. */ + @Test public void testBeanProperties() throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); - assertTrue("connection factory ok", template.getConnectionFactory() == mockQueueConnectionFactory); + assertTrue("connection factory ok", template.getConnectionFactory() == queueConnectionFactory); JmsTemplate102 s102 = createTemplate(); try { @@ -452,7 +332,7 @@ public class JmsTemplate102Tests extends TestCase { // The default is for the JmsTemplate102 to send to queues. // Test to make sure exeception is thrown and has reasonable message. s102 = createTemplate(); - s102.setConnectionFactory(mockTopicConnectionFactory); + s102.setConnectionFactory(topicConnectionFactory); try { s102.afterPropertiesSet(); fail("IllegalArgumentException not thrown. Mismatch of Destination and ConnectionFactory types."); @@ -462,7 +342,7 @@ public class JmsTemplate102Tests extends TestCase { } s102 = createTemplate(); - s102.setConnectionFactory(mockQueueConnectionFactory); + s102.setConnectionFactory(queueConnectionFactory); s102.setPubSubDomain(true); try { s102.afterPropertiesSet(); @@ -477,6 +357,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(String destination, MessgaeCreator c) using * a queue and default QOS values. */ + @Test public void testSendStringQueue() throws Exception { sendQueue(true, false, false, true); } @@ -485,6 +366,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(String destination, MessageCreator c) when * explicit QOS parameters are enabled, using a queue. */ + @Test public void testSendStringQueueWithQOS() throws Exception { sendQueue(false, false, false, false); } @@ -492,6 +374,7 @@ public class JmsTemplate102Tests extends TestCase { /** * Test the method send(MessageCreator c) using default QOS values. */ + @Test public void testSendDefaultDestinationQueue() throws Exception { sendQueue(true, false, true, true); } @@ -499,6 +382,7 @@ public class JmsTemplate102Tests extends TestCase { /** * Test the method send(MessageCreator c) using explicit QOS values. */ + @Test public void testSendDefaultDestinationQueueWithQOS() throws Exception { sendQueue(false, false, true, false); } @@ -507,6 +391,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(String destination, MessageCreator c) using * a topic and default QOS values. */ + @Test public void testSendStringTopic() throws Exception { sendTopic(true, false); } @@ -515,6 +400,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(String destination, MessageCreator c) using explicit * QOS values. */ + @Test public void testSendStringTopicWithQOS() throws Exception { sendTopic(false, false); } @@ -523,6 +409,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(Destination queue, MessgaeCreator c) using * a queue and default QOS values. */ + @Test public void testSendQueue() throws Exception { sendQueue(true, false, false, true); } @@ -531,6 +418,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(Destination queue, MessageCreator c) sing explicit * QOS values. */ + @Test public void testSendQueueWithQOS() throws Exception { sendQueue(false, false, false, false); } @@ -539,6 +427,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(Destination queue, MessgaeCreator c) using * a topic and default QOS values. */ + @Test public void testSendTopic() throws Exception { sendTopic(true, false); } @@ -547,6 +436,7 @@ public class JmsTemplate102Tests extends TestCase { * Test the method send(Destination queue, MessageCreator c) using explicity * QOS values. */ + @Test public void testSendTopicWithQOS() throws Exception { sendQueue(false, false, false, true); } @@ -560,62 +450,30 @@ public class JmsTemplate102Tests extends TestCase { throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.afterPropertiesSet(); if (useDefaultDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } if (disableIdAndTimestamp) { template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); } - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage message = mock(TextMessage.class); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - if (disableIdAndTimestamp) { - mockQueueSender.setDisableMessageID(true); - queueSenderControl.setVoidCallable(1); - mockQueueSender.setDisableMessageTimestamp(true); - queueSenderControl.setVoidCallable(1); - } + given(queueSession.createSender(this.queue)).willReturn(queueSender); + given(queueSession.createTextMessage("just testing")).willReturn(message); - mockQueueSession.createSender(this.mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("just testing"); - queueSessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); - } - - if (ignoreQOS) { - mockQueueSender.send(mockMessage); - } - else { + if (!ignoreQOS) { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockQueueSender.send(mockMessage, deliveryMode, priority, timeToLive); } - queueSenderControl.setVoidCallable(1); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); if (useDefaultDestination) { template.send(new MessageCreator() { @@ -627,7 +485,7 @@ public class JmsTemplate102Tests extends TestCase { } else { if (explicitQueue) { - template.send(mockQueue, new MessageCreator() { + template.send(queue, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("just testing"); @@ -645,61 +503,54 @@ public class JmsTemplate102Tests extends TestCase { } } - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - queueSenderControl.verify(); + if (disableIdAndTimestamp) { + verify(queueSender).setDisableMessageID(true); + verify(queueSender).setDisableMessageTimestamp(true); + } + + if (useTransactedTemplate()) { + verify(queueSession).commit(); + } + + if (ignoreQOS) { + verify(queueSender).send(message); + } + else { + verify(queueSender).send(message, deliveryMode, priority, timeToLive); + } + + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } private void sendTopic(boolean ignoreQOS, boolean explicitTopic) throws Exception { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(true); - template.setConnectionFactory(mockTopicConnectionFactory); + template.setConnectionFactory(topicConnectionFactory); template.afterPropertiesSet(); - MockControl topicPublisherControl = MockControl.createControl(TopicPublisher.class); - TopicPublisher mockTopicPublisher = (TopicPublisher) topicPublisherControl.getMock(); + TopicPublisher topicPublisher = mock(TopicPublisher.class); + TextMessage message = mock(TextMessage.class); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); - - mockTopicSession.createPublisher(this.mockTopic); - topicSessionControl.setReturnValue(mockTopicPublisher); - mockTopicSession.createTextMessage("just testing"); - topicSessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockTopicSession.commit(); - topicSessionControl.setVoidCallable(1); - } - - mockTopicPublisher.close(); - topicPublisherControl.setVoidCallable(1); - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - - - topicSessionControl.replay(); - topicConnectionControl.replay(); + given(topicSession.createPublisher(this.topic)).willReturn(topicPublisher); + given(topicSession.createTextMessage("just testing")).willReturn(message); if (ignoreQOS) { - mockTopicPublisher.publish(mockMessage); + topicPublisher.publish(message); } else { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockTopicPublisher.publish(mockMessage, deliveryMode, priority, timeToLive); + topicPublisher.publish(message, deliveryMode, priority, timeToLive); } - topicPublisherControl.replay(); template.setPubSubDomain(true); if (explicitTopic) { - template.send(mockTopic, new MessageCreator() { + template.send(topic, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { @@ -717,163 +568,175 @@ public class JmsTemplate102Tests extends TestCase { }); } - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); - topicPublisherControl.verify(); + if (useTransactedTemplate()) { + verify(topicSession).commit(); + } + verify(topicPublisher).close(); + verify(topicSession).close(); + verify(topicConnection).close(); + verify(jndiContext).close(); } + @Test public void testConverter() throws Exception { JmsTemplate102 template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage message = mock(TextMessage.class); - mockQueueSession.createSender(this.mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("Hello world"); - queueSessionControl.setReturnValue(mockMessage); + given(queueSession.createSender(this.queue)).willReturn(queueSender); + given(queueSession.createTextMessage("Hello world")).willReturn(message); + + template.convertAndSend(queue, s); if (useTransactedTemplate()) { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); + verify(queueSession).commit(); } - - mockQueueSender.send(mockMessage); - queueSenderControl.setVoidCallable(1); - - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); - - template.convertAndSend(mockQueue, s); - - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - queueSenderControl.verify(); + verify(queueSender).send(message); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } + @Test public void testQueueReceiveDefaultDestination() throws Exception { doTestReceive(false, false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveDestination() throws Exception { doTestReceive(false, true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(false, true, false, false, true, false, false, 1000); } + @Test public void testQueueReceiveStringDestination() throws Exception { doTestReceive(false, false, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(false, false, true, false, false, true, true, 1000); } + @Test public void testQueueReceiveDestinationWithSelector() throws Exception { doTestReceive(false, true, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(false, true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveStringDestinationWithSelector() throws Exception { doTestReceive(false, false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(false, false, true, true, false, false, false, 1000); } + @Test public void testQueueReceiveAndConvertStringDestination() throws Exception { doTestReceive(false, false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDestination() throws Exception { doTestReceive(false, true, false, true, false, false, true, 1000); } + @Test public void testQueueReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(false, false, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testQueueReceiveAndConvertStringDestinationWithSelector() throws Exception { doTestReceive(false, false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testQueueReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(false, true, false, true, false, true, false, 1000); } + @Test public void testTopicReceiveDefaultDestination() throws Exception { doTestReceive(true, false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveDestination() throws Exception { doTestReceive(true, true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(true, true, false, false, true, false, false, 1000); } + @Test public void testTopicReceiveStringDestination() throws Exception { doTestReceive(true, false, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testTopicReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(true, false, true, false, false, true, true, 1000); } + @Test public void testTopicReceiveDestinationWithSelector() throws Exception { doTestReceive(true, true, false, false, false, true, false, 1000); } + @Test public void testTopicReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(true, true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveStringDestinationWithSelector() throws Exception { doTestReceive(true, false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(true, false, true, true, false, false, false, 1000); } + @Test public void testTopicReceiveAndConvertStringDestination() throws Exception { doTestReceive(true, false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDestination() throws Exception { doTestReceive(true, true, false, true, false, false, true, 1000); } + @Test public void testTopicReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(true, false, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testTopicReceiveAndConvertStringDestinationWithSelector() throws Exception { doTestReceive(true, false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testTopicReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(true, true, false, true, false, true, false, 1000); } @@ -886,41 +749,38 @@ public class JmsTemplate102Tests extends TestCase { JmsTemplate102 template = createTemplate(); template.setPubSubDomain(pubSub); - if (pubSub) { - template.setConnectionFactory(mockTopicConnectionFactory); - } - else { - template.setConnectionFactory(mockQueueConnectionFactory); - } + template.setConnectionFactory(pubSub ? topicConnectionFactory : queueConnectionFactory); // Override the default settings for client ack used in the test setup. // Can't use Session.getAcknowledgeMode() if (pubSub) { - topicConnectionControl.reset(); + reset(topicConnection); if (clientAcknowledge) { template.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE); + given(topicConnection.createTopicSession( + useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE)).willReturn(topicSession); } else { template.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - mockTopicConnection.createTopicSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); + given(topicConnection.createTopicSession( + useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(topicSession); } - topicConnectionControl.setReturnValue(mockTopicSession); } else { - queueConnectionControl.reset(); + reset(queueConnection); if (clientAcknowledge) { template.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE); + given(queueConnection.createQueueSession( + useTransactedTemplate(), Session.CLIENT_ACKNOWLEDGE)).willReturn(queueSession); } else { template.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE); - mockQueueConnection.createQueueSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); + given(queueConnection.createQueueSession( + useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE)).willReturn(queueSession); } - queueConnectionControl.setReturnValue(mockQueueSession); } - Destination dest = pubSub ? (Destination) mockTopic : (Destination) mockQueue; + Destination dest = pubSub ? (Destination) topic : (Destination) queue; if (useDefaultDestination) { template.setDefaultDestination(dest); @@ -930,94 +790,38 @@ public class JmsTemplate102Tests extends TestCase { } template.setReceiveTimeout(timeout); - if (pubSub) { - mockTopicConnection.start(); - topicConnectionControl.setVoidCallable(1); - mockTopicConnection.close(); - topicConnectionControl.setVoidCallable(1); - } - else { - mockQueueConnection.start(); - queueConnectionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - } String selectorString = "selector"; - MockControl messageConsumerControl = null; - MessageConsumer mockMessageConsumer = null; + MessageConsumer messageConsumer = null; if (pubSub) { - messageConsumerControl = MockControl.createControl(TopicSubscriber.class); - TopicSubscriber mockTopicSubscriber = (TopicSubscriber) messageConsumerControl.getMock(); - mockMessageConsumer = mockTopicSubscriber; - mockTopicSession.createSubscriber(mockTopic, messageSelector ? selectorString : null, noLocal); - topicSessionControl.setReturnValue(mockTopicSubscriber); + TopicSubscriber topicSubscriber = mock(TopicSubscriber.class); + messageConsumer = topicSubscriber; + given(topicSession.createSubscriber(topic, + messageSelector ? selectorString : null, noLocal)).willReturn(topicSubscriber); } else { - messageConsumerControl = MockControl.createControl(QueueReceiver.class); - QueueReceiver mockQueueReceiver = (QueueReceiver) messageConsumerControl.getMock(); - mockMessageConsumer = mockQueueReceiver; - mockQueueSession.createReceiver(mockQueue, messageSelector ? selectorString : null); - queueSessionControl.setReturnValue(mockQueueReceiver); + QueueReceiver queueReceiver = mock(QueueReceiver.class); + messageConsumer = queueReceiver; + given(queueSession.createReceiver(queue, + messageSelector ? selectorString : null)).willReturn(queueReceiver); } - if (useTransactedTemplate()) { - if (pubSub) { - mockTopicSession.commit(); - topicSessionControl.setVoidCallable(1); - } - else { - mockQueueSession.commit(); - queueSessionControl.setVoidCallable(1); - } - } - - if (pubSub) { - mockTopicSession.close(); - topicSessionControl.setVoidCallable(1); - } - else { - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - } - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + TextMessage textMessage = mock(TextMessage.class); if (testConverter) { - mockMessage.getText(); - messageControl.setReturnValue("Hello World!"); + given(textMessage.getText()).willReturn("Hello World!"); } - if (!useTransactedSession() && clientAcknowledge) { - mockMessage.acknowledge(); - messageControl.setVoidCallable(1); - } - - if (pubSub) { - topicSessionControl.replay(); - topicConnectionControl.replay(); - } - else { - queueSessionControl.replay(); - queueConnectionControl.replay(); - } - messageControl.replay(); if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) { - mockMessageConsumer.receiveNoWait(); + given(messageConsumer.receiveNoWait()).willReturn(textMessage); } else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { - mockMessageConsumer.receive(); + given(messageConsumer.receive()).willReturn(textMessage); } else { - mockMessageConsumer.receive(timeout); + given(messageConsumer.receive(timeout)).willReturn(textMessage); } - messageConsumerControl.setReturnValue(mockMessage); - mockMessageConsumer.close(); - messageConsumerControl.setVoidCallable(1); - - messageConsumerControl.replay(); Message message = null; String textFromMessage = null; @@ -1056,112 +860,123 @@ public class JmsTemplate102Tests extends TestCase { } } - if (pubSub) { - topicConnectionFactoryControl.verify(); - topicConnectionControl.verify(); - topicSessionControl.verify(); - } - else { - queueConnectionFactoryControl.verify(); - queueConnectionControl.verify(); - queueSessionControl.verify(); - } - messageConsumerControl.verify(); - messageControl.verify(); - if (testConverter) { assertEquals("Message text should be equal", "Hello World!", textFromMessage); } else { - assertEquals("Messages should refer to the same object", message, mockMessage); + assertEquals("Messages should refer to the same object", message, textMessage); } + + if (pubSub) { + verify(topicConnection).start(); + verify(topicConnection).close(); + verify(topicSession).close(); + } + else { + verify(queueConnection).start(); + verify(queueConnection).close(); + verify(queueSession).close(); + } + + + if (useTransactedTemplate()) { + if (pubSub) { + verify(topicSession).commit(); + } + else { + verify(queueSession).commit(); + } + } + + if (!useTransactedSession() && clientAcknowledge) { + verify(textMessage).acknowledge(); + } + + verify(messageConsumer).close(); } + @Test public void testIllegalStateException() throws Exception { doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class); } + @Test public void testInvalidClientIDException() throws Exception { doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class); } + @Test public void testInvalidDestinationException() throws Exception { doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class); } + @Test public void testInvalidSelectorException() throws Exception { doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class); } + @Test public void testJmsSecurityException() throws Exception { doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class); } + @Test public void testMessageEOFException() throws Exception { doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class); } + @Test public void testMessageFormatException() throws Exception { doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class); } + @Test public void testMessageNotReadableException() throws Exception { doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class); } + @Test public void testMessageNotWriteableException() throws Exception { doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class); } + @Test public void testResourceAllocationException() throws Exception { doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class); } + @Test public void testTransactionInProgressException() throws Exception { doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class); } + @Test public void testTransactionRolledBackException() throws Exception { doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class); } + @Test public void testUncategorizedJmsException() throws Exception { doTestJmsException(new javax.jms.JMSException(""), UncategorizedJmsException.class); } protected void doTestJmsException(JMSException original, Class thrownExceptionClass) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockQueueConnectionFactory); + template.setConnectionFactory(queueConnectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl queueSenderControl = MockControl.createControl(QueueSender.class); - QueueSender mockQueueSender = (QueueSender) queueSenderControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + QueueSender queueSender = mock(QueueSender.class); + TextMessage textMessage = mock(TextMessage.class); - queueSessionControl.reset(); - mockQueueSession.createSender(mockQueue); - queueSessionControl.setReturnValue(mockQueueSender); - mockQueueSession.createTextMessage("Hello world"); - queueSessionControl.setReturnValue(mockMessage); + reset(queueSession); + given(queueSession.createSender(queue)).willReturn(queueSender); + given(queueSession.createTextMessage("Hello world")).willReturn(textMessage); - mockQueueSender.send(mockMessage); - queueSenderControl.setThrowable(original, 1); - mockQueueSender.close(); - queueSenderControl.setVoidCallable(1); - - mockQueueSession.close(); - queueSessionControl.setVoidCallable(1); - mockQueueConnection.close(); - queueConnectionControl.setVoidCallable(1); - - queueSenderControl.replay(); - queueSessionControl.replay(); - queueConnectionControl.replay(); + willThrow(original).given(queueSender).send(textMessage); try { - template.convertAndSend(mockQueue, s); + template.convertAndSend(queue, s); fail("Should have thrown JmsException"); } catch (JmsException wrappedEx) { @@ -1170,10 +985,9 @@ public class JmsTemplate102Tests extends TestCase { assertEquals(original, wrappedEx.getCause()); } - queueSenderControl.verify(); - queueSessionControl.verify(); - queueConnectionControl.verify(); - queueConnectionFactoryControl.verify(); + verify(queueSender).close(); + verify(queueSession).close(); + verify(queueConnection).close(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java index 2ff2c9afda..1ac040f3f8 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/JmsTemplateTests.java @@ -16,6 +16,16 @@ package org.springframework.jms.core; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; @@ -32,11 +42,9 @@ import javax.jms.Queue; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; -import javax.naming.NamingException; - -import junit.framework.TestCase; -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.InvalidClientIDException; import org.springframework.jms.InvalidDestinationException; import org.springframework.jms.InvalidSelectorException; @@ -66,22 +74,13 @@ import org.springframework.transaction.support.TransactionSynchronizationManager * @author Andre Biryukov * @author Mark Pollack */ -public class JmsTemplateTests extends TestCase { +public class JmsTemplateTests { - private Context mockJndiContext; - private MockControl mockJndiControl; - - private MockControl connectionFactoryControl; - private ConnectionFactory mockConnectionFactory; - - private MockControl connectionControl; - private Connection mockConnection; - - private MockControl sessionControl; - private Session mockSession; - - private MockControl queueControl; - private Destination mockQueue; + private Context jndiContext; + private ConnectionFactory connectionFactory; + private Connection connection; + private Session session; + private Destination queue; private int deliveryMode = DeliveryMode.PERSISTENT; private int priority = 9; @@ -91,41 +90,19 @@ public class JmsTemplateTests extends TestCase { /** * Create the mock objects for testing. */ - @Override - protected void setUp() throws Exception { - mockJndiControl = MockControl.createControl(Context.class); - mockJndiContext = (Context) this.mockJndiControl.getMock(); + @Before + public void setupMocks() throws Exception { + jndiContext = mock(Context.class); + connectionFactory = mock(ConnectionFactory.class); + connection = mock(Connection.class); + session = mock(Session.class); + queue = mock(Queue.class); - createMockforDestination(); - - mockJndiContext.close(); - mockJndiControl.replay(); - } - - private void createMockforDestination() throws JMSException, NamingException { - connectionFactoryControl = MockControl.createControl(ConnectionFactory.class); - mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock(); - - connectionControl = MockControl.createControl(Connection.class); - mockConnection = (Connection) connectionControl.getMock(); - - sessionControl = MockControl.createControl(Session.class); - mockSession = (Session) sessionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - mockConnectionFactory.createConnection(); - connectionFactoryControl.setReturnValue(mockConnection); - connectionFactoryControl.replay(); - - mockConnection.createSession(useTransactedTemplate(), Session.AUTO_ACKNOWLEDGE); - connectionControl.setReturnValue(mockSession); - mockSession.getTransacted(); - sessionControl.setReturnValue(useTransactedSession()); - - mockJndiContext.lookup("testDestination"); - mockJndiControl.setReturnValue(mockQueue); + given(connectionFactory.createConnection()).willReturn(connection); + given(connection.createSession(useTransactedTemplate(), + Session.AUTO_ACKNOWLEDGE)).willReturn(session); + given(session.getTransacted()).willReturn(useTransactedSession()); + given(jndiContext.lookup("testDestination")).willReturn(queue); } private JmsTemplate createTemplate() { @@ -134,7 +111,7 @@ public class JmsTemplateTests extends TestCase { destMan.setJndiTemplate(new JndiTemplate() { @Override protected Context createInitialContext() { - return mockJndiContext; + return jndiContext; } }); template.setDestinationResolver(destMan); @@ -151,6 +128,7 @@ public class JmsTemplateTests extends TestCase { } + @Test public void testExceptionStackTrace() { JMSException jmsEx = new JMSException("could not connect"); Exception innerEx = new Exception("host not found"); @@ -163,29 +141,14 @@ public class JmsTemplateTests extends TestCase { assertTrue("inner jms exception not found", trace.indexOf("host not found") > 0); } + @Test public void testProducerCallback() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - - mockSession.createProducer(null); - sessionControl.setReturnValue(mockMessageProducer); - - mockMessageProducer.getPriority(); - messageProducerControl.setReturnValue(4); - - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + MessageProducer messageProducer = mock(MessageProducer.class); + given(session.createProducer(null)).willReturn(messageProducer); + given(messageProducer.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -196,40 +159,21 @@ public class JmsTemplateTests extends TestCase { } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } + @Test public void testProducerCallbackWithIdAndTimestampDisabled() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); template.setMessageIdEnabled(false); template.setMessageTimestampEnabled(false); - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - - mockSession.createProducer(null); - sessionControl.setReturnValue(mockMessageProducer); - - mockMessageProducer.setDisableMessageID(true); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.setDisableMessageTimestamp(true); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.getPriority(); - messageProducerControl.setReturnValue(4); - - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + MessageProducer messageProducer = mock(MessageProducer.class); + given(session.createProducer(null)).willReturn(messageProducer); + given(messageProducer.getPriority()).willReturn(4); template.execute(new ProducerCallback() { @Override @@ -240,26 +184,20 @@ public class JmsTemplateTests extends TestCase { } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(messageProducer).setDisableMessageID(true); + verify(messageProducer).setDisableMessageTimestamp(true); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } /** * Test the method execute(SessionCallback action). */ + @Test public void testSessionCallback() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); - - mockSession.close(); - sessionControl.setVoidCallable(1); - - mockConnection.close(); - connectionControl.setVoidCallable(1); - - sessionControl.replay(); - connectionControl.replay(); + template.setConnectionFactory(connectionFactory); template.execute(new SessionCallback() { @Override @@ -269,35 +207,16 @@ public class JmsTemplateTests extends TestCase { } }); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(session).close(); + verify(connection).close(); } + @Test public void testSessionCallbackWithinSynchronizedTransaction() throws Exception { - SingleConnectionFactory scf = new SingleConnectionFactory(mockConnectionFactory); + SingleConnectionFactory scf = new SingleConnectionFactory(connectionFactory); JmsTemplate template = createTemplate(); template.setConnectionFactory(scf); - mockConnection.start(); - connectionControl.setVoidCallable(1); - // We're gonna call getTransacted 3 times, i.e. 2 more times. - mockSession.getTransacted(); - sessionControl.setReturnValue(useTransactedSession(), 2); - if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); - } - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.stop(); - connectionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - sessionControl.replay(); - connectionControl.replay(); - TransactionSynchronizationManager.initSynchronization(); try { template.execute(new SessionCallback() { @@ -315,8 +234,8 @@ public class JmsTemplateTests extends TestCase { } }); - assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); - assertSame(mockSession, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); + assertSame(session, ConnectionFactoryUtils.getTransactionalSession(scf, null, false)); + assertSame(session, ConnectionFactoryUtils.getTransactionalSession(scf, scf.createConnection(), false)); TransactionAwareConnectionFactoryProxy tacf = new TransactionAwareConnectionFactoryProxy(scf); Connection tac = tacf.createConnection(); @@ -339,15 +258,20 @@ public class JmsTemplateTests extends TestCase { } assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); + verify(connection).start(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + verify(session).close(); + verify(connection).stop(); + verify(connection).close(); } /** * Test sending to a destination using the method * send(Destination d, MessageCreator messageCreator) */ + @Test public void testSendDestination() throws Exception { doTestSendDestination(true, false, true, false); } @@ -356,6 +280,7 @@ public class JmsTemplateTests extends TestCase { * Test seding to a destination using the method * send(String d, MessageCreator messageCreator) */ + @Test public void testSendDestinationName() throws Exception { doTestSendDestination(false, false, true, false); } @@ -364,6 +289,7 @@ public class JmsTemplateTests extends TestCase { * Test sending to a destination using the method * send(Destination d, MessageCreator messageCreator) using QOS parameters. */ + @Test public void testSendDestinationWithQOS() throws Exception { doTestSendDestination(true, false, false, true); } @@ -372,6 +298,7 @@ public class JmsTemplateTests extends TestCase { * Test sending to a destination using the method * send(String d, MessageCreator messageCreator) using QOS parameters. */ + @Test public void testSendDestinationNameWithQOS() throws Exception { doTestSendDestination(false, false, false, true); } @@ -379,6 +306,7 @@ public class JmsTemplateTests extends TestCase { /** * Test sending to the default destination. */ + @Test public void testSendDefaultDestination() throws Exception { doTestSendDestination(true, true, true, true); } @@ -386,6 +314,7 @@ public class JmsTemplateTests extends TestCase { /** * Test sending to the default destination name. */ + @Test public void testSendDefaultDestinationName() throws Exception { doTestSendDestination(false, true, true, true); } @@ -393,6 +322,7 @@ public class JmsTemplateTests extends TestCase { /** * Test sending to the default destination using explicit QOS parameters. */ + @Test public void testSendDefaultDestinationWithQOS() throws Exception { doTestSendDestination(true, true, false, false); } @@ -400,6 +330,7 @@ public class JmsTemplateTests extends TestCase { /** * Test sending to the default destination name using explicit QOS parameters. */ + @Test public void testSendDefaultDestinationNameWithQOS() throws Exception { doTestSendDestination(false, true, false, false); } @@ -414,13 +345,13 @@ public class JmsTemplateTests extends TestCase { boolean ignoreQOS, boolean disableIdAndTimestamp) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); String destinationName = "testDestination"; if (useDefaultDestination) { if (explicitDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } else { template.setDefaultDestinationName(destinationName); @@ -431,51 +362,18 @@ public class JmsTemplateTests extends TestCase { template.setMessageTimestampEnabled(false); } - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("just testing")).willReturn(textMessage); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("just testing"); - sessionControl.setReturnValue(mockMessage); - - if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); - } - - if (disableIdAndTimestamp) { - mockMessageProducer.setDisableMessageID(true); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.setDisableMessageTimestamp(true); - messageProducerControl.setVoidCallable(1); - } - - if (ignoreQOS) { - mockMessageProducer.send(mockMessage); - } - else { + if (!ignoreQOS) { template.setExplicitQosEnabled(true); template.setDeliveryMode(deliveryMode); template.setPriority(priority); template.setTimeToLive(timeToLive); - mockMessageProducer.send(mockMessage, deliveryMode, priority, timeToLive); } - messageProducerControl.setVoidCallable(1); - - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); if (useDefaultDestination) { template.send(new MessageCreator() { @@ -487,7 +385,7 @@ public class JmsTemplateTests extends TestCase { } else { if (explicitDestination) { - template.send(mockQueue, new MessageCreator() { + template.send(queue, new MessageCreator() { @Override public Message createMessage(Session session) throws JMSException { return session.createTextMessage("just testing"); @@ -504,119 +402,131 @@ public class JmsTemplateTests extends TestCase { } } - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); - messageProducerControl.verify(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + + if (disableIdAndTimestamp) { + verify(messageProducer).setDisableMessageID(true); + verify(messageProducer).setDisableMessageTimestamp(true); + } + + if (ignoreQOS) { + verify(messageProducer).send(textMessage); + } + else { + verify(messageProducer).send(textMessage, deliveryMode, priority, timeToLive); + } + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } + @Test public void testConverter() throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("Hello world"); - sessionControl.setReturnValue(mockMessage); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("Hello world")).willReturn(textMessage); - mockMessageProducer.send(mockMessage); - messageProducerControl.setVoidCallable(1); - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); + template.convertAndSend(queue, s); + verify(messageProducer).send(textMessage); + verify(messageProducer).close(); if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); + verify(session).commit(); } - - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); - - template.convertAndSend(mockQueue, s); - - messageProducerControl.verify(); - sessionControl.verify(); - connectionControl.verify(); - connectionFactoryControl.verify(); + verify(session).close(); + verify(connection).close(); } + @Test public void testReceiveDefaultDestination() throws Exception { doTestReceive(true, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDefaultDestinationName() throws Exception { doTestReceive(false, true, false, false, false, false, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestination() throws Exception { doTestReceive(true, false, false, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestinationWithClientAcknowledge() throws Exception { doTestReceive(true, false, false, true, false, false, 1000); } + @Test public void testReceiveDestinationName() throws Exception { doTestReceive(false, false, false, false, false, true, 1000); } + @Test public void testReceiveDefaultDestinationWithSelector() throws Exception { doTestReceive(true, true, false, false, true, true, 1000); } + @Test public void testReceiveDefaultDestinationNameWithSelector() throws Exception { doTestReceive(false, true, false, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveDestinationWithSelector() throws Exception { doTestReceive(true, false, false, false, true, false, 1000); } + @Test public void testReceiveDestinationWithClientAcknowledgeWithSelector() throws Exception { doTestReceive(true, false, false, true, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveDestinationNameWithSelector() throws Exception { doTestReceive(false, false, false, false, true, false, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveAndConvertDefaultDestination() throws Exception { doTestReceive(true, true, true, false, false, false, 1000); } + @Test public void testReceiveAndConvertDefaultDestinationName() throws Exception { doTestReceive(false, true, true, false, false, false, 1000); } + @Test public void testReceiveAndConvertDestinationName() throws Exception { doTestReceive(false, false, true, false, false, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveAndConvertDestination() throws Exception { doTestReceive(true, false, true, false, false, true, 1000); } + @Test public void testReceiveAndConvertDefaultDestinationWithSelector() throws Exception { doTestReceive(true, true, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT); } + @Test public void testReceiveAndConvertDestinationNameWithSelector() throws Exception { doTestReceive(false, false, true, false, true, true, JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT); } + @Test public void testReceiveAndConvertDestinationWithSelector() throws Exception { doTestReceive(true, false, true, false, true, false, 1000); } @@ -627,13 +537,13 @@ public class JmsTemplateTests extends TestCase { throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); String destinationName = "testDestination"; if (useDefaultDestination) { if (explicitDestination) { - template.setDefaultDestination(mockQueue); + template.setDefaultDestination(queue); } else { template.setDefaultDestinationName(destinationName); @@ -644,67 +554,34 @@ public class JmsTemplateTests extends TestCase { } template.setReceiveTimeout(timeout); - mockConnection.start(); - connectionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - MockControl messageConsumerControl = MockControl.createControl(MessageConsumer.class); - MessageConsumer mockMessageConsumer = (MessageConsumer) messageConsumerControl.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); String selectorString = "selector"; - mockSession.createConsumer(mockQueue, messageSelector ? selectorString : null); - sessionControl.setReturnValue(mockMessageConsumer); + given(session.createConsumer(queue, + messageSelector ? selectorString : null)).willReturn(messageConsumer); - if (useTransactedTemplate()) { - mockSession.commit(); - sessionControl.setVoidCallable(1); - } - else if (!useTransactedSession()) { - mockSession.getAcknowledgeMode(); - if (clientAcknowledge) { - sessionControl.setReturnValue(Session.CLIENT_ACKNOWLEDGE, 1); - } - else { - sessionControl.setReturnValue(Session.AUTO_ACKNOWLEDGE, 1); - } + if (!useTransactedTemplate() && !useTransactedSession()) { + given(session.getAcknowledgeMode()).willReturn( + clientAcknowledge ? Session.CLIENT_ACKNOWLEDGE + : Session.AUTO_ACKNOWLEDGE); } - mockSession.close(); - sessionControl.setVoidCallable(1); - - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + TextMessage textMessage = mock(TextMessage.class); if (testConverter) { - mockMessage.getText(); - messageControl.setReturnValue("Hello World!"); + given(textMessage.getText()).willReturn("Hello World!"); } - if (!useTransactedSession() && clientAcknowledge) { - mockMessage.acknowledge(); - messageControl.setVoidCallable(1); - } - - sessionControl.replay(); - connectionControl.replay(); - messageControl.replay(); if (timeout == JmsTemplate.RECEIVE_TIMEOUT_NO_WAIT) { - mockMessageConsumer.receiveNoWait(); + given(messageConsumer.receiveNoWait()).willReturn(textMessage); } else if (timeout == JmsTemplate.RECEIVE_TIMEOUT_INDEFINITE_WAIT) { - mockMessageConsumer.receive(); + given(messageConsumer.receive()).willReturn(textMessage); } else { - mockMessageConsumer.receive(timeout); + given(messageConsumer.receive(timeout)).willReturn(textMessage); } - messageConsumerControl.setReturnValue(mockMessage); - mockMessageConsumer.close(); - messageConsumerControl.setVoidCallable(1); - - messageConsumerControl.replay(); - Message message = null; String textFromMessage = null; @@ -721,12 +598,12 @@ public class JmsTemplateTests extends TestCase { else if (explicitDestination) { if (testConverter) { textFromMessage = (String) - (messageSelector ? template.receiveSelectedAndConvert(mockQueue, selectorString) : - template.receiveAndConvert(mockQueue)); + (messageSelector ? template.receiveSelectedAndConvert(queue, selectorString) : + template.receiveAndConvert(queue)); } else { - message = (messageSelector ? template.receiveSelected(mockQueue, selectorString) : - template.receive(mockQueue)); + message = (messageSelector ? template.receiveSelected(queue, selectorString) : + template.receive(queue)); } } else { @@ -741,105 +618,107 @@ public class JmsTemplateTests extends TestCase { } } - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); - messageConsumerControl.verify(); - messageControl.verify(); - if (testConverter) { assertEquals("Message text should be equal", "Hello World!", textFromMessage); } else { - assertEquals("Messages should refer to the same object", message, mockMessage); + assertEquals("Messages should refer to the same object", message, textMessage); } + + verify(connection).start(); + verify(connection).close(); + if (useTransactedTemplate()) { + verify(session).commit(); + } + verify(session).close(); + if (!useTransactedSession() && clientAcknowledge) { + verify(textMessage).acknowledge(); + } + verify(messageConsumer).close(); } + @Test public void testIllegalStateException() throws Exception { doTestJmsException(new javax.jms.IllegalStateException(""), org.springframework.jms.IllegalStateException.class); } + @Test public void testInvalidClientIDException() throws Exception { doTestJmsException(new javax.jms.InvalidClientIDException(""), InvalidClientIDException.class); } + @Test public void testInvalidDestinationException() throws Exception { doTestJmsException(new javax.jms.InvalidDestinationException(""), InvalidDestinationException.class); } + @Test public void testInvalidSelectorException() throws Exception { doTestJmsException(new javax.jms.InvalidSelectorException(""), InvalidSelectorException.class); } + @Test public void testJmsSecurityException() throws Exception { doTestJmsException(new javax.jms.JMSSecurityException(""), JmsSecurityException.class); } + @Test public void testMessageEOFException() throws Exception { doTestJmsException(new javax.jms.MessageEOFException(""), MessageEOFException.class); } + @Test public void testMessageFormatException() throws Exception { doTestJmsException(new javax.jms.MessageFormatException(""), MessageFormatException.class); } + @Test public void testMessageNotReadableException() throws Exception { doTestJmsException(new javax.jms.MessageNotReadableException(""), MessageNotReadableException.class); } + @Test public void testMessageNotWriteableException() throws Exception { doTestJmsException(new javax.jms.MessageNotWriteableException(""), MessageNotWriteableException.class); } + @Test public void testResourceAllocationException() throws Exception { doTestJmsException(new javax.jms.ResourceAllocationException(""), ResourceAllocationException.class); } + @Test public void testTransactionInProgressException() throws Exception { doTestJmsException(new javax.jms.TransactionInProgressException(""), TransactionInProgressException.class); } + @Test public void testTransactionRolledBackException() throws Exception { doTestJmsException(new javax.jms.TransactionRolledBackException(""), TransactionRolledBackException.class); } + @Test public void testUncategorizedJmsException() throws Exception { doTestJmsException(new javax.jms.JMSException(""), UncategorizedJmsException.class); } protected void doTestJmsException(JMSException original, Class thrownExceptionClass) throws Exception { JmsTemplate template = createTemplate(); - template.setConnectionFactory(mockConnectionFactory); + template.setConnectionFactory(connectionFactory); template.setMessageConverter(new SimpleMessageConverter()); String s = "Hello world"; - MockControl messageProducerControl = MockControl.createControl(MessageProducer.class); - MessageProducer mockMessageProducer = (MessageProducer) messageProducerControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage mockMessage = (TextMessage) messageControl.getMock(); + MessageProducer messageProducer = mock(MessageProducer.class); + TextMessage textMessage = mock(TextMessage.class); - sessionControl.reset(); - mockSession.createProducer(mockQueue); - sessionControl.setReturnValue(mockMessageProducer); - mockSession.createTextMessage("Hello world"); - sessionControl.setReturnValue(mockMessage); + reset(session); + given(session.createProducer(queue)).willReturn(messageProducer); + given(session.createTextMessage("Hello world")).willReturn(textMessage); - mockMessageProducer.send(mockMessage); - messageProducerControl.setThrowable(original, 1); - mockMessageProducer.close(); - messageProducerControl.setVoidCallable(1); - - mockSession.close(); - sessionControl.setVoidCallable(1); - mockConnection.close(); - connectionControl.setVoidCallable(1); - - messageProducerControl.replay(); - sessionControl.replay(); - connectionControl.replay(); + willThrow(original).given(messageProducer).send(textMessage); try { - template.convertAndSend(mockQueue, s); + template.convertAndSend(queue, s); fail("Should have thrown JmsException"); } catch (JmsException wrappedEx) { @@ -848,10 +727,9 @@ public class JmsTemplateTests extends TestCase { assertEquals(original, wrappedEx.getCause()); } - messageProducerControl.verify(); - sessionControl.verify(); - connectionControl.verify(); - connectionFactoryControl.verify(); + verify(messageProducer).close(); + verify(session).close(); + verify(connection).close(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java index 30b71cf182..15eefc873f 100644 --- a/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/core/support/JmsGatewaySupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,26 +15,26 @@ */ package org.springframework.jms.core.support; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + import java.util.ArrayList; import java.util.List; import javax.jms.ConnectionFactory; -import junit.framework.TestCase; -import org.easymock.MockControl; - +import org.junit.Test; import org.springframework.jms.core.JmsTemplate; /** * @author Mark Pollack * @since 24.9.2004 */ -public class JmsGatewaySupportTests extends TestCase { +public class JmsGatewaySupportTests { + @Test public void testJmsGatewaySupportWithConnectionFactory() throws Exception { - MockControl connectionFactoryControl = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory mockConnectionFactory = (ConnectionFactory) connectionFactoryControl.getMock(); - connectionFactoryControl.replay(); + ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class); final List test = new ArrayList(); JmsGatewaySupport gateway = new JmsGatewaySupport() { @Override @@ -47,9 +47,9 @@ public class JmsGatewaySupportTests extends TestCase { assertEquals("Correct ConnectionFactory", mockConnectionFactory, gateway.getConnectionFactory()); assertEquals("Correct JmsTemplate", mockConnectionFactory, gateway.getJmsTemplate().getConnectionFactory()); assertEquals("initGatway called", test.size(), 1); - connectionFactoryControl.verify(); - } + + @Test public void testJmsGatewaySupportWithJmsTemplate() throws Exception { JmsTemplate template = new JmsTemplate(); final List test = new ArrayList(); diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java index 6bd5c57123..8dad2a08e0 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/SimpleMessageListenerContainerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,14 @@ package org.springframework.jms.listener; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import java.util.HashSet; @@ -29,12 +36,8 @@ import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.Session; -import org.easymock.EasyMock; -import org.easymock.MockControl; -import org.easymock.internal.AlwaysMatcher; import org.junit.Before; import org.junit.Test; - import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.task.TaskExecutor; import org.springframework.jms.StubQueue; @@ -91,38 +94,20 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener @Test public void testContextRefreshedEventDoesNotStartTheConnectionIfAutoStartIsSetToFalse() throws Exception { - MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class); - MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock(); - messageConsumer.setMessageListener(null); - // anon. inner class passed in, so just expect a call... - mockMessageConsumer.setMatcher(new AlwaysMatcher()); - mockMessageConsumer.setVoidCallable(); - mockMessageConsumer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - mockSession.replay(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); - mockConnection.replay(); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -134,49 +119,26 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener context.getBeanFactory().registerSingleton("messageListenerContainer", this.container); context.refresh(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); } @Test public void testContextRefreshedEventStartsTheConnectionByDefault() throws Exception { - MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class); - MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock(); - messageConsumer.setMessageListener(null); - // anon. inner class passed in, so just expect a call... - mockMessageConsumer.setMatcher(new AlwaysMatcher()); - mockMessageConsumer.setVoidCallable(); - mockMessageConsumer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - mockSession.replay(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -187,48 +149,31 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener context.getBeanFactory().registerSingleton("messageListenerContainer", this.container); context.refresh(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testCorrectSessionExposedForSessionAwareMessageListenerInvocation() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); + final Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(false); - session.getAcknowledgeMode(); - mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE); - mockSession.replay(); + given(session.getTransacted()).willReturn(false); + given(session.getAcknowledgeMode()).willReturn(Session.AUTO_ACKNOWLEDGE); - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final HashSet failure = new HashSet(); @@ -250,52 +195,33 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener this.container.afterPropertiesSet(); this.container.start(); - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); messageConsumer.sendMessage(message); if (!failure.isEmpty()) { fail(failure.iterator().next().toString()); } - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testTaskExecutorCorrectlyInvokedWhenSpecified() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - session.getTransacted(); - mockSession.setReturnValue(false); - session.getAcknowledgeMode(); - mockSession.setReturnValue(Session.AUTO_ACKNOWLEDGE); - mockSession.replay(); + final Session session = mock(Session.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... + given(session.getTransacted()).willReturn(false); + given(session.getAcknowledgeMode()).willReturn(Session.AUTO_ACKNOWLEDGE); - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); + Connection connection = mock(Connection.class); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - final ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + final ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final TestMessageListener listener = new TestMessageListener(); @@ -314,53 +240,36 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener this.container.afterPropertiesSet(); this.container.start(); - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); messageConsumer.sendMessage(message); assertTrue(listener.executorInvoked); assertTrue(listener.listenerInvoked); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testRegisteredExceptionListenerIsInvokedOnException() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(false); - mockSession.replay(); + given(session.getTransacted()).willReturn(false); - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final JMSException theException = new JMSException(EXCEPTION_MESSAGE); @@ -373,61 +282,44 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener } }); - MockControl mockExceptionListener = MockControl.createControl(ExceptionListener.class); - ExceptionListener exceptionListener = (ExceptionListener) mockExceptionListener.getMock(); - exceptionListener.onException(theException); - mockExceptionListener.setVoidCallable(); - mockExceptionListener.replay(); + ExceptionListener exceptionListener = mock(ExceptionListener.class); this.container.setExceptionListener(exceptionListener); this.container.afterPropertiesSet(); this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockExceptionListener.verify(); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(exceptionListener).onException(theException); } @Test public void testRegisteredErrorHandlerIsInvokedOnException() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - Session session = EasyMock.createMock(Session.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - EasyMock.expectLastCall().andReturn(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - EasyMock.expectLastCall().andReturn(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - EasyMock.expectLastCall().andReturn(false); - EasyMock.replay(session); + given(session.getTransacted()).willReturn(false); - Connection connection = EasyMock.createMock(Connection.class); - connection.setExceptionListener(this.container); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - EasyMock.expectLastCall().andReturn(session); - // and the connection is start()ed after the listener is registered... - connection.start(); - EasyMock.replay(connection); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); - ConnectionFactory connectionFactory = EasyMock.createMock(ConnectionFactory.class); - connectionFactory.createConnection(); - EasyMock.expectLastCall().andReturn(connection); - EasyMock.replay(connectionFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); final IllegalStateException theException = new IllegalStateException("intentional test failure"); @@ -440,58 +332,42 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener } }); - ErrorHandler errorHandler = EasyMock.createMock(ErrorHandler.class); - errorHandler.handleError(theException); - EasyMock.expectLastCall(); - EasyMock.replay(errorHandler); + ErrorHandler errorHandler = mock(ErrorHandler.class); this.container.setErrorHandler(errorHandler); this.container.afterPropertiesSet(); this.container.start(); // manually trigger an Exception with the above bad MessageListener... - Message message = EasyMock.createMock(Message.class); - EasyMock.replay(message); + Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - EasyMock.verify(errorHandler, message, session, connection, connectionFactory); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(errorHandler).handleError(theException); } @Test public void testNoRollbackOccursIfSessionIsNotTransactedAndThatExceptionsDo_NOT_Propagate() throws Exception { final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(false); - mockSession.replay(); + given(session.getTransacted()).willReturn(false); - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -505,17 +381,13 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test @@ -524,39 +396,22 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener final SimpleMessageConsumer messageConsumer = new SimpleMessageConsumer(); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... // an exception is thrown, so the rollback logic is being applied here... - session.getTransacted(); - mockSession.setReturnValue(true); - // Session is rolled back 'cos it is transacted... - session.rollback(); - mockSession.setVoidCallable(); - mockSession.replay(); + given(session.getTransacted()).willReturn(true); - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -570,65 +425,34 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener this.container.start(); // manually trigger an Exception with the above bad MessageListener... - MockControl mockMessage = MockControl.createControl(Message.class); - final Message message = (Message) mockMessage.getMock(); - mockMessage.replay(); + final Message message = mock(Message.class); // a Throwable from a MessageListener MUST simply be swallowed... messageConsumer.sendMessage(message); - mockMessage.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + // Session is rolled back 'cos it is transacted... + verify(session).rollback(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); } @Test public void testDestroyClosesConsumersSessionsAndConnectionInThatOrder() throws Exception { - MockControl mockMessageConsumer = MockControl.createControl(MessageConsumer.class); - MessageConsumer messageConsumer = (MessageConsumer) mockMessageConsumer.getMock(); - messageConsumer.setMessageListener(null); - // anon. inner class passed in, so just expect a call... - mockMessageConsumer.setMatcher(new AlwaysMatcher()); - mockMessageConsumer.setVoidCallable(); - // closing down... - messageConsumer.close(); - mockMessageConsumer.setVoidCallable(); - mockMessageConsumer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); + MessageConsumer messageConsumer = mock(MessageConsumer.class); + Session session = mock(Session.class); // Queue gets created in order to create MessageConsumer for that Destination... - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(QUEUE_DESTINATION); + given(session.createQueue(DESTINATION_NAME)).willReturn(QUEUE_DESTINATION); // and then the MessageConsumer gets created... - session.createConsumer(QUEUE_DESTINATION, null); // no MessageSelector... - mockSession.setReturnValue(messageConsumer); - // closing down... - session.close(); - mockSession.setVoidCallable(); - mockSession.replay(); + given(session.createConsumer(QUEUE_DESTINATION, null)).willReturn(messageConsumer); // no MessageSelector... - MockControl mockConnection = MockControl.createControl(Connection.class); - Connection connection = (Connection) mockConnection.getMock(); - connection.setExceptionListener(this.container); - mockConnection.setVoidCallable(); + Connection connection = mock(Connection.class); // session gets created in order to register MessageListener... - connection.createSession(this.container.isSessionTransacted(), this.container.getSessionAcknowledgeMode()); - mockConnection.setReturnValue(session); + given(connection.createSession(this.container.isSessionTransacted(), + this.container.getSessionAcknowledgeMode())).willReturn(session); // and the connection is start()ed after the listener is registered... - connection.start(); - mockConnection.setVoidCallable(); - // closing down... - connection.close(); - mockConnection.setVoidCallable(); - mockConnection.replay(); - MockControl mockConnectionFactory = MockControl.createControl(ConnectionFactory.class); - ConnectionFactory connectionFactory = (ConnectionFactory) mockConnectionFactory.getMock(); - connectionFactory.createConnection(); - mockConnectionFactory.setReturnValue(connection); - mockConnectionFactory.replay(); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); + given(connectionFactory.createConnection()).willReturn(connection); this.container.setConnectionFactory(connectionFactory); this.container.setDestinationName(DESTINATION_NAME); @@ -638,10 +462,11 @@ public class SimpleMessageListenerContainerTests extends AbstractMessageListener this.container.start(); this.container.destroy(); - mockMessageConsumer.verify(); - mockSession.verify(); - mockConnection.verify(); - mockConnectionFactory.verify(); + verify(messageConsumer).close(); + verify(session).close(); + verify(connection).setExceptionListener(this.container); + verify(connection).start(); + verify(connection).close(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java index a41851b5ec..0781e2916d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapter102Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,13 @@ package org.springframework.jms.listener.adapter; import static org.junit.Assert.*; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import javax.jms.BytesMessage; import javax.jms.InvalidDestinationException; @@ -30,8 +37,9 @@ import javax.jms.Topic; import javax.jms.TopicPublisher; import javax.jms.TopicSession; -import org.easymock.MockControl; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.SimpleMessageConverter102; /** @@ -40,6 +48,7 @@ import org.springframework.jms.support.converter.SimpleMessageConverter102; * @author Rick Evans * @author Chris Beams */ +@Deprecated public final class MessageListenerAdapter102Tests { private static final String TEXT = "The Runaways"; @@ -50,48 +59,36 @@ public final class MessageListenerAdapter102Tests { @Test public void testWithMessageContentsDelegateForBytesMessage() throws Exception { - MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class); - BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock(); + BytesMessage bytesMessage = mock(BytesMessage.class); // BytesMessage contents must be unwrapped... - bytesMessage.readBytes(null); - mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER); - mockBytesMessage.setReturnValue(TEXT.getBytes().length); - mockBytesMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT.getBytes()); - mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); + } + }); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); adapter.onMessage(bytesMessage); - mockDelegate.verify(); - mockBytesMessage.verify(); + verify(delegate).handleMessage(TEXT.getBytes()); } @Test public void testWithMessageDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + TextMessage textMessage = mock(TextMessage.class); + MessageDelegate delegate = mock(MessageDelegate.class); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test @@ -104,69 +101,38 @@ public final class MessageListenerAdapter102Tests { @Test public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); + TextMessage textMessage = mock(TextMessage.class); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setReturnValue(TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(textMessage)).willReturn(TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForQueue() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); + Queue destination = mock(Queue.class); - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); // we want to fall back to the default... - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createSender(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -177,58 +143,30 @@ public final class MessageListenerAdapter102Tests { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSuppliedForTopic() throws Exception { - MockControl mockDestination = MockControl.createControl(Topic.class); - Topic destination = (Topic) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Topic destination = mock(Topic.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); // we want to fall back to the default... - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default... - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); + TopicPublisher topicPublisher = mock(TopicPublisher.class); + TopicSession session = mock(TopicSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createPublisher(destination)).willReturn(topicPublisher); - MockControl mockTopicPublisher = MockControl.createControl(TopicPublisher.class); - TopicPublisher topicPublisher = (TopicPublisher) mockTopicPublisher.getMock(); - topicPublisher.publish(responseTextMessage); - mockTopicPublisher.setVoidCallable(); - topicPublisher.close(); - mockTopicPublisher.setVoidCallable(); - mockTopicPublisher.replay(); - - MockControl mockSession = MockControl.createControl(TopicSession.class); - TopicSession session = (TopicSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createPublisher(destination); - mockSession.setReturnValue(topicPublisher); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -239,58 +177,30 @@ public final class MessageListenerAdapter102Tests { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockTopicPublisher.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(topicPublisher).publish(responseTextMessage); + verify(topicPublisher).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createSender(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -300,44 +210,29 @@ public final class MessageListenerAdapter102Tests { }; adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - mockSession.replay(); + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -350,57 +245,31 @@ public final class MessageListenerAdapter102Tests { fail("expected InvalidDestinationException"); } catch (InvalidDestinationException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); - - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setThrowable(new JMSException("Dow!")); + TextMessage responseTextMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); + willThrow(new JMSException("Doe!")).given(queueSender).send(responseTextMessage); // ensure that regardless of a JMSException the producer is closed... - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createSender(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createSender(destination)).willReturn(queueSender); - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -413,30 +282,20 @@ public final class MessageListenerAdapter102Tests { fail("expected JMSException"); } catch (JMSException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); - mockSentTextMessage.replay(); + final TextMessage sentTextMessage = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setThrowable(new IllegalArgumentException("Dow!")); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(sentTextMessage); final MessageListenerAdapter102 adapter = new MessageListenerAdapter102(delegate) { @Override @@ -448,10 +307,6 @@ public final class MessageListenerAdapter102Tests { adapter.onMessage(sentTextMessage, session); fail("expected ListenerExecutionFailedException"); } catch (ListenerExecutionFailedException ex) { /* expected */ } - - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java index 8fdf939108..c673f51a44 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,19 @@ package org.springframework.jms.listener.adapter; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.willThrow; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import java.io.ByteArrayInputStream; import java.io.Serializable; import javax.jms.BytesMessage; @@ -33,9 +44,9 @@ import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.MockControl; import org.junit.Test; - +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; @@ -59,161 +70,110 @@ public class MessageListenerAdapterTests { @Test public void testWithMessageContentsDelegateForTextMessage() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(TEXT); } @Test public void testWithMessageContentsDelegateForBytesMessage() throws Exception { - MockControl mockBytesMessage = MockControl.createControl(BytesMessage.class); - BytesMessage bytesMessage = (BytesMessage) mockBytesMessage.getMock(); + BytesMessage bytesMessage = mock(BytesMessage.class); // BytesMessage contents must be unwrapped... - bytesMessage.getBodyLength(); - mockBytesMessage.setReturnValue(TEXT.getBytes().length); - bytesMessage.readBytes(null); - mockBytesMessage.setMatcher(MockControl.ALWAYS_MATCHER); - mockBytesMessage.setReturnValue(TEXT.getBytes().length); - mockBytesMessage.replay(); + given(bytesMessage.getBodyLength()).willReturn(new Long(TEXT.getBytes().length)); + given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + byte[] bytes = (byte[]) invocation.getArguments()[0]; + ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes()); + return inputStream.read(bytes); + } + }); - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(TEXT.getBytes()); - mockDelegate.setMatcher(MockControl.ALWAYS_MATCHER); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(bytesMessage); - mockDelegate.verify(); - mockBytesMessage.verify(); + verify(delegate).handleMessage(TEXT.getBytes()); } @Test public void testWithMessageContentsDelegateForObjectMessage() throws Exception { - MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class); - ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock(); - objectMessage.getObject(); - mockObjectMessage.setReturnValue(NUMBER); - mockObjectMessage.replay(); + ObjectMessage objectMessage = mock(ObjectMessage.class); + given(objectMessage.getObject()).willReturn(NUMBER); - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(NUMBER); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(objectMessage); - mockDelegate.verify(); - mockObjectMessage.verify(); + verify(delegate).handleMessage(NUMBER); } @Test public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception { - MockControl mockObjectMessage = MockControl.createControl(ObjectMessage.class); - ObjectMessage objectMessage = (ObjectMessage) mockObjectMessage.getMock(); - objectMessage.getObject(); - mockObjectMessage.setReturnValue(OBJECT); - mockObjectMessage.replay(); + ObjectMessage objectMessage = mock(ObjectMessage.class); + given(objectMessage.getObject()).willReturn(OBJECT); - MockControl mockDelegate = MockControl.createControl(MessageContentsDelegate.class); - MessageContentsDelegate delegate = (MessageContentsDelegate) mockDelegate.getMock(); - delegate.handleMessage(OBJECT); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageContentsDelegate delegate = mock(MessageContentsDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); adapter.onMessage(objectMessage); - mockDelegate.verify(); - mockObjectMessage.verify(); + verify(delegate).handleMessage(OBJECT); } @Test public void testWithMessageDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); + TextMessage textMessage = mock(TextMessage.class); - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setVoidCallable(); - mockDelegate.replay(); + MessageDelegate delegate = mock(MessageDelegate.class); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - mockDelegate.verify(); - mockTextMessage.verify(); + verify(delegate).handleMessage(textMessage); } @Test public void testWhenTheAdapterItselfIsTheDelegate() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.onMessage(textMessage); assertTrue(adapter.wasCalled()); - - mockTextMessage.verify(); } @Test public void testRainyDayWithNoApplicableHandlingMethods() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); + TextMessage textMessage = mock(TextMessage.class); // TextMessage contents must be unwrapped... - textMessage.getText(); - mockTextMessage.setReturnValue(TEXT); - mockTextMessage.replay(); + given(textMessage.getText()).willReturn(TEXT); StubMessageListenerAdapter adapter = new StubMessageListenerAdapter(); adapter.setDefaultListenerMethod("walnutsRock"); adapter.onMessage(textMessage); assertFalse(adapter.wasCalled()); - - mockTextMessage.verify(); } @Test public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception { final IllegalArgumentException exception = new IllegalArgumentException(); - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(MessageDelegate.class); - MessageDelegate delegate = (MessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setThrowable(exception); - mockDelegate.replay(); + TextMessage textMessage = mock(TextMessage.class); + MessageDelegate delegate = mock(MessageDelegate.class); + willThrow(exception).given(delegate).handleMessage(textMessage); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -230,9 +190,6 @@ public class MessageListenerAdapterTests { // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - - mockDelegate.verify(); - mockTextMessage.verify(); } @Test @@ -257,68 +214,35 @@ public class MessageListenerAdapterTests { @Test public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception { - MockControl mockTextMessage = MockControl.createControl(TextMessage.class); - TextMessage textMessage = (TextMessage) mockTextMessage.getMock(); - mockTextMessage.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(textMessage); - mockDelegate.setReturnValue(TEXT); - mockDelegate.replay(); + TextMessage textMessage = mock(TextMessage.class); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(textMessage)).willReturn(TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate); // we DON'T want the default SimpleMessageConversion happening... adapter.setMessageConverter(null); adapter.onMessage(textMessage); - - mockDelegate.verify(); - mockTextMessage.verify(); } @Test public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn( + CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); // we want to fall back to the default... - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default... - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseTextMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); + QueueSender queueSender = mock(QueueSender.class); + Session session = mock(Session.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(queueSender); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createProducer(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -329,59 +253,30 @@ public class MessageListenerAdapterTests { adapter.setDefaultResponseDestination(destination); adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockQueueSender.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseTextMessage); + verify(queueSender).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(null); - sentTextMessage.getJMSMessageID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(null); + given(sentTextMessage.getJMSMessageID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); + MessageProducer messageProducer = mock(MessageProducer.class); + Session session = mock(Session.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(messageProducer); - MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class); - MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock(); - messageProducer.send(responseTextMessage); - mockMessageProducer.setVoidCallable(); - messageProducer.close(); - mockMessageProducer.setVoidCallable(); - mockMessageProducer.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createProducer(destination); - mockSession.setReturnValue(messageProducer); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -391,43 +286,26 @@ public class MessageListenerAdapterTests { }; adapter.onMessage(sentTextMessage, session); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockMessageProducer.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(messageProducer).send(responseTextMessage); + verify(messageProducer).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(null); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(null); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -440,56 +318,30 @@ public class MessageListenerAdapterTests { fail("expected InvalidDestinationException"); } catch(InvalidDestinationException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); + Queue destination = mock(Queue.class); - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); - MockControl mockResponseTextMessage = MockControl.createControl(TextMessage.class); - TextMessage responseTextMessage = (TextMessage) mockResponseTextMessage.getMock(); - responseTextMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseTextMessage.setVoidCallable(); - mockResponseTextMessage.replay(); + TextMessage responseTextMessage = mock(TextMessage.class); + MessageProducer messageProducer = mock(MessageProducer.class); + willThrow(new JMSException("Doe!")).given(messageProducer).send(responseTextMessage); - MockControl mockMessageProducer = MockControl.createControl(MessageProducer.class); - MessageProducer messageProducer = (MessageProducer) mockMessageProducer.getMock(); - messageProducer.send(responseTextMessage); - mockMessageProducer.setThrowable(new JMSException("Dow!")); - // ensure that regardless of a JMSException the producer is closed... - messageProducer.close(); - mockMessageProducer.setVoidCallable(); - mockMessageProducer.replay(); + final QueueSession session = mock(QueueSession.class); + given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage); + given(session.createProducer(destination)).willReturn(messageProducer); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - session.createTextMessage(RESPONSE_TEXT); - mockSession.setReturnValue(responseTextMessage); - session.createProducer(destination); - mockSession.setReturnValue(messageProducer); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -502,29 +354,18 @@ public class MessageListenerAdapterTests { fail("expected JMSException"); } catch(JMSException ex) { /* expected */ } - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockResponseTextMessage.verify(); - mockSession.verify(); - mockDestination.verify(); - mockMessageProducer.verify(); + verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID); + verify(messageProducer).close(); + verify(delegate).handleMessage(sentTextMessage); } @Test public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception { - MockControl mockMessage = MockControl.createControl(TextMessage.class); - final TextMessage message = (TextMessage) mockMessage.getMock(); - mockMessage.replay(); + final TextMessage message = mock(TextMessage.class); + final QueueSession session = mock(QueueSession.class); - MockControl mockSession = MockControl.createControl(QueueSession.class); - final QueueSession session = (QueueSession) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(message); - mockDelegate.setThrowable(new IllegalArgumentException("Dow!")); - mockDelegate.replay(); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(message); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -536,20 +377,12 @@ public class MessageListenerAdapterTests { adapter.onMessage(message, session); fail("expected ListenerExecutionFailedException"); } catch(ListenerExecutionFailedException ex) { /* expected */ } - - mockDelegate.verify(); - mockMessage.verify(); - mockSession.verify(); } @Test public void testFailsIfNoDefaultListenerMethodNameIsSupplied() throws Exception { - MockControl mockMessage = MockControl.createControl(TextMessage.class); - final TextMessage message = (TextMessage) mockMessage.getMock(); - message.getText(); - mockMessage.setReturnValue(TEXT); - - mockMessage.replay(); + final TextMessage message = mock(TextMessage.class); + given(message.getText()).willReturn(TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter() { @Override @@ -559,18 +392,12 @@ public class MessageListenerAdapterTests { }; adapter.setDefaultListenerMethod(null); adapter.onMessage(message); - - mockMessage.verify(); } @Test public void testFailsWhenOverriddenGetListenerMethodNameReturnsNull() throws Exception { - MockControl mockMessage = MockControl.createControl(TextMessage.class); - final TextMessage message = (TextMessage) mockMessage.getMock(); - message.getText(); - mockMessage.setReturnValue(TEXT); - - mockMessage.replay(); + final TextMessage message = mock(TextMessage.class); + given(message.getText()).willReturn(TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter() { @Override @@ -584,25 +411,14 @@ public class MessageListenerAdapterTests { }; adapter.setDefaultListenerMethod(null); adapter.onMessage(message); - - mockMessage.verify(); } @Test public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); - mockSentTextMessage.replay(); - - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveMessageDelegate.class); - ResponsiveMessageDelegate delegate = (ResponsiveMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(RESPONSE_TEXT); - mockDelegate.replay(); + final TextMessage sentTextMessage = mock(TextMessage.class); + final Session session = mock(Session.class); + ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -615,53 +431,25 @@ public class MessageListenerAdapterTests { adapter.onMessage(sentTextMessage, session); fail("expected MessageConversionException"); } catch(MessageConversionException ex) { /* expected */ } - - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); } @Test public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception { - MockControl mockDestination = MockControl.createControl(Queue.class); - Queue destination = (Queue) mockDestination.getMock(); - mockDestination.replay(); - - MockControl mockSentTextMessage = MockControl.createControl(TextMessage.class); - final TextMessage sentTextMessage = (TextMessage) mockSentTextMessage.getMock(); + Queue destination = mock(Queue.class); + final TextMessage sentTextMessage = mock(TextMessage.class); // correlation ID is queried when response is being created... - sentTextMessage.getJMSCorrelationID(); - mockSentTextMessage.setReturnValue(CORRELATION_ID); + given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID); // Reply-To is queried when response is being created... - sentTextMessage.getJMSReplyTo(); - mockSentTextMessage.setReturnValue(destination); - mockSentTextMessage.replay(); + given(sentTextMessage.getJMSReplyTo()).willReturn(destination); - MockControl mockResponseMessage = MockControl.createControl(TextMessage.class); - TextMessage responseMessage = (TextMessage) mockResponseMessage.getMock(); - responseMessage.setJMSCorrelationID(CORRELATION_ID); - mockResponseMessage.setVoidCallable(); - mockResponseMessage.replay(); + TextMessage responseMessage = mock(TextMessage.class); + QueueSender queueSender = mock(QueueSender.class); - MockControl mockQueueSender = MockControl.createControl(QueueSender.class); - QueueSender queueSender = (QueueSender) mockQueueSender.getMock(); - queueSender.send(responseMessage); - mockQueueSender.setVoidCallable(); - queueSender.close(); - mockQueueSender.setVoidCallable(); - mockQueueSender.replay(); + Session session = mock(Session.class); + given(session.createProducer(destination)).willReturn(queueSender); - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createProducer(destination); - mockSession.setReturnValue(queueSender); - mockSession.replay(); - - MockControl mockDelegate = MockControl.createControl(ResponsiveJmsTextMessageReturningMessageDelegate.class); - ResponsiveJmsTextMessageReturningMessageDelegate delegate = (ResponsiveJmsTextMessageReturningMessageDelegate) mockDelegate.getMock(); - delegate.handleMessage(sentTextMessage); - mockDelegate.setReturnValue(responseMessage); - mockDelegate.replay(); + ResponsiveJmsTextMessageReturningMessageDelegate delegate = mock(ResponsiveJmsTextMessageReturningMessageDelegate.class); + given(delegate.handleMessage(sentTextMessage)).willReturn(responseMessage); final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) { @Override @@ -672,12 +460,9 @@ public class MessageListenerAdapterTests { adapter.setMessageConverter(null); adapter.onMessage(sentTextMessage, session); - mockDestination.verify(); - mockDelegate.verify(); - mockSentTextMessage.verify(); - mockSession.verify(); - mockQueueSender.verify(); - mockResponseMessage.verify(); + verify(responseMessage).setJMSCorrelationID(CORRELATION_ID); + verify(queueSender).send(responseMessage); + verify(queueSender).close(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java index f91da0b40c..ea98f90206 100644 --- a/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java @@ -16,12 +16,14 @@ package org.springframework.jms.listener.endpoint; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.jms.Destination; import javax.jms.Session; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.jca.StubResourceAdapter; import org.springframework.jms.StubQueue; import org.springframework.jms.support.destination.DestinationResolver; @@ -60,12 +62,10 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { public void testWebSphereResourceAdapterSetup() throws Exception { Destination destination = new StubQueue(); - MockControl control = MockControl.createControl(DestinationResolver.class); - DestinationResolver destinationResolver = (DestinationResolver) control.getMock(); + DestinationResolver destinationResolver = mock(DestinationResolver.class); - destinationResolver.resolveDestinationName(null, "destinationname", false); - control.setReturnValue(destination); - control.replay(); + given(destinationResolver.resolveDestinationName(null, "destinationname", + false)).willReturn(destination); DefaultJmsActivationSpecFactory activationSpecFactory = new DefaultJmsActivationSpecFactory(); activationSpecFactory.setDestinationResolver(destinationResolver); @@ -73,8 +73,6 @@ public class DefaultJmsActivationSpecFactoryTests extends TestCase { StubWebSphereActivationSpecImpl spec = (StubWebSphereActivationSpecImpl) activationSpecFactory .createActivationSpec(new StubWebSphereResourceAdapterImpl(), activationSpecConfig); - control.verify(); - assertEquals(destination, spec.getDestination()); assertEquals(5, spec.getMaxConcurrency()); assertEquals(3, spec.getMaxBatchSize()); diff --git a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java index 55736c4d2a..9cdbf34136 100644 --- a/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/remoting/JmsInvokerTests.java @@ -16,9 +16,16 @@ package org.springframework.jms.remoting; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import java.io.Serializable; import java.util.Arrays; import java.util.Enumeration; + import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; @@ -30,71 +37,47 @@ import javax.jms.QueueConnectionFactory; import javax.jms.QueueSession; import javax.jms.Session; -import junit.framework.TestCase; -import org.easymock.MockControl; - -import org.springframework.tests.sample.beans.ITestBean; -import org.springframework.tests.sample.beans.TestBean; +import org.junit.Before; +import org.junit.Test; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; +import org.springframework.tests.sample.beans.ITestBean; +import org.springframework.tests.sample.beans.TestBean; /** * @author Juergen Hoeller */ -public class JmsInvokerTests extends TestCase { +public class JmsInvokerTests { - private MockControl connectionFactoryControl; private QueueConnectionFactory mockConnectionFactory; - private MockControl connectionControl; private QueueConnection mockConnection; - private MockControl sessionControl; private QueueSession mockSession; - private MockControl queueControl; private Queue mockQueue; - @Override - protected void setUp() throws Exception { - connectionFactoryControl = MockControl.createControl(QueueConnectionFactory.class); - mockConnectionFactory = (QueueConnectionFactory) connectionFactoryControl.getMock(); + @Before + public void setUpMocks() throws Exception { + mockConnectionFactory = mock(QueueConnectionFactory.class); + mockConnection = mock(QueueConnection.class); + mockSession = mock(QueueSession.class); + mockQueue = mock(Queue.class); - connectionControl = MockControl.createControl(QueueConnection.class); - mockConnection = (QueueConnection) connectionControl.getMock(); - - sessionControl = MockControl.createControl(QueueSession.class); - mockSession = (QueueSession) sessionControl.getMock(); - - queueControl = MockControl.createControl(Queue.class); - mockQueue = (Queue) queueControl.getMock(); - - mockConnectionFactory.createConnection(); - connectionFactoryControl.setReturnValue(mockConnection, 8); - - mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); - connectionControl.setReturnValue(mockSession, 8); - - mockConnection.start(); - connectionControl.setVoidCallable(8); - - connectionFactoryControl.replay(); - connectionControl.replay(); + given(mockConnectionFactory.createConnection()).willReturn(mockConnection); + given(mockConnection.createSession(false, Session.AUTO_ACKNOWLEDGE)).willReturn(mockSession); } + @Test public void testJmsInvokerProxyFactoryBeanAndServiceExporter() throws Throwable { - sessionControl.replay(); - doTestJmsInvokerProxyFactoryBeanAndServiceExporter(false); } + @Test public void testJmsInvokerProxyFactoryBeanAndServiceExporterWithDynamicQueue() throws Throwable { - mockSession.createQueue("myQueue"); - sessionControl.setReturnValue(mockQueue, 8); - sessionControl.replay(); - + given(mockSession.createQueue("myQueue")).willReturn(mockQueue); doTestJmsInvokerProxyFactoryBeanAndServiceExporter(true); } @@ -110,14 +93,10 @@ public class JmsInvokerTests extends TestCase { JmsInvokerProxyFactoryBean pfb = new JmsInvokerProxyFactoryBean() { @Override protected Message doExecuteRequest(Session session, Queue queue, Message requestMessage) throws JMSException { - MockControl exporterSessionControl = MockControl.createControl(Session.class); - Session mockExporterSession = (Session) exporterSessionControl.getMock(); + Session mockExporterSession = mock(Session.class); ResponseStoringProducer mockProducer = new ResponseStoringProducer(); - mockExporterSession.createProducer(requestMessage.getJMSReplyTo()); - exporterSessionControl.setReturnValue(mockProducer); - exporterSessionControl.replay(); + given(mockExporterSession.createProducer(requestMessage.getJMSReplyTo())).willReturn(mockProducer); exporter.onMessage(requestMessage, mockExporterSession); - exporterSessionControl.verify(); assertTrue(mockProducer.closed); return mockProducer.response; } @@ -156,10 +135,6 @@ public class JmsInvokerTests extends TestCase { catch (IllegalAccessException ex) { // expected } - - connectionFactoryControl.verify(); - connectionControl.verify(); - sessionControl.verify(); } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java index 7d4663a285..8ca5ad2e1f 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverter102Tests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,16 +16,24 @@ package org.springframework.jms.support; -import junit.framework.TestCase; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; -import org.springframework.jms.support.converter.SimpleMessageConverter102; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; + +import java.io.ByteArrayInputStream; +import java.util.Random; import javax.jms.BytesMessage; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; -import java.util.Arrays; + +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.springframework.jms.support.converter.SimpleMessageConverter102; /** * Unit tests for the {@link SimpleMessageConverter102} class. @@ -33,46 +41,28 @@ import java.util.Arrays; * @author Juergen Hoeller * @author Rick Evans */ -public final class SimpleMessageConverter102Tests extends TestCase { +public final class SimpleMessageConverter102Tests { + @Test public void testByteArrayConversion102() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(BytesMessage.class); - BytesMessage message = (BytesMessage) messageControl.getMock(); + Session session = mock(Session.class); + BytesMessage message = mock(BytesMessage.class); byte[] content = new byte[5000]; + new Random().nextBytes(content); - session.createBytesMessage(); - sessionControl.setReturnValue(message, 1); - message.writeBytes(content); - messageControl.setVoidCallable(1); - message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]); - messageControl.setMatcher(new ArgumentsMatcher() { + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); + given(session.createBytesMessage()).willReturn(message); + given(message.readBytes(any(byte[].class))).willAnswer(new Answer() { @Override - public boolean matches(Object[] arg0, Object[] arg1) { - byte[] one = (byte[]) arg0[0]; - byte[] two = (byte[]) arg1[0]; - return Arrays.equals(one, two); - } - - @Override - public String toString(Object[] arg0) { - return "bla"; + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteArrayInputStream.read((byte[])invocation.getArguments()[0]); } }); - messageControl.setReturnValue(SimpleMessageConverter102.BUFFER_SIZE, 1); - message.readBytes(new byte[SimpleMessageConverter102.BUFFER_SIZE]); - messageControl.setReturnValue(5000 - SimpleMessageConverter102.BUFFER_SIZE, 1); - sessionControl.replay(); - messageControl.replay(); SimpleMessageConverter102 converter = new SimpleMessageConverter102(); Message msg = converter.toMessage(content, session); - assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length); - - sessionControl.verify(); - messageControl.verify(); + assertThat((byte[])converter.fromMessage(msg), equalTo(content)); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java index 147987430b..b903ff3686 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/SimpleMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,9 +16,15 @@ package org.springframework.jms.support; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; -import java.util.Arrays; +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -31,9 +37,9 @@ import javax.jms.ObjectMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.ArgumentsMatcher; -import org.easymock.MockControl; import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; import org.springframework.jms.support.converter.MessageConversionException; import org.springframework.jms.support.converter.SimpleMessageConverter; @@ -48,127 +54,79 @@ public final class SimpleMessageConverterTests { @Test public void testStringConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(TextMessage.class); - TextMessage message = (TextMessage) messageControl.getMock(); + Session session = mock(Session.class); + TextMessage message = mock(TextMessage.class); String content = "test"; - session.createTextMessage(content); - sessionControl.setReturnValue(message, 1); - message.getText(); - messageControl.setReturnValue(content, 1); - sessionControl.replay(); - messageControl.replay(); + given(session.createTextMessage(content)).willReturn(message); + given(message.getText()).willReturn(content); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - - sessionControl.verify(); - messageControl.verify(); } @Test public void testByteArrayConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(BytesMessage.class); - BytesMessage message = (BytesMessage) messageControl.getMock(); + Session session = mock(Session.class); + BytesMessage message = mock(BytesMessage.class); byte[] content = "test".getBytes(); + final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content); - session.createBytesMessage(); - sessionControl.setReturnValue(message, 1); - message.writeBytes(content); - messageControl.setVoidCallable(1); - message.getBodyLength(); - messageControl.setReturnValue(content.length, 1); - message.readBytes(new byte[content.length]); - messageControl.setMatcher(new ArgumentsMatcher() { + given(session.createBytesMessage()).willReturn(message); + given(message.getBodyLength()).willReturn((long) content.length); + given(message.readBytes(any(byte[].class))).willAnswer(new Answer() { @Override - public boolean matches(Object[] arg0, Object[] arg1) { - byte[] one = (byte[]) arg0[0]; - byte[] two = (byte[]) arg1[0]; - return Arrays.equals(one, two); - } - - @Override - public String toString(Object[] arg0) { - return "bla"; + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteArrayInputStream.read((byte[]) invocation.getArguments()[0]); } }); - messageControl.setReturnValue(content.length, 1); - sessionControl.replay(); - messageControl.replay(); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content.length, ((byte[]) converter.fromMessage(msg)).length); - sessionControl.verify(); - messageControl.verify(); + verify(message).writeBytes(content); } @Test public void testMapConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(MapMessage.class); - MapMessage message = (MapMessage) messageControl.getMock(); + Session session = mock(Session.class); + MapMessage message = mock(MapMessage.class); Map content = new HashMap(); content.put("key1", "value1"); content.put("key2", "value2"); - session.createMapMessage(); - sessionControl.setReturnValue(message, 1); - message.setObject("key1", "value1"); - messageControl.setVoidCallable(1); - message.setObject("key2", "value2"); - messageControl.setVoidCallable(1); - message.getMapNames(); - messageControl.setReturnValue(Collections.enumeration(content.keySet())); - message.getObject("key1"); - messageControl.setReturnValue("value1", 1); - message.getObject("key2"); - messageControl.setReturnValue("value2", 1); - - sessionControl.replay(); - messageControl.replay(); + given(session.createMapMessage()).willReturn(message); + given(message.getMapNames()).willReturn(Collections.enumeration(content.keySet())); + given(message.getObject("key1")).willReturn("value1"); + given(message.getObject("key2")).willReturn("value2"); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - sessionControl.verify(); - messageControl.verify(); + verify(message).setObject("key1", "value1"); + verify(message).setObject("key2", "value2"); } @Test public void testSerializableConversion() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - MockControl messageControl = MockControl.createControl(ObjectMessage.class); - ObjectMessage message = (ObjectMessage) messageControl.getMock(); + Session session = mock(Session.class); + ObjectMessage message = mock(ObjectMessage.class); Integer content = new Integer(5); - session.createObjectMessage(content); - sessionControl.setReturnValue(message, 1); - message.getObject(); - messageControl.setReturnValue(content, 1); - sessionControl.replay(); - messageControl.replay(); + given(session.createObjectMessage(content)).willReturn(message); + given(message.getObject()).willReturn(content); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(content, session); assertEquals(content, converter.fromMessage(msg)); - - sessionControl.verify(); - messageControl.verify(); } @Test(expected=MessageConversionException.class) @@ -184,50 +142,30 @@ public final class SimpleMessageConverterTests { @Test public void testToMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { - MockControl sessionControl = MockControl.createControl(Session.class); - Session session = (Session) sessionControl.getMock(); - - MockControl messageControl = MockControl.createControl(ObjectMessage.class); - ObjectMessage message = (ObjectMessage) messageControl.getMock(); - - sessionControl.replay(); - messageControl.replay(); + Session session = mock(Session.class); + ObjectMessage message = mock(ObjectMessage.class); SimpleMessageConverter converter = new SimpleMessageConverter(); Message msg = converter.toMessage(message, session); assertSame(message, msg); - - sessionControl.verify(); - messageControl.verify(); } @Test public void testFromMessageSimplyReturnsMessageAsIsIfSuppliedWithMessage() throws JMSException { - MockControl messageControl = MockControl.createControl(Message.class); - Message message = (Message) messageControl.getMock(); - - messageControl.replay(); + Message message = mock(Message.class); SimpleMessageConverter converter = new SimpleMessageConverter(); Object msg = converter.fromMessage(message); assertSame(message, msg); - - messageControl.verify(); } @Test public void testMapConversionWhereMapHasNonStringTypesForKeys() throws JMSException { - MockControl messageControl = MockControl.createControl(MapMessage.class); - MapMessage message = (MapMessage) messageControl.getMock(); - messageControl.replay(); - - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - session.createMapMessage(); - sessionControl.setReturnValue(message); - sessionControl.replay(); + MapMessage message = mock(MapMessage.class); + final Session session = mock(Session.class); + given(session.createMapMessage()).willReturn(message); final Map content = new HashMap(); content.put(new Integer(1), "value1"); @@ -237,22 +175,14 @@ public final class SimpleMessageConverterTests { converter.toMessage(content, session); fail("expected MessageConversionException"); } catch (MessageConversionException ex) { /* expected */ } - - sessionControl.verify(); } @Test public void testMapConversionWhereMapHasNNullForKey() throws JMSException { - MockControl messageControl = MockControl.createControl(MapMessage.class); - MapMessage message = (MapMessage) messageControl.getMock(); - messageControl.replay(); - - MockControl sessionControl = MockControl.createControl(Session.class); - final Session session = (Session) sessionControl.getMock(); - session.createMapMessage(); - sessionControl.setReturnValue(message); - sessionControl.replay(); + MapMessage message = mock(MapMessage.class); + final Session session = mock(Session.class); + given(session.createMapMessage()).willReturn(message); final Map content = new HashMap(); content.put(null, "value1"); @@ -262,8 +192,6 @@ public final class SimpleMessageConverterTests { converter.toMessage(content, session); fail("expected MessageConversionException"); } catch (MessageConversionException ex) { /* expected */ } - - sessionControl.verify(); } } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java index 025ba22fc7..d2054d5bf2 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJackson2MessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,21 +16,27 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; /** * @author Arjen Poutsma @@ -44,7 +50,7 @@ public class MappingJackson2MessageConverterTests { @Before public void setUp() throws Exception { - sessionMock = createMock(Session.class); + sessionMock = mock(Session.class); converter = new MappingJackson2MessageConverter(); converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); @@ -52,128 +58,94 @@ public class MappingJackson2MessageConverterTests { @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Date toBeMarshalled = new Date(); - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - bytesMessageMock.setStringProperty("__encoding__", "UTF-8"); - bytesMessageMock.setStringProperty("__typeid__", Date.class.getName()); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, bytesMessageMock); + verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); + verify(bytesMessageMock).setStringProperty("__typeid__", Date.class.getName()); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + BytesMessage bytesMessageMock = mock(BytesMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); - final byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); - @SuppressWarnings("serial") - Capture captured = new Capture() { - @Override - public void setValue(byte[] value) { - super.setValue(value); - System.arraycopy(bytes, 0, value, 0, bytes.length); - } - }; + byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); + final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); - expect( - bytesMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect( - bytesMessageMock.propertyExists("__encoding__")) - .andReturn(false); - expect(bytesMessageMock.getBodyLength()).andReturn( - new Long(bytes.length)); - expect(bytesMessageMock.readBytes(EasyMock.capture(captured))) - .andReturn(bytes.length); - - replay(sessionMock, bytesMessageMock); + given(bytesMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); + given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( + new Answer() { + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteStream.read((byte[]) invocation.getArguments()[0]); + } + }); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, bytesMessageMock); } @Test public void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Date toBeMarshalled = new Date(); - textMessageMock.setStringProperty("__typeid__", Date.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock); - - replay(sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn( + textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", Date.class.getName()); } @Test public void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Map toBeMarshalled = new HashMap(); toBeMarshalled.put("foo", "bar"); - textMessageMock.setStringProperty("__typeid__", HashMap.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( + given(sessionMock.createTextMessage(isA(String.class))).willReturn( textMessageMock); - replay(sessionMock, textMessageMock); - converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test public void fromTextMessageAsObject() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } @Test public void fromTextMessageAsMap() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(HashMap.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + HashMap.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java index 54ca352ea0..0bce702aaa 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MappingJacksonMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,20 +16,26 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; import java.util.Collections; import java.util.HashMap; import java.util.Map; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; -import org.easymock.Capture; -import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; - -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; /** * @author Arjen Poutsma @@ -43,7 +49,7 @@ public class MappingJacksonMessageConverterTests { @Before public void setUp() throws Exception { - sessionMock = createMock(Session.class); + sessionMock = mock(Session.class); converter = new MappingJacksonMessageConverter(); converter.setEncodingPropertyName("__encoding__"); converter.setTypeIdPropertyName("__typeid__"); @@ -51,128 +57,96 @@ public class MappingJacksonMessageConverterTests { @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - bytesMessageMock.setStringProperty("__encoding__", "UTF-8"); - bytesMessageMock.setStringProperty("__typeid__", Object.class.getName()); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, bytesMessageMock); + verify(bytesMessageMock).setStringProperty("__encoding__", "UTF-8"); + verify(bytesMessageMock).setStringProperty("__typeid__", Object.class.getName()); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test @SuppressWarnings("serial") public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + BytesMessage bytesMessageMock = mock(BytesMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); - final byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); - Capture captured = new Capture() { - @Override - public void setValue(byte[] value) { - super.setValue(value); - System.arraycopy(bytes, 0, value, 0, bytes.length); - } - }; + byte[] bytes = "{\"foo\":\"bar\"}".getBytes(); + final ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); - expect( - bytesMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect( - bytesMessageMock.propertyExists("__encoding__")) - .andReturn(false); - expect(bytesMessageMock.getBodyLength()).andReturn( - new Long(bytes.length)); - expect(bytesMessageMock.readBytes(EasyMock.capture(captured))) - .andReturn(bytes.length); + given(bytesMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(bytesMessageMock.propertyExists("__encoding__")).willReturn(false); + given(bytesMessageMock.getBodyLength()).willReturn(new Long(bytes.length)); + given(bytesMessageMock.readBytes(any(byte[].class))).willAnswer( + new Answer() { - replay(sessionMock, bytesMessageMock); + @Override + public Integer answer(InvocationOnMock invocation) throws Throwable { + return byteStream.read((byte[]) invocation.getArguments()[0]); + } + }); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, bytesMessageMock); } @Test public void toTextMessageWithObject() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); - textMessageMock.setStringProperty("__typeid__", Object.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( textMessageMock); - - replay(sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn( + textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", Object.class.getName()); } @Test public void toTextMessageWithMap() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Map toBeMarshalled = new HashMap(); toBeMarshalled.put("foo", "bar"); - - textMessageMock.setStringProperty("__typeid__", HashMap.class.getName()); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn( + given(sessionMock.createTextMessage(isA(String.class))).willReturn( textMessageMock); - replay(sessionMock, textMessageMock); - converter.toMessage(toBeMarshalled, sessionMock); - verify(sessionMock, textMessageMock); + verify(textMessageMock).setStringProperty("__typeid__", HashMap.class.getName()); } @Test public void fromTextMessageAsObject() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(Object.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + Object.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } @Test public void fromTextMessageAsMap() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); - Map unmarshalled = Collections.singletonMap("foo", - "bar"); + TextMessage textMessageMock = mock(TextMessage.class); + Map unmarshalled = Collections.singletonMap("foo", "bar"); String text = "{\"foo\":\"bar\"}"; - expect( - textMessageMock.getStringProperty("__typeid__")) - .andReturn(HashMap.class.getName()); - expect(textMessageMock.getText()).andReturn(text); - - replay(sessionMock, textMessageMock); + given(textMessageMock.getStringProperty("__typeid__")).willReturn( + HashMap.class.getName()); + given(textMessageMock.getText()).willReturn(text); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(sessionMock, textMessageMock); } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java index 861179583d..2f6a06199d 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/converter/MarshallingMessageConverterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,17 +16,21 @@ package org.springframework.jms.support.converter; +import static org.junit.Assert.assertEquals; +import static org.mockito.BDDMockito.given; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + import javax.jms.BytesMessage; import javax.jms.Session; import javax.jms.TextMessage; import javax.xml.transform.Result; import javax.xml.transform.Source; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; - import org.springframework.oxm.Marshaller; import org.springframework.oxm.Unmarshaller; @@ -45,76 +49,60 @@ public class MarshallingMessageConverterTests { @Before public void setUp() throws Exception { - marshallerMock = createMock(Marshaller.class); - unmarshallerMock = createMock(Unmarshaller.class); - sessionMock = createMock(Session.class); + marshallerMock = mock(Marshaller.class); + unmarshallerMock = mock(Unmarshaller.class); + sessionMock = mock(Session.class); converter = new MarshallingMessageConverter(marshallerMock, unmarshallerMock); } @Test public void toBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object toBeMarshalled = new Object(); - - expect(sessionMock.createBytesMessage()).andReturn(bytesMessageMock); - marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class)); - bytesMessageMock.writeBytes(isA(byte[].class)); - - replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + given(sessionMock.createBytesMessage()).willReturn(bytesMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); + verify(bytesMessageMock).writeBytes(isA(byte[].class)); } @Test public void fromBytesMessage() throws Exception { - BytesMessage bytesMessageMock = createMock(BytesMessage.class); + BytesMessage bytesMessageMock = mock(BytesMessage.class); Object unmarshalled = new Object(); - expect(bytesMessageMock.getBodyLength()).andReturn(10L); - expect(bytesMessageMock.readBytes(isA(byte[].class))).andReturn(0); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - replay(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); + given(bytesMessageMock.getBodyLength()).willReturn(10L); + given(bytesMessageMock.readBytes(isA(byte[].class))).willReturn(0); + given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(bytesMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(marshallerMock, unmarshallerMock, sessionMock, bytesMessageMock); } @Test public void toTextMessage() throws Exception { converter.setTargetType(MessageType.TEXT); - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object toBeMarshalled = new Object(); - expect(sessionMock.createTextMessage(isA(String.class))).andReturn(textMessageMock); - marshallerMock.marshal(eq(toBeMarshalled), isA(Result.class)); - - replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + given(sessionMock.createTextMessage(isA(String.class))).willReturn(textMessageMock); converter.toMessage(toBeMarshalled, sessionMock); - verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + verify(marshallerMock).marshal(eq(toBeMarshalled), isA(Result.class)); } @Test public void fromTextMessage() throws Exception { - TextMessage textMessageMock = createMock(TextMessage.class); + TextMessage textMessageMock = mock(TextMessage.class); Object unmarshalled = new Object(); String text = "foo"; - expect(textMessageMock.getText()).andReturn(text); - expect(unmarshallerMock.unmarshal(isA(Source.class))).andReturn(unmarshalled); - - replay(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); + given(textMessageMock.getText()).willReturn(text); + given(unmarshallerMock.unmarshal(isA(Source.class))).willReturn(unmarshalled); Object result = converter.fromMessage(textMessageMock); assertEquals("Invalid result", result, unmarshalled); - - verify(marshallerMock, unmarshallerMock, sessionMock, textMessageMock); } - } diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java index e968d8cf28..504e247ee9 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/DynamicDestinationResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,9 @@ package org.springframework.jms.support.destination; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; + import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Queue; @@ -25,7 +28,6 @@ import javax.jms.Topic; import javax.jms.TopicSession; import junit.framework.TestCase; -import org.easymock.MockControl; import org.springframework.jms.StubQueue; import org.springframework.jms.StubTopic; @@ -39,63 +41,31 @@ public class DynamicDestinationResolverTests extends TestCase { public void testResolveWithPubSubTopicSession() throws Exception { - Topic expectedDestination = new StubTopic(); - - MockControl mockSession = MockControl.createControl(TopicSession.class); - TopicSession session = (TopicSession) mockSession.getMock(); - session.createTopic(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + TopicSession session = mock(TopicSession.class); + given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, true); - - mockSession.verify(); } public void testResolveWithPubSubVanillaSession() throws Exception { - Topic expectedDestination = new StubTopic(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createTopic(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + Session session = mock(Session.class); + given(session.createTopic(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, true); - - mockSession.verify(); } public void testResolveWithPointToPointQueueSession() throws Exception { - Queue expectedDestination = new StubQueue(); - - MockControl mockSession = MockControl.createControl(QueueSession.class); - Session session = (Session) mockSession.getMock(); - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + Session session = mock(QueueSession.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, false); - - mockSession.verify(); } public void testResolveWithPointToPointVanillaSession() throws Exception { - Queue expectedDestination = new StubQueue(); - - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - session.createQueue(DESTINATION_NAME); - mockSession.setReturnValue(expectedDestination); - mockSession.replay(); - + Session session = mock(Session.class); + given(session.createQueue(DESTINATION_NAME)).willReturn(expectedDestination); testResolveDestination(session, expectedDestination, false); - - mockSession.verify(); } private static void testResolveDestination(Session session, Destination expectedDestination, boolean isPubSub) throws JMSException { diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java index 133602bcbd..2afd8e6f9c 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JmsDestinationAccessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,9 @@ package org.springframework.jms.support.destination; -import static org.easymock.EasyMock.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; import javax.jms.ConnectionFactory; @@ -31,8 +32,7 @@ public class JmsDestinationAccessorTests { @Test public void testChokesIfDestinationResolverIsetToNullExplcitly() throws Exception { - ConnectionFactory connectionFactory = createMock(ConnectionFactory.class); - replay(connectionFactory); + ConnectionFactory connectionFactory = mock(ConnectionFactory.class); try { JmsDestinationAccessor accessor = new StubJmsDestinationAccessor(); @@ -40,9 +40,11 @@ public class JmsDestinationAccessorTests { accessor.setDestinationResolver(null); accessor.afterPropertiesSet(); fail("expected IllegalArgumentException"); - } catch (IllegalArgumentException ex) { /* expected */ } + } + catch (IllegalArgumentException ex) { + // expected + } - verify(connectionFactory); } @Test diff --git a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java index 9cdf36ef45..548e0334d1 100644 --- a/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java +++ b/spring-jms/src/test/java/org/springframework/jms/support/destination/JndiDestinationResolverTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,13 +16,17 @@ package org.springframework.jms.support.destination; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.mock; import javax.jms.Destination; import javax.jms.Session; import javax.naming.NamingException; -import org.easymock.MockControl; import org.junit.Test; import org.springframework.jms.StubTopic; @@ -40,24 +44,18 @@ public class JndiDestinationResolverTests { @Test public void testHitsCacheSecondTimeThrough() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); JndiDestinationResolver resolver = new OneTimeLookupJndiDestinationResolver(); Destination destination = resolver.resolveDestinationName(session, DESTINATION_NAME, true); assertNotNull(destination); assertSame(DESTINATION, destination); - - mockSession.verify(); } @Test public void testDoesNotUseCacheIfCachingIsTurnedOff() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); CountingCannedJndiDestinationResolver resolver = new CountingCannedJndiDestinationResolver(); @@ -71,21 +69,15 @@ public class JndiDestinationResolverTests { assertNotNull(destination); assertSame(DESTINATION, destination); assertEquals(2, resolver.getCallCount()); - - mockSession.verify(); } @Test public void testDelegatesToFallbackIfNotResolvedInJndi() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - Session session = (Session) mockSession.getMock(); - mockSession.replay(); + Session session = mock(Session.class); - MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class); - DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock(); - dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, true); - mockDestinationResolver.setReturnValue(DESTINATION); - mockDestinationResolver.replay(); + DestinationResolver dynamicResolver = mock(DestinationResolver.class); + given(dynamicResolver.resolveDestinationName(session, DESTINATION_NAME, + true)).willReturn(DESTINATION); JndiDestinationResolver resolver = new JndiDestinationResolver() { @Override @@ -99,20 +91,12 @@ public class JndiDestinationResolverTests { assertNotNull(destination); assertSame(DESTINATION, destination); - - mockSession.verify(); - mockDestinationResolver.verify(); } @Test public void testDoesNotDelegateToFallbackIfNotResolvedInJndi() throws Exception { - MockControl mockSession = MockControl.createControl(Session.class); - final Session session = (Session) mockSession.getMock(); - mockSession.replay(); - - MockControl mockDestinationResolver = MockControl.createControl(DestinationResolver.class); - DestinationResolver dynamicResolver = (DestinationResolver) mockDestinationResolver.getMock(); - mockDestinationResolver.replay(); + final Session session = mock(Session.class); + DestinationResolver dynamicResolver = mock(DestinationResolver.class); final JndiDestinationResolver resolver = new JndiDestinationResolver() { @Override @@ -125,10 +109,10 @@ public class JndiDestinationResolverTests { try { resolver.resolveDestinationName(session, DESTINATION_NAME, true); fail("expected DestinationResolutionException"); - } catch (DestinationResolutionException ex) { /* expected */ } - - mockSession.verify(); - mockDestinationResolver.verify(); + } + catch (DestinationResolutionException ex) { + // expected + } } From c4194ee1755e5f2a90df3839a5dc687aee10653f Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 23:03:36 +0100 Subject: [PATCH 215/311] Added paragraph on BeanPostProcessor side effects when autowiring dependencies into it (SPR-9577) --- .../docbook/beans-extension-points.xml | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/reference/docbook/beans-extension-points.xml b/src/reference/docbook/beans-extension-points.xml index 551496d7be..d2a0aa80c3 100644 --- a/src/reference/docbook/beans-extension-points.xml +++ b/src/reference/docbook/beans-extension-points.xml @@ -65,8 +65,7 @@ />. - The - org.springframework.beans.factory.config.BeanPostProcessor + The org.springframework.beans.factory.config.BeanPostProcessor interface consists of exactly two callback methods. When such a class is registered as a post-processor with the container, for each bean instance that is created by the container, the post-processor gets a callback from @@ -93,8 +92,7 @@ Programmatically registering <interfacename>BeanPostProcessors </interfacename> - - While the recommended approach for BeanPostProcessor + While the recommended approach for BeanPostProcessor registration is through ApplicationContext auto-detection (as described above), it is also possible to register them programmatically @@ -108,8 +106,7 @@ registration that dictates the order of execution. Note also that BeanPostProcessors registered programmatically are always processed before those registered through - auto-detection, regardless of any explicit ordering. - + auto-detection, regardless of any explicit ordering. @@ -135,6 +132,14 @@ Bean foo is not eligible for getting processed by all BeanPostProcessor interfaces (for example: not eligible for auto-proxying). + + Note that if you have beans wired into your BeanPostProcessor + using autowiring or @Resource (which may fall back to autowiring), + Spring might access unexpected beans when searching for type-matching dependency candidates, + and therefore make them ineligible for auto-proxying or other kinds of bean post-processing. + For example, if you have a dependency annotated with @Resource + where the field/setter name does not directly correspond to the declared name of a bean and + no name attribute is used, then Spring will access other beans for matching them by type. The following examples show how to write, register, and use From d442c40e0c2b60969dc0d9194a07cb9932df6717 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Sun, 10 Feb 2013 23:24:25 +0100 Subject: [PATCH 216/311] Added section on GemFire as a cache provider choice (SPR-9468) --- src/reference/docbook/cache.xml | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/reference/docbook/cache.xml b/src/reference/docbook/cache.xml index 2ed4ab2b3f..01fa2d5a87 100644 --- a/src/reference/docbook/cache.xml +++ b/src/reference/docbook/cache.xml @@ -57,7 +57,7 @@ Note that just like other services in Spring Framework, the caching service is an abstraction (not a cache implementation) and requires the use of an actual storage to store the cache data - that is, the abstraction frees the developer from having to write the caching logic but does not provide the actual stores. There are two integrations available out of the box, for JDK java.util.concurrent.ConcurrentMap - and Ehcache - see for more information on plugging in other cache stores/providers. + and EhCache - see for more information on plugging in other cache stores/providers.

@@ -558,20 +558,28 @@ public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)]]><
- Ehcache-based <interfacename>Cache</interfacename> + EhCache-based <interfacename>Cache</interfacename> - The Ehcache implementation is located under org.springframework.cache.ehcache package. Again, to use it, one simply needs to declare the appropriate + The EhCache implementation is located under org.springframework.cache.ehcache package. Again, to use it, one simply needs to declare the appropriate CacheManager: - + ]]> This setup bootstraps ehcache library inside Spring IoC (through bean ehcache) which is then wired into the dedicated CacheManager implementation. Note the entire ehcache-specific configuration is read from the resource ehcache.xml.
+
+ GemFire-based <interfacename>Cache</interfacename> + + GemFire is a memory-oriented/disk-backed, elastically scalable, continuously available, active (with built-in pattern-based subscription notifications), + globally replicated database and provides fully-featured edge caching. For further information on how to use GemFire as a CacheManager (and more), please refer + to the Spring GemFire reference documentation. +
+
Dealing with caches without a backing store From 634284e1fdd9a32b7356117055bc62b64d6e0add Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sun, 10 Feb 2013 16:25:38 -0800 Subject: [PATCH 217/311] Use bridge methods in ReflectiveMethodResolver Update ReflectiveMethodResolver to consider bridge methods. Issue: SPR-10210 --- .../support/ReflectiveMethodResolver.java | 34 +++++++++---------- .../expression/spel/SpelReproTests.java | 10 ++++++ .../expression/spel/spr10210/A.java | 23 +++++++++++++ .../expression/spel/spr10210/D.java | 20 +++++++++++ .../expression/spel/spr10210/comp/B.java | 24 +++++++++++++ .../expression/spel/spr10210/infra/C.java | 20 +++++++++++ 6 files changed, 113 insertions(+), 18 deletions(-) create mode 100644 spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java create mode 100644 spring-expression/src/test/java/org/springframework/expression/spel/spr10210/D.java create mode 100644 spring-expression/src/test/java/org/springframework/expression/spel/spr10210/comp/B.java create mode 100644 spring-expression/src/test/java/org/springframework/expression/spel/spr10210/infra/C.java diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java index c086771cbe..ce6ad5123b 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/support/ReflectiveMethodResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,16 @@ package org.springframework.expression.spel.support; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.springframework.core.BridgeMethodResolver; import org.springframework.core.MethodParameter; import org.springframework.core.convert.TypeDescriptor; import org.springframework.expression.AccessException; @@ -37,7 +40,6 @@ import org.springframework.expression.MethodResolver; import org.springframework.expression.TypeConverter; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; -import org.springframework.util.CollectionUtils; /** * Reflection-based {@link MethodResolver} used by default in @@ -92,25 +94,16 @@ public class ReflectiveMethodResolver implements MethodResolver { try { TypeConverter typeConverter = context.getTypeConverter(); Class type = (targetObject instanceof Class ? (Class) targetObject : targetObject.getClass()); - Method[] methods = getMethods(type, targetObject); + List methods = new ArrayList(Arrays.asList(getMethods(type, targetObject))); // If a filter is registered for this type, call it MethodFilter filter = (this.filters != null ? this.filters.get(type) : null); if (filter != null) { - List methodsForFiltering = new ArrayList(); - for (Method method: methods) { - methodsForFiltering.add(method); - } - List methodsFiltered = filter.filter(methodsForFiltering); - if (CollectionUtils.isEmpty(methodsFiltered)) { - methods = NO_METHODS; - } - else { - methods = methodsFiltered.toArray(new Method[methodsFiltered.size()]); - } + methods = filter.filter(methods); } - Arrays.sort(methods, new Comparator() { + // Sort methods into a sensible order + Collections.sort(methods, new Comparator() { public int compare(Method m1, Method m2) { int m1pl = m1.getParameterTypes().length; int m2pl = m2.getParameterTypes().length; @@ -118,6 +111,14 @@ public class ReflectiveMethodResolver implements MethodResolver { } }); + // Resolve any bridge methods + for (int i = 0; i < methods.size(); i++) { + methods.set(i, BridgeMethodResolver.findBridgedMethod(methods.get(i))); + } + + // Remove duplicate methods (possible due to resolved bridge methods) + methods = new ArrayList(new LinkedHashSet(methods)); + Method closeMatch = null; int closeMatchDistance = Integer.MAX_VALUE; int[] argsToConvert = null; @@ -125,9 +126,6 @@ public class ReflectiveMethodResolver implements MethodResolver { boolean multipleOptions = false; for (Method method : methods) { - if (method.isBridge()) { - continue; - } if (method.getName().equals(name)) { Class[] paramTypes = method.getParameterTypes(); List paramDescriptors = new ArrayList(paramTypes.length); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index fdf04c7ba8..d84ef3bd99 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; @@ -1736,6 +1737,14 @@ public class SpelReproTests extends ExpressionTestCase { assertThat(fromClass, is("interfaceValue")); } + @Test + public void SPR_10210() throws Exception { + StandardEvaluationContext context = new StandardEvaluationContext(); + context.setVariable("bridgeExample", new org.springframework.expression.spel.spr10210.D()); + Expression parseExpression = parser.parseExpression("#bridgeExample.bridgetMethod()"); + parseExpression.getValue(context); + } + public static class BooleanHolder { private Boolean simpleProperty = true; @@ -1796,4 +1805,5 @@ public class SpelReproTests extends ExpressionTestCase { public static class StaticFinalImpl2 extends AbstractStaticFinal { } + } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java new file mode 100644 index 0000000000..9d8d6395ef --- /dev/null +++ b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java @@ -0,0 +1,23 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.expression.spel.spr10210; + +import org.springframework.expression.spel.spr10210.comp.B; +import org.springframework.expression.spel.spr10210.infra.C; + +abstract class A extends B { +} diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/D.java b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/D.java new file mode 100644 index 0000000000..e4776d70e6 --- /dev/null +++ b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/D.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.expression.spel.spr10210; + +public class D extends A { +} diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/comp/B.java b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/comp/B.java new file mode 100644 index 0000000000..3250836265 --- /dev/null +++ b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/comp/B.java @@ -0,0 +1,24 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.expression.spel.spr10210.comp; + +import java.io.Serializable; + +import org.springframework.expression.spel.spr10210.infra.C; + +public class B implements Serializable { +} diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/infra/C.java b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/infra/C.java new file mode 100644 index 0000000000..2f0a32e53b --- /dev/null +++ b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/infra/C.java @@ -0,0 +1,20 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.expression.spel.spr10210.infra; + +public interface C { +} From 0b6101478e705f5fff1fa7e1cd2b1159ac60280c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sun, 10 Feb 2013 17:17:23 -0800 Subject: [PATCH 218/311] Use bridge methods in ReflectiveMethodResolver Fix failing test Issue: SPR-10210 --- .../org/springframework/expression/spel/SpelReproTests.java | 1 - .../java/org/springframework/expression/spel/spr10210/A.java | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index d84ef3bd99..549b44aa53 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -24,7 +24,6 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java index 9d8d6395ef..35f2f0de93 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java @@ -20,4 +20,8 @@ import org.springframework.expression.spel.spr10210.comp.B; import org.springframework.expression.spel.spr10210.infra.C; abstract class A extends B { + + public void bridgetMethod() { + } + } From 19eecb151b8a0e2b2dad1aa4baf4c552587342fb Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sun, 10 Feb 2013 18:54:28 -0800 Subject: [PATCH 219/311] Add @Ignored Test case to reproduce SPR-10243 Issue: SPR-10243 --- .../beanvalidation/ValidatorFactoryTests.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java index 3e6cac5759..f28b7e35bd 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java @@ -35,6 +35,7 @@ import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.hibernate.validator.HibernateValidator; +import org.junit.Ignore; import org.junit.Test; import org.springframework.validation.BeanPropertyBindingResult; @@ -42,6 +43,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.*; /** @@ -102,6 +104,22 @@ public class ValidatorFactoryTests { assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid); } + @Test + @Ignore + public void testSpringValidationFieldType() throws Exception { + LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); + validator.afterPropertiesSet(); + ValidPerson person = new ValidPerson(); + person.setName("Phil"); + person.getAddress().setStreet("Phil's Street"); + BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); + validator.validate(person, errors); + assertEquals(1, errors.getErrorCount()); + assertThat("Field/Value type missmatch", + errors.getFieldError("address").getRejectedValue(), + instanceOf(ValidAddress.class)); + } + @Test public void testSpringValidation() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); @@ -289,8 +307,13 @@ public class ValidatorFactoryTests { } @Override - public boolean isValid(ValidPerson value, ConstraintValidatorContext constraintValidatorContext) { - return (value.name == null || !value.address.street.contains(value.name)); + public boolean isValid(ValidPerson value, ConstraintValidatorContext context) { + boolean valid = (value.name == null || !value.address.street.contains(value.name)); + if (!valid && "Phil".equals(value.name)) { + context.buildConstraintViolationWithTemplate( + context.getDefaultConstraintMessageTemplate()).addNode("address").addConstraintViolation().disableDefaultConstraintViolation(); + } + return valid; } } From cef97819c53e41f1736ba778170740f0935c5edc Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 11 Feb 2013 12:21:46 +0100 Subject: [PATCH 220/311] Fixed regression in SpringValidatorAdapter's retrieval of invalid values Issue: SPR-10243 --- .../validation/beanvalidation/SpringValidatorAdapter.java | 3 ++- .../validation/beanvalidation/ValidatorFactoryTests.java | 7 ++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java b/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java index 7565e82099..f3c45fc2fa 100644 --- a/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java +++ b/spring-context/src/main/java/org/springframework/validation/beanvalidation/SpringValidatorAdapter.java @@ -130,7 +130,8 @@ public class SpringValidatorAdapter implements SmartValidator, javax.validation. } else { Object invalidValue = violation.getInvalidValue(); - if (field.contains(".") && !field.contains("[]")) { + if (!"".equals(field) && (invalidValue == violation.getLeafBean() || + (field.contains(".") && !field.contains("[]")))) { // Possibly a bean constraint with property path: retrieve the actual property value. // However, explicitly avoid this for "address[]" style paths that we can't handle. invalidValue = bindingResult.getRawFieldValue(field); diff --git a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java index f28b7e35bd..be4f45213a 100644 --- a/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java +++ b/spring-context/src/test/java/org/springframework/validation/beanvalidation/ValidatorFactoryTests.java @@ -35,7 +35,6 @@ import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.hibernate.validator.HibernateValidator; -import org.junit.Ignore; import org.junit.Test; import org.springframework.validation.BeanPropertyBindingResult; @@ -43,7 +42,7 @@ import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; -import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; /** @@ -105,7 +104,6 @@ public class ValidatorFactoryTests { } @Test - @Ignore public void testSpringValidationFieldType() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); @@ -115,8 +113,7 @@ public class ValidatorFactoryTests { BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person"); validator.validate(person, errors); assertEquals(1, errors.getErrorCount()); - assertThat("Field/Value type missmatch", - errors.getFieldError("address").getRejectedValue(), + assertThat("Field/Value type mismatch", errors.getFieldError("address").getRejectedValue(), instanceOf(ValidAddress.class)); } From 6fc0790c5f27a69c3ce84d50217a606f4e07b08b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 11 Feb 2013 13:09:05 +0100 Subject: [PATCH 221/311] Added note on EhCache 2.1+ as recommended version --- .../cache/ehcache/EhCacheFactoryBean.java | 29 ++++++++--------- .../ehcache/EhCacheManagerFactoryBean.java | 31 ++++++++++--------- 2 files changed, 31 insertions(+), 29 deletions(-) diff --git a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java index fc2ad00022..dcec4047ee 100644 --- a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java +++ b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -40,9 +40,9 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** - * {@link FactoryBean} that creates a named EHCache {@link net.sf.ehcache.Cache} instance + * {@link FactoryBean} that creates a named EhCache {@link net.sf.ehcache.Cache} instance * (or a decorator that implements the {@link net.sf.ehcache.Ehcache} interface), - * representing a cache region within an EHCache {@link net.sf.ehcache.CacheManager}. + * representing a cache region within an EhCache {@link net.sf.ehcache.CacheManager}. * *

If the specified named cache is not configured in the cache configuration descriptor, * this FactoryBean will construct an instance of a Cache with the provided name and the @@ -52,7 +52,8 @@ import org.springframework.util.Assert; *

Note: If the named Cache instance is found, the properties will be ignored and the * Cache instance will be retrieved from the CacheManager. * - *

Note: As of Spring 3.0, Spring's EHCache support requires EHCache 1.3 or higher. + *

Note: As of Spring 3.0, Spring's EhCache support requires EhCache 1.3 or higher. + * As of Spring 3.2, we recommend using EhCache 2.1 or higher. * @author Dmitriy Kopylenko * @author Juergen Hoeller @@ -117,7 +118,7 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, * properly handle the shutdown of the CacheManager: Set up a separate * EhCacheManagerFactoryBean and pass a reference to this bean property. *

A separate EhCacheManagerFactoryBean is also necessary for loading - * EHCache configuration from a non-default config location. + * EhCache configuration from a non-default config location. * @see EhCacheManagerFactoryBean * @see net.sf.ehcache.CacheManager#getInstance */ @@ -152,7 +153,7 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, /** * Set the memory style eviction policy for this cache. *

Supported values are "LRU", "LFU" and "FIFO", according to the - * constants defined in EHCache's MemoryStoreEvictionPolicy class. + * constants defined in EhCache's MemoryStoreEvictionPolicy class. * Default is "LRU". */ public void setMemoryStoreEvictionPolicy(MemoryStoreEvictionPolicy memoryStoreEvictionPolicy) { @@ -239,9 +240,9 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, } /** - * Set an EHCache {@link net.sf.ehcache.constructs.blocking.CacheEntryFactory} + * Set an EhCache {@link net.sf.ehcache.constructs.blocking.CacheEntryFactory} * to use for a self-populating cache. If such a factory is specified, - * the cache will be decorated with EHCache's + * the cache will be decorated with EhCache's * {@link net.sf.ehcache.constructs.blocking.SelfPopulatingCache}. *

The specified factory can be of type * {@link net.sf.ehcache.constructs.blocking.UpdatingCacheEntryFactory}, @@ -257,7 +258,7 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, } /** - * Set an EHCache {@link net.sf.ehcache.bootstrap.BootstrapCacheLoader} + * Set an EhCache {@link net.sf.ehcache.bootstrap.BootstrapCacheLoader} * for this cache, if any. */ public void setBootstrapCacheLoader(BootstrapCacheLoader bootstrapCacheLoader) { @@ -265,7 +266,7 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, } /** - * Specify EHCache {@link net.sf.ehcache.event.CacheEventListener cache event listeners} + * Specify EhCache {@link net.sf.ehcache.event.CacheEventListener cache event listeners} * to registered with this cache. */ public void setCacheEventListeners(Set cacheEventListeners) { @@ -305,7 +306,7 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, // If no CacheManager given, fetch the default. if (this.cacheManager == null) { if (logger.isDebugEnabled()) { - logger.debug("Using default EHCache CacheManager for cache region '" + this.cacheName + "'"); + logger.debug("Using default EhCache CacheManager for cache region '" + this.cacheName + "'"); } this.cacheManager = CacheManager.getInstance(); } @@ -320,13 +321,13 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, Ehcache rawCache; if (this.cacheManager.cacheExists(this.cacheName)) { if (logger.isDebugEnabled()) { - logger.debug("Using existing EHCache cache region '" + this.cacheName + "'"); + logger.debug("Using existing EhCache cache region '" + this.cacheName + "'"); } rawCache = this.cacheManager.getEhcache(this.cacheName); } else { if (logger.isDebugEnabled()) { - logger.debug("Creating new EHCache cache region '" + this.cacheName + "'"); + logger.debug("Creating new EhCache cache region '" + this.cacheName + "'"); } rawCache = createCache(); this.cacheManager.addCache(rawCache); @@ -359,7 +360,7 @@ public class EhCacheFactoryBean implements FactoryBean, BeanNameAware, * Create a raw Cache object based on the configuration of this FactoryBean. */ protected Cache createCache() { - // Only call EHCache 1.6 constructor if actually necessary (for compatibility with EHCache 1.3+) + // Only call EhCache 1.6 constructor if actually necessary (for compatibility with EhCache 1.3+) return (!this.clearOnFlush) ? new Cache(this.cacheName, this.maxElementsInMemory, this.memoryStoreEvictionPolicy, this.overflowToDisk, null, this.eternal, this.timeToLive, this.timeToIdle, diff --git a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java index a170eb84f8..a94c1fe2cb 100644 --- a/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java +++ b/spring-context-support/src/main/java/org/springframework/cache/ehcache/EhCacheManagerFactoryBean.java @@ -35,19 +35,20 @@ import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; /** - * {@link FactoryBean} that exposes an EHCache {@link net.sf.ehcache.CacheManager} + * {@link FactoryBean} that exposes an EhCache {@link net.sf.ehcache.CacheManager} * instance (independent or shared), configured from a specified config location. * *

If no config location is specified, a CacheManager will be configured from - * "ehcache.xml" in the root of the class path (that is, default EHCache initialization - * - as defined in the EHCache docs - will apply). + * "ehcache.xml" in the root of the class path (that is, default EhCache initialization + * - as defined in the EhCache docs - will apply). * *

Setting up a separate EhCacheManagerFactoryBean is also advisable when using * EhCacheFactoryBean, as it provides a (by default) independent CacheManager instance * and cares for proper shutdown of the CacheManager. EhCacheManagerFactoryBean is - * also necessary for loading EHCache configuration from a non-default config location. + * also necessary for loading EhCache configuration from a non-default config location. * - *

Note: As of Spring 3.0, Spring's EHCache support requires EHCache 1.3 or higher. + *

Note: As of Spring 3.0, Spring's EhCache support requires EhCache 1.3 or higher. + * As of Spring 3.2, we recommend using EhCache 2.1 or higher. * * @author Dmitriy Kopylenko * @author Juergen Hoeller @@ -59,7 +60,7 @@ import org.springframework.util.ReflectionUtils; */ public class EhCacheManagerFactoryBean implements FactoryBean, InitializingBean, DisposableBean { - // Check whether EHCache 2.1+ CacheManager.create(Configuration) method is available... + // Check whether EhCache 2.1+ CacheManager.create(Configuration) method is available... private static final Method createWithConfiguration = ClassUtils.getMethodIfAvailable(CacheManager.class, "create", Configuration.class); @@ -75,9 +76,9 @@ public class EhCacheManagerFactoryBean implements FactoryBean, Ini /** - * Set the location of the EHCache config file. A typical value is "/WEB-INF/ehcache.xml". + * Set the location of the EhCache config file. A typical value is "/WEB-INF/ehcache.xml". *

Default is "ehcache.xml" in the root of the class path, or if not found, - * "ehcache-failsafe.xml" in the EHCache jar (default EHCache initialization). + * "ehcache-failsafe.xml" in the EhCache jar (default EhCache initialization). * @see net.sf.ehcache.CacheManager#create(java.io.InputStream) * @see net.sf.ehcache.CacheManager#CacheManager(java.io.InputStream) */ @@ -86,7 +87,7 @@ public class EhCacheManagerFactoryBean implements FactoryBean, Ini } /** - * Set whether the EHCache CacheManager should be shared (as a singleton at the VM level) + * Set whether the EhCache CacheManager should be shared (as a singleton at the VM level) * or independent (typically local within the application). Default is "false", creating * an independent instance. * @see net.sf.ehcache.CacheManager#create() @@ -97,7 +98,7 @@ public class EhCacheManagerFactoryBean implements FactoryBean, Ini } /** - * Set the name of the EHCache CacheManager (if a specific name is desired). + * Set the name of the EhCache CacheManager (if a specific name is desired). * @see net.sf.ehcache.CacheManager#setName(String) */ public void setCacheManagerName(String cacheManagerName) { @@ -106,14 +107,14 @@ public class EhCacheManagerFactoryBean implements FactoryBean, Ini public void afterPropertiesSet() throws IOException, CacheException { - logger.info("Initializing EHCache CacheManager"); + logger.info("Initializing EhCache CacheManager"); InputStream is = (this.configLocation != null ? this.configLocation.getInputStream() : null); try { - // A bit convoluted for EHCache 1.x/2.0 compatibility. - // To be much simpler once we require EHCache 2.1+ + // A bit convoluted for EhCache 1.x/2.0 compatibility. + // To be much simpler once we require EhCache 2.1+ if (this.cacheManagerName != null) { if (this.shared && createWithConfiguration == null) { - // No CacheManager.create(Configuration) method available before EHCache 2.1; + // No CacheManager.create(Configuration) method available before EhCache 2.1; // can only set CacheManager name after creation. this.cacheManager = (is != null ? CacheManager.create(is) : CacheManager.create()); this.cacheManager.setName(this.cacheManagerName); @@ -160,7 +161,7 @@ public class EhCacheManagerFactoryBean implements FactoryBean, Ini public void destroy() { - logger.info("Shutting down EHCache CacheManager"); + logger.info("Shutting down EhCache CacheManager"); this.cacheManager.shutdown(); } From 536325bc7524e9ba7c142eb13adc85fe272a28de Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 11 Feb 2013 09:18:57 -0800 Subject: [PATCH 222/311] Make HierarchicalUriComponents Serializable Issue: SPR-10266 --- .../web/util/HierarchicalUriComponents.java | 3 ++- .../web/util/UriComponentsTests.java | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index 103784e9c2..720ca4fad7 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -17,6 +17,7 @@ package org.springframework.web.util; import java.io.ByteArrayOutputStream; +import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; @@ -615,7 +616,7 @@ final class HierarchicalUriComponents extends UriComponents { /** * Defines the contract for path (segments). */ - interface PathComponent { + interface PathComponent extends Serializable { String getPath(); diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java index c9f8d60917..7fd5ccffd6 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java @@ -16,11 +16,16 @@ package org.springframework.web.util; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; import java.net.URI; import java.net.URISyntaxException; import org.junit.Test; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; /** @author Arjen Poutsma */ @@ -75,4 +80,16 @@ public class UriComponentsTests { assertEquals("http://example.com/bar", uriComponents.normalize().toString()); } + @Test + public void serializable() throws Exception { + UriComponents uriComponents = UriComponentsBuilder.fromUriString( + "http://example.com").path("/{foo}").query("bar={baz}").build(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(bos); + oos.writeObject(uriComponents); + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); + UriComponents readObject = (UriComponents) ois.readObject(); + assertThat(uriComponents.toString(), equalTo(readObject.toString())); + } + } From f32ce3a6130fc6ebe2463d7125ef69396ff34646 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 11 Feb 2013 09:25:30 -0800 Subject: [PATCH 223/311] Make HierarchicalUriComponents Serializable (fix apache header copyright dates) Issue: SPR-10266 --- .../org/springframework/web/util/HierarchicalUriComponents.java | 2 +- .../java/org/springframework/web/util/UriComponentsTests.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index 720ca4fad7..9c33379422 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java index 7fd5ccffd6..c1ad072e8b 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. From 203b22b2462bd2c05791fde937f69312e2cfe6c3 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 11 Feb 2013 09:39:51 -0800 Subject: [PATCH 224/311] UriComponentsBuilder supports query without value Fix UriComponentsBuilder to support query parameters that do not include a value without losing '='. The following styles are now supported: http://example.com/foo?bar=baz http://example.com/foo?bar= http://example.com/foo?bar Issue: SPR-10215 --- .../web/util/UriComponentsBuilder.java | 10 +++++---- .../web/util/UriComponentsBuilderTests.java | 22 ++++++++++++++++++- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java index 141cd7b86e..4a1aa85af9 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ import org.springframework.util.StringUtils; */ 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 = "([^:/?#]+):"; @@ -496,8 +496,10 @@ public class UriComponentsBuilder { Matcher m = QUERY_PARAM_PATTERN.matcher(query); while (m.find()) { String name = m.group(1); - String value = m.group(2); - queryParam(name, value); + String eq = m.group(2); + String value = m.group(3); + queryParam(name, (value != null ? value : + (StringUtils.hasLength(eq) ? "" : null))); } } else { diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 8205ca6cdf..afa1691008 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,10 +27,12 @@ import org.junit.Test; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.*; /** * @author Arjen Poutsma + * @author Phillip Webb */ public class UriComponentsBuilderTests { @@ -312,4 +314,22 @@ public class UriComponentsBuilderTests { assertEquals("mailto:foo@example.com", result.toUriString()); } + @Test + public void queryParamWithValueWithEquals() throws Exception { + UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://example.com/foo?bar=baz").build(); + assertThat(uriComponents.toUriString(), equalTo("http://example.com/foo?bar=baz")); + } + + @Test + public void queryParamWithoutValueWithEquals() throws Exception { + UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://example.com/foo?bar=").build(); + assertThat(uriComponents.toUriString(), equalTo("http://example.com/foo?bar=")); + } + + @Test + public void queryParamWithoutValueWithoutEquals() throws Exception { + UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://example.com/foo?bar").build(); + assertThat(uriComponents.toUriString(), equalTo("http://example.com/foo?bar")); + } + } From 2ca75386f1e9a1c9f12c71ce56e47c3dee998703 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 11 Feb 2013 11:17:23 -0800 Subject: [PATCH 225/311] Align UriComponents.toUri() with toUriString() Update HierarchicalUriComponents.toUri() to only prepend a missing '/' when the scheme, user info, host or port are specified. This makes the toUri() method behave in the same way as .toUriString() and allows relative URIs to be created. Issue: SPR-10231 --- .../web/util/HierarchicalUriComponents.java | 5 ++++- .../web/util/UriComponentsBuilderTests.java | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index 9c33379422..dce503962c 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -407,7 +407,10 @@ final class HierarchicalUriComponents extends UriComponents { else { String path = getPath(); if (StringUtils.hasLength(path) && path.charAt(0) != PATH_DELIMITER) { - path = PATH_DELIMITER + path; + // Only prefix the path delimiter if something exists before it + if(getScheme() != null || getUserInfo() != null || getHost() != null || getPort() != -1) { + path = PATH_DELIMITER + path; + } } return new URI(getScheme(), getUserInfo(), getHost(), getPort(), path, getQuery(), getFragment()); diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index afa1691008..3040ee4aa9 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -57,7 +57,9 @@ public class UriComponentsBuilderTests { assertEquals("bar", result.getQuery()); assertEquals("baz", result.getFragment()); - URI expected = new URI("/foo?bar#baz"); + assertEquals("Invalid result URI String", "foo?bar#baz", result.toUriString()); + + URI expected = new URI("foo?bar#baz"); assertEquals("Invalid result URI", expected, result.toUri()); result = UriComponentsBuilder.fromPath("/foo").build(); @@ -332,4 +334,16 @@ public class UriComponentsBuilderTests { assertThat(uriComponents.toUriString(), equalTo("http://example.com/foo?bar")); } + @Test + public void relativeUrls() throws Exception { + assertThat(UriComponentsBuilder.fromUriString("http://example.com/foo/../bar").build().toString(), equalTo("http://example.com/foo/../bar")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com/foo/../bar").build().toUriString(), equalTo("http://example.com/foo/../bar")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com/foo/../bar").build().toUri().getPath(), equalTo("/foo/../bar")); + assertThat(UriComponentsBuilder.fromUriString("../../").build().toString(), equalTo("../../")); + assertThat(UriComponentsBuilder.fromUriString("../../").build().toUriString(), equalTo("../../")); + assertThat(UriComponentsBuilder.fromUriString("../../").build().toUri().getPath(), equalTo("../../")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toString(), equalTo("http://example.com/foo/../bar")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toUriString(), equalTo("http://example.com/foo/../bar")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toUri().getPath(), equalTo("/foo/../bar")); + } } From 23925edc95655d5d6ff664aa28e2fe9f27cad38c Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 11 Feb 2013 21:49:14 +0100 Subject: [PATCH 226/311] Added "mappedClass" property to Jaxb2Marshaller, introducing support for partial unmarshalling Issue: SPR-10282 --- .../oxm/jaxb/Jaxb2Marshaller.java | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java index 956c003233..3684aa3b9f 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -155,14 +155,16 @@ public class Jaxb2Marshaller private LSResourceResolver schemaResourceResolver; - private boolean mtomEnabled = false; - private boolean lazyInit = false; + private boolean mtomEnabled = false; + private boolean supportJaxbElementClass = false; private boolean checkForXmlRootElement = true; + private Class mappedClass; + private ClassLoader beanClassLoader; private ResourceLoader resourceLoader; @@ -329,14 +331,6 @@ public class Jaxb2Marshaller this.schemaResourceResolver = schemaResourceResolver; } - /** - * Specify whether MTOM support should be enabled or not. - * Default is {@code false}: marshalling using XOP/MTOM not being enabled. - */ - public void setMtomEnabled(boolean mtomEnabled) { - this.mtomEnabled = mtomEnabled; - } - /** * Set whether to lazily initialize the {@link JAXBContext} for this marshaller. * Default is {@code false} to initialize on startup; can be switched to {@code true}. @@ -346,14 +340,22 @@ public class Jaxb2Marshaller this.lazyInit = lazyInit; } + /** + * Specify whether MTOM support should be enabled or not. + * Default is {@code false}: marshalling using XOP/MTOM not being enabled. + */ + public void setMtomEnabled(boolean mtomEnabled) { + this.mtomEnabled = mtomEnabled; + } + /** * Specify whether the {@link #supports(Class)} returns {@code true} for the {@link JAXBElement} class. *

Default is {@code false}, meaning that {@code supports(Class)} always returns {@code false} for - * {@code JAXBElement} classes (though {@link #supports(Type)} can return {@code true}, since it can obtain the - * type parameters of {@code JAXBElement}). + * {@code JAXBElement} classes (though {@link #supports(Type)} can return {@code true}, since it can + * obtain the type parameters of {@code JAXBElement}). *

This property is typically enabled in combination with usage of classes like - * {@link org.springframework.web.servlet.view.xml.MarshallingView MarshallingView}, since the {@code ModelAndView} - * does not offer type parameter information at runtime. + * {@link org.springframework.web.servlet.view.xml.MarshallingView MarshallingView}, + * since the {@code ModelAndView} does not offer type parameter information at runtime. * @see #supports(Class) * @see #supports(Type) */ @@ -376,6 +378,14 @@ public class Jaxb2Marshaller this.checkForXmlRootElement = checkForXmlRootElement; } + /** + * Specify a JAXB mapped class for partial unmarshalling. + * @see javax.xml.bind.Unmarshaller#unmarshal(javax.xml.transform.Source, Class) + */ + public void setMappedClass(Class mappedClass) { + this.mappedClass = mappedClass; + } + public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } @@ -384,6 +394,7 @@ public class Jaxb2Marshaller this.resourceLoader = resourceLoader; } + public final void afterPropertiesSet() throws Exception { boolean hasContextPath = StringUtils.hasLength(this.contextPath); boolean hasClassesToBeBound = !ObjectUtils.isEmpty(this.classesToBeBound); @@ -707,6 +718,9 @@ public class Jaxb2Marshaller if (StaxUtils.isStaxSource(source)) { return unmarshalStaxSource(unmarshaller, source); } + else if (this.mappedClass != null) { + return unmarshaller.unmarshal(source, this.mappedClass); + } else { return unmarshaller.unmarshal(source); } @@ -716,7 +730,7 @@ public class Jaxb2Marshaller } } - private Object unmarshalStaxSource(Unmarshaller jaxbUnmarshaller, Source staxSource) throws JAXBException { + protected Object unmarshalStaxSource(Unmarshaller jaxbUnmarshaller, Source staxSource) throws JAXBException { XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(staxSource); if (streamReader != null) { return jaxbUnmarshaller.unmarshal(streamReader); From 93e6238f927f7dfb39d72641c28b2be85fd5388d Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 11 Feb 2013 21:51:02 +0100 Subject: [PATCH 227/311] Polishing --- .../springframework/util/xml/StaxResult.java | 54 +++++++++--------- .../springframework/util/xml/StaxSource.java | 56 +++++++++---------- .../springframework/util/xml/StaxUtils.java | 34 +++++------ 3 files changed, 68 insertions(+), 76 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/xml/StaxResult.java b/spring-core/src/main/java/org/springframework/util/xml/StaxResult.java index c001902252..801769cdfa 100644 --- a/spring-core/src/main/java/org/springframework/util/xml/StaxResult.java +++ b/spring-core/src/main/java/org/springframework/util/xml/StaxResult.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,24 +24,24 @@ import javax.xml.transform.sax.SAXResult; import org.xml.sax.ContentHandler; /** - * Implementation of the {@code Result} tagging interface for StAX writers. Can be constructed with a - * {@code XMLEventConsumer} or a {@code XMLStreamWriter}. + * Implementation of the {@code Result} tagging interface for StAX writers. Can be constructed with + * an {@code XMLEventConsumer} or an {@code XMLStreamWriter}. * - *

This class is necessary because there is no implementation of {@code Source} for StaxReaders in JAXP 1.3. - * There is a {@code StAXResult} in JAXP 1.4 (JDK 1.6), but this class is kept around for back-ward compatibility - * reasons. + *

This class is necessary because there is no implementation of {@code Source} for StaxReaders + * in JAXP 1.3. There is a {@code StAXResult} in JAXP 1.4 (JDK 1.6), but this class is kept around + * for backwards compatibility reasons. * *

Even though {@code StaxResult} extends from {@code SAXResult}, calling the methods of - * {@code SAXResult} is not supported. In general, the only supported operation on this class is - * to use the {@code ContentHandler} obtained via {@link #getHandler()} to parse an input source using an - * {@code XMLReader}. Calling {@link #setHandler(org.xml.sax.ContentHandler)} will result in - * {@code UnsupportedOperationException}s. + * {@code SAXResult} is not supported. In general, the only supported operation + * on this class is to use the {@code ContentHandler} obtained via {@link #getHandler()} to parse an + * input source using an {@code XMLReader}. Calling {@link #setHandler(org.xml.sax.ContentHandler)} + * will result in {@code UnsupportedOperationException}s. * * @author Arjen Poutsma + * @since 3.0 * @see XMLEventWriter * @see XMLStreamWriter * @see javax.xml.transform.Transformer - * @since 3.0 */ class StaxResult extends SAXResult { @@ -49,9 +49,9 @@ class StaxResult extends SAXResult { private XMLStreamWriter streamWriter; + /** - * Constructs a new instance of the {@code StaxResult} with the specified {@code XMLStreamWriter}. - * + * Construct a new instance of the {@code StaxResult} with the specified {@code XMLStreamWriter}. * @param streamWriter the {@code XMLStreamWriter} to write to */ StaxResult(XMLStreamWriter streamWriter) { @@ -60,8 +60,7 @@ class StaxResult extends SAXResult { } /** - * Constructs a new instance of the {@code StaxResult} with the specified {@code XMLEventWriter}. - * + * Construct a new instance of the {@code StaxResult} with the specified {@code XMLEventWriter}. * @param eventWriter the {@code XMLEventWriter} to write to */ StaxResult(XMLEventWriter eventWriter) { @@ -70,9 +69,8 @@ class StaxResult extends SAXResult { } /** - * Constructs a new instance of the {@code StaxResult} with the specified {@code XMLEventWriter} and - * {@code XMLEventFactory}. - * + * Construct a new instance of the {@code StaxResult} with the specified {@code XMLEventWriter} + * and {@code XMLEventFactory}. * @param eventWriter the {@code XMLEventWriter} to write to * @param eventFactory the {@code XMLEventFactory} to use for creating events */ @@ -81,35 +79,35 @@ class StaxResult extends SAXResult { this.eventWriter = eventWriter; } + /** - * Returns the {@code XMLEventWriter} used by this {@code StaxResult}. If this {@code StaxResult} was - * created with an {@code XMLStreamWriter}, the result will be {@code null}. - * + * Return the {@code XMLEventWriter} used by this {@code StaxResult}. If this {@code StaxResult} + * was created with an {@code XMLStreamWriter}, the result will be {@code null}. * @return the StAX event writer used by this result * @see #StaxResult(javax.xml.stream.XMLEventWriter) */ XMLEventWriter getXMLEventWriter() { - return eventWriter; + return this.eventWriter; } /** - * Returns the {@code XMLStreamWriter} used by this {@code StaxResult}. If this {@code StaxResult} was - * created with an {@code XMLEventConsumer}, the result will be {@code null}. - * + * Return the {@code XMLStreamWriter} used by this {@code StaxResult}. If this {@code StaxResult} + * was created with an {@code XMLEventConsumer}, the result will be {@code null}. * @return the StAX stream writer used by this result * @see #StaxResult(javax.xml.stream.XMLStreamWriter) */ XMLStreamWriter getXMLStreamWriter() { - return streamWriter; + return this.streamWriter; } + /** - * Throws a {@code UnsupportedOperationException}. - * + * Throws an {@code UnsupportedOperationException}. * @throws UnsupportedOperationException always */ @Override public void setHandler(ContentHandler handler) { throw new UnsupportedOperationException("setHandler is not supported"); } + } diff --git a/spring-core/src/main/java/org/springframework/util/xml/StaxSource.java b/spring-core/src/main/java/org/springframework/util/xml/StaxSource.java index af005ecc14..5706a4317e 100644 --- a/spring-core/src/main/java/org/springframework/util/xml/StaxSource.java +++ b/spring-core/src/main/java/org/springframework/util/xml/StaxSource.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,24 +24,24 @@ import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** - * Implementation of the {@code Source} tagging interface for StAX readers. Can be constructed with a - * {@code XMLEventReader} or a {@code XMLStreamReader}. + * Implementation of the {@code Source} tagging interface for StAX readers. Can be constructed with + * an {@code XMLEventReader} or an {@code XMLStreamReader}. * - *

This class is necessary because there is no implementation of {@code Source} for StAX Readers in JAXP 1.3. - * There is a {@code StAXSource} in JAXP 1.4 (JDK 1.6), but this class is kept around for back-ward compatibility - * reasons. + *

This class is necessary because there is no implementation of {@code Source} for StAX Readers + * in JAXP 1.3. There is a {@code StAXSource} in JAXP 1.4 (JDK 1.6), but this class is kept around + * for backwards compatibility reasons. * *

Even though {@code StaxSource} extends from {@code SAXSource}, calling the methods of - * {@code SAXSource} is not supported. In general, the only supported operation on this class is - * to use the {@code XMLReader} obtained via {@link #getXMLReader()} to parse the input source obtained via {@link - * #getInputSource()}. Calling {@link #setXMLReader(XMLReader)} or {@link #setInputSource(InputSource)} will result in - * {@code UnsupportedOperationException}s. + * {@code SAXSource} is not supported. In general, the only supported operation + * on this class is to use the {@code XMLReader} obtained via {@link #getXMLReader()} to parse the + * input source obtained via {@link #getInputSource()}. Calling {@link #setXMLReader(XMLReader)} + * or {@link #setInputSource(InputSource)} will result in {@code UnsupportedOperationException}s. * * @author Arjen Poutsma + * @since 3.0 * @see XMLEventReader * @see XMLStreamReader * @see javax.xml.transform.Transformer - * @since 3.0 */ class StaxSource extends SAXSource { @@ -49,11 +49,11 @@ class StaxSource extends SAXSource { private XMLStreamReader streamReader; + /** - * Constructs a new instance of the {@code StaxSource} with the specified {@code XMLStreamReader}. The - * supplied stream reader must be in {@code XMLStreamConstants.START_DOCUMENT} or + * Construct a new instance of the {@code StaxSource} with the specified {@code XMLStreamReader}. + * The supplied stream reader must be in {@code XMLStreamConstants.START_DOCUMENT} or * {@code XMLStreamConstants.START_ELEMENT} state. - * * @param streamReader the {@code XMLStreamReader} to read from * @throws IllegalStateException if the reader is not at the start of a document or element */ @@ -63,10 +63,9 @@ class StaxSource extends SAXSource { } /** - * Constructs a new instance of the {@code StaxSource} with the specified {@code XMLEventReader}. The - * supplied event reader must be in {@code XMLStreamConstants.START_DOCUMENT} or + * Construct a new instance of the {@code StaxSource} with the specified {@code XMLEventReader}. + * The supplied event reader must be in {@code XMLStreamConstants.START_DOCUMENT} or * {@code XMLStreamConstants.START_ELEMENT} state. - * * @param eventReader the {@code XMLEventReader} to read from * @throws IllegalStateException if the reader is not at the start of a document or element */ @@ -75,31 +74,30 @@ class StaxSource extends SAXSource { this.eventReader = eventReader; } + /** - * Returns the {@code XMLEventReader} used by this {@code StaxSource}. If this {@code StaxSource} was - * created with an {@code XMLStreamReader}, the result will be {@code null}. - * + * Return the {@code XMLEventReader} used by this {@code StaxSource}. If this {@code StaxSource} + * was created with an {@code XMLStreamReader}, the result will be {@code null}. * @return the StAX event reader used by this source * @see StaxSource#StaxSource(javax.xml.stream.XMLEventReader) */ XMLEventReader getXMLEventReader() { - return eventReader; + return this.eventReader; } /** - * Returns the {@code XMLStreamReader} used by this {@code StaxSource}. If this {@code StaxSource} was - * created with an {@code XMLEventReader}, the result will be {@code null}. - * + * Return the {@code XMLStreamReader} used by this {@code StaxSource}. If this {@code StaxSource} + * was created with an {@code XMLEventReader}, the result will be {@code null}. * @return the StAX event reader used by this source * @see StaxSource#StaxSource(javax.xml.stream.XMLEventReader) */ XMLStreamReader getXMLStreamReader() { - return streamReader; + return this.streamReader; } + /** - * Throws a {@code UnsupportedOperationException}. - * + * Throws an {@code UnsupportedOperationException}. * @throws UnsupportedOperationException always */ @Override @@ -108,12 +106,12 @@ class StaxSource extends SAXSource { } /** - * Throws a {@code UnsupportedOperationException}. - * + * Throws an {@code UnsupportedOperationException}. * @throws UnsupportedOperationException always */ @Override public void setXMLReader(XMLReader reader) { throw new UnsupportedOperationException("setXMLReader is not supported"); } + } diff --git a/spring-core/src/main/java/org/springframework/util/xml/StaxUtils.java b/spring-core/src/main/java/org/springframework/util/xml/StaxUtils.java index 576f39ebcf..efafa259d4 100644 --- a/spring-core/src/main/java/org/springframework/util/xml/StaxUtils.java +++ b/spring-core/src/main/java/org/springframework/util/xml/StaxUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -45,14 +45,15 @@ import org.springframework.util.ClassUtils; */ public abstract class StaxUtils { + // JAXP 1.4 is only available on JDK 1.6+ private static boolean jaxp14Available = ClassUtils.isPresent("javax.xml.transform.stax.StAXSource", StaxUtils.class.getClassLoader()); + // Stax Source /** * Create a custom, non-JAXP 1.4 StAX {@link Source} for the given {@link XMLStreamReader}. - * * @param streamReader the StAX stream reader * @return a source wrapping the {@code streamReader} */ @@ -62,9 +63,8 @@ public abstract class StaxUtils { /** * Create a StAX {@link Source} for the given {@link XMLStreamReader}. - * - *

If JAXP 1.4 is available, this method returns a {@link StAXSource}; otherwise it returns a - * custom StAX Source. + *

If JAXP 1.4 is available, this method returns a {@link StAXSource}; + * otherwise it returns a custom StAX Source. * @param streamReader the StAX stream reader * @return a source wrapping the {@code streamReader} * @see #createCustomStaxSource(XMLStreamReader) @@ -80,7 +80,6 @@ public abstract class StaxUtils { /** * Create a custom, non-JAXP 1.4 StAX {@link Source} for the given {@link XMLEventReader}. - * * @param eventReader the StAX event reader * @return a source wrapping the {@code eventReader} */ @@ -90,9 +89,8 @@ public abstract class StaxUtils { /** * Create a StAX {@link Source} for the given {@link XMLEventReader}. - * - *

If JAXP 1.4 is available, this method returns a {@link StAXSource}; otherwise it returns a - * custom StAX Source. + *

If JAXP 1.4 is available, this method returns a {@link StAXSource}; + * otherwise it returns a custom StAX Source. * @param eventReader the StAX event reader * @return a source wrapping the {@code eventReader} * @throws XMLStreamException in case of StAX errors @@ -116,11 +114,11 @@ public abstract class StaxUtils { return (source instanceof StaxSource || (jaxp14Available && Jaxp14StaxHandler.isStaxSource(source))); } + // Stax Result /** * Create a custom, non-JAXP 1.4 StAX {@link Result} for the given {@link XMLStreamWriter}. - * * @param streamWriter the StAX stream writer * @return a source wrapping the {@code streamWriter} */ @@ -130,9 +128,8 @@ public abstract class StaxUtils { /** * Create a StAX {@link Result} for the given {@link XMLStreamWriter}. - * - *

If JAXP 1.4 is available, this method returns a {@link StAXResult}; otherwise it returns a - * custom StAX Result. + *

If JAXP 1.4 is available, this method returns a {@link StAXResult}; + * otherwise it returns a custom StAX Result. * @param streamWriter the StAX stream writer * @return a result wrapping the {@code streamWriter} * @see #createCustomStaxResult(XMLStreamWriter) @@ -148,7 +145,6 @@ public abstract class StaxUtils { /** * Create a custom, non-JAXP 1.4 StAX {@link Result} for the given {@link XMLEventWriter}. - * * @param eventWriter the StAX event writer * @return a source wrapping the {@code eventWriter} */ @@ -158,7 +154,6 @@ public abstract class StaxUtils { /** * Create a StAX {@link Result} for the given {@link XMLEventWriter}. - * *

If JAXP 1.4 is available, this method returns a {@link StAXResult}; otherwise it returns a * custom StAX Result. * @param eventWriter the StAX event writer @@ -177,8 +172,8 @@ public abstract class StaxUtils { /** * Indicate whether the given {@link javax.xml.transform.Result} is a StAX Result. - * @return {@code true} if {@code result} is a custom Stax Result or JAXP - * 1.4 {@link StAXResult}; {@code false} otherwise. + * @return {@code true} if {@code result} is a custom Stax Result or JAXP 1.4 + * {@link StAXResult}; {@code false} otherwise. */ public static boolean isStaxResult(Result result) { return (result instanceof StaxResult || (jaxp14Available && Jaxp14StaxHandler.isStaxResult(result))); @@ -327,6 +322,7 @@ public abstract class StaxUtils { return new XMLEventStreamWriter(eventWriter, eventFactory); } + /** * Inner class to avoid a static JAXP 1.4 dependency. */ @@ -349,11 +345,11 @@ public abstract class StaxUtils { } private static boolean isStaxSource(Source source) { - return source instanceof StAXSource; + return (source instanceof StAXSource); } private static boolean isStaxResult(Result result) { - return result instanceof StAXResult; + return (result instanceof StAXResult); } private static XMLStreamReader getXMLStreamReader(Source source) { From 08e1cbc02b61647ba694cbedc340a4c40e1b1285 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 11 Feb 2013 21:51:29 +0100 Subject: [PATCH 228/311] Jaxb2Marshaller etc --- src/dist/changelog.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 6cbfe51eb7..5cfeae864b 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -13,6 +13,7 @@ Changes in version 3.2.2 (2013-03-07) * "depends-on" attribute on lang namespace element actually respected at runtime now (SPR-8625) * allow for ordering of mixed AspectJ before/after advices (SPR-9438) * added "maximumAutoGrowSize" property to SpelParserConfiguration (SPR-10229) +* fixed regression in SpringValidatorAdapter's retrieval of invalid values (SPR-10243) * support 'unless' expression for cache veto (SPR-8871) * @Async's qualifier works for target class annotations behind a JDK proxy as well (SPR-10274) * @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support (SPR-8067) @@ -23,6 +24,7 @@ Changes in version 3.2.2 (2013-03-07) * added useful query variants without parameters to NamedParameterJdbcTemplate, for convenience in DAOs (SPR-10256) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) +* added "mappedClass" property to Jaxb2Marshaller, introducing support for partial unmarshalling (SPR-10282) * added "entityResolver", "classDescriptorResolver", "doctypes" and further properties to CastorMarshaller (SPR-8470) * deprecated CastorMarshaller's "object" property in favor of "rootObject" (SPR-8470) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) From 6661788748daccfc8d08b4a17a66beb4f01fc7b8 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 11 Feb 2013 18:42:21 -0800 Subject: [PATCH 229/311] Ensure HTTP classes don't close streams Prior to this commit several HTTP classes made use of FileCopyUtils when reading from or writing to streams. This has the unfortunate side effect of closing streams that should really be left open. The problem is particularly noticeable when dealing with a FormHttpMessageConverter that is writing a multi-part response. Relevant HTTP classes have now been refactored to make use of a new StreamUtils class that works in a similar way FileCopyUtils but does not close streams. The NonClosingOutputStream class from SimpleStreamingClientHttpRequest has also been refactored to a StreamUtils method. Issue: SPR-10095 --- .../springframework/util/FileCopyUtils.java | 26 +-- .../org/springframework/util/StreamUtils.java | 183 ++++++++++++++++++ .../util/StreamUtilsTests.java | 129 ++++++++++++ .../BufferingClientHttpRequestWrapper.java | 7 +- .../BufferingClientHttpResponseWrapper.java | 5 +- .../client/InterceptingClientHttpRequest.java | 6 +- .../SimpleStreamingClientHttpRequest.java | 28 +-- .../ByteArrayHttpMessageConverter.java | 17 +- .../converter/FormHttpMessageConverter.java | 9 +- .../ResourceHttpMessageConverter.java | 9 +- .../converter/StringHttpMessageConverter.java | 10 +- .../http/MockHttpOutputMessage.java | 6 +- .../FormHttpMessageConverterTests.java | 5 +- 13 files changed, 360 insertions(+), 80 deletions(-) create mode 100644 spring-core/src/main/java/org/springframework/util/StreamUtils.java create mode 100644 spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java diff --git a/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java b/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java index 5aac309086..2c14da3b51 100644 --- a/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java +++ b/spring-core/src/main/java/org/springframework/util/FileCopyUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,19 +31,19 @@ import java.io.StringWriter; import java.io.Writer; /** - * Simple utility methods for file and stream copying. - * All copy methods use a block size of 4096 bytes, - * and close all affected streams when done. + * Simple utility methods for file and stream copying. All copy methods use a block size + * of 4096 bytes, and close all affected streams when done. A variation of the copy + * methods from this class that leave streams open can be found in {@link StreamUtils}. * - *

Mainly for use within the framework, - * but also useful for application code. + *

Mainly for use within the framework, but also useful for application code. * * @author Juergen Hoeller * @since 06.10.2003 + * @see StreamUtils */ public abstract class FileCopyUtils { - public static final int BUFFER_SIZE = 4096; + public static final int BUFFER_SIZE = StreamUtils.BUFFER_SIZE; //--------------------------------------------------------------------- @@ -106,15 +106,7 @@ public abstract class FileCopyUtils { Assert.notNull(in, "No InputStream specified"); Assert.notNull(out, "No OutputStream specified"); try { - int byteCount = 0; - byte[] buffer = new byte[BUFFER_SIZE]; - int bytesRead = -1; - while ((bytesRead = in.read(buffer)) != -1) { - out.write(buffer, 0, bytesRead); - byteCount += bytesRead; - } - out.flush(); - return byteCount; + return StreamUtils.copy(in, out); } finally { try { @@ -208,7 +200,7 @@ public abstract class FileCopyUtils { /** * Copy the contents of the given String to the given output Writer. - * Closes the write when done. + * Closes the writer when done. * @param in the String to copy from * @param out the Writer to copy to * @throws IOException in case of I/O errors diff --git a/spring-core/src/main/java/org/springframework/util/StreamUtils.java b/spring-core/src/main/java/org/springframework/util/StreamUtils.java new file mode 100644 index 0000000000..8adf07159e --- /dev/null +++ b/spring-core/src/main/java/org/springframework/util/StreamUtils.java @@ -0,0 +1,183 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.util; + +import java.io.ByteArrayOutputStream; +import java.io.FilterInputStream; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.Charset; + + +/** + * Simple utility methods for dealing with streams. The copy methods of this class are + * similar to those defined in {@link FileCopyUtils} except that all affected streams are + * left open when done. All copy methods use a block size of 4096 bytes. + * + *

Mainly for use within the framework, but also useful for application code. + * + * @author Juergen Hoeller + * @author Phillip Webb + * @since 3.2 + * @see FileCopyUtils + */ +public abstract class StreamUtils { + + public static final int BUFFER_SIZE = 4096; + + + /** + * Copy the contents of the given InputStream into a new byte array. + * Leaves the stream open when done. + * @param in the stream to copy from + * @return the new byte array that has been copied to + * @throws IOException in case of I/O errors + */ + public static byte[] copyToByteArray(InputStream in) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE); + copy(in, out); + return out.toByteArray(); + } + + /** + * Copy the contents of the given InputStream into a String. + * Leaves the stream open when done. + * @param in the InputStream to copy from + * @return the String that has been copied to + * @throws IOException in case of I/O errors + */ + public static String copyToString(InputStream in, Charset charset) throws IOException { + Assert.notNull(in, "No InputStream specified"); + StringBuilder out = new StringBuilder(); + InputStreamReader reader = new InputStreamReader(in, charset); + char[] buffer = new char[BUFFER_SIZE]; + int bytesRead = -1; + while ((bytesRead = reader.read(buffer)) != -1) { + out.append(buffer, 0, bytesRead); + } + return out.toString(); + } + + /** + * Copy the contents of the given byte array to the given OutputStream. + * Leaves the stream open when done. + * @param in the byte array to copy from + * @param out the OutputStream to copy to + * @throws IOException in case of I/O errors + */ + public static void copy(byte[] in, OutputStream out) throws IOException { + Assert.notNull(in, "No input byte array specified"); + Assert.notNull(out, "No OutputStream specified"); + out.write(in); + } + + /** + * Copy the contents of the given String to the given output OutputStream. + * Leaves the stream open when done. + * @param in the String to copy from + * @param charset the Charset + * @param out the OutputStream to copy to + * @throws IOException in case of I/O errors + */ + public static void copy(String in, Charset charset, OutputStream out) throws IOException { + Assert.notNull(in, "No input String specified"); + Assert.notNull(charset, "No charset specified"); + Assert.notNull(out, "No OutputStream specified"); + Writer writer = new OutputStreamWriter(out, charset); + writer.write(in); + writer.flush(); + } + + /** + * Copy the contents of the given InputStream to the given OutputStream. + * Leaves both streams open when done. + * @param in the InputStream to copy from + * @param out the OutputStream to copy to + * @return the number of bytes copied + * @throws IOException in case of I/O errors + */ + public static int copy(InputStream in, OutputStream out) throws IOException { + Assert.notNull(in, "No InputStream specified"); + Assert.notNull(out, "No OutputStream specified"); + int byteCount = 0; + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead = -1; + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + byteCount += bytesRead; + } + out.flush(); + return byteCount; + } + + /** + * Returns a variant of the given {@link InputStream} where calling + * {@link InputStream#close() close()} has no effect. + * @param in the InputStream to decorate + * @return a version of the InputStream that ignores calls to close + */ + public static InputStream nonClosing(InputStream in) { + Assert.notNull(in, "No InputStream specified"); + return new NonClosingInputStream(in); + } + + /** + * Returns a variant of the given {@link OutputStream} where calling + * {@link OutputStream#close() close()} has no effect. + * @param in the OutputStream to decorate + * @return a version of the OutputStream that ignores calls to close + */ + public static OutputStream nonClosing(OutputStream out) { + Assert.notNull(out, "No OutputStream specified"); + return new NonClosingOutputStream(out); + } + + + private static class NonClosingInputStream extends FilterInputStream { + + public NonClosingInputStream(InputStream in) { + super(in); + } + + @Override + public void close() throws IOException { + } + } + + + private static class NonClosingOutputStream extends FilterOutputStream { + + public NonClosingOutputStream(OutputStream out) { + super(out); + } + + @Override + public void write(byte[] b, int off, int let) throws IOException { + // It is critical that we override this method for performance + out.write(b, off, let); + } + + @Override + public void close() throws IOException { + } + } +} diff --git a/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java b/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java new file mode 100644 index 0000000000..fe10d23596 --- /dev/null +++ b/spring-core/src/test/java/org/springframework/util/StreamUtilsTests.java @@ -0,0 +1,129 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.util; + +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.Charset; +import java.util.Random; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InOrder; + +/** + * Tests for {@link StreamUtils}. + * + * @author Phillip Webb + */ +public class StreamUtilsTests { + + private byte[] bytes = new byte[StreamUtils.BUFFER_SIZE + 10]; + + private String string = ""; + + @Before + public void setup() { + new Random().nextBytes(bytes); + while (string.length() < StreamUtils.BUFFER_SIZE + 10) { + string += UUID.randomUUID().toString(); + } + } + + @Test + public void copyToByteArray() throws Exception { + InputStream inputStream = spy(new ByteArrayInputStream(bytes)); + byte[] actual = StreamUtils.copyToByteArray(inputStream); + assertThat(actual, equalTo(bytes)); + verify(inputStream, never()).close(); + } + + @Test + public void copyToString() throws Exception { + Charset charset = Charset.defaultCharset(); + InputStream inputStream = spy(new ByteArrayInputStream(string.getBytes(charset))); + String actual = StreamUtils.copyToString(inputStream, charset); + assertThat(actual, equalTo(string)); + verify(inputStream, never()).close(); + } + + @Test + public void copyBytes() throws Exception { + ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); + StreamUtils.copy(bytes, out); + assertThat(out.toByteArray(), equalTo(bytes)); + verify(out, never()).close(); + } + + @Test + public void copyString() throws Exception { + Charset charset = Charset.defaultCharset(); + ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); + StreamUtils.copy(string, charset, out); + assertThat(out.toByteArray(), equalTo(string.getBytes(charset))); + verify(out, never()).close(); + } + + @Test + public void copyStream() throws Exception { + ByteArrayOutputStream out = spy(new ByteArrayOutputStream()); + StreamUtils.copy(new ByteArrayInputStream(bytes), out); + assertThat(out.toByteArray(), equalTo(bytes)); + verify(out, never()).close(); + } + + @Test + public void nonClosingInputStream() throws Exception { + InputStream source = mock(InputStream.class); + InputStream nonClosing = StreamUtils.nonClosing(source); + nonClosing.read(); + nonClosing.read(bytes); + nonClosing.read(bytes, 1, 2); + nonClosing.close(); + InOrder ordered = inOrder(source); + ordered.verify(source).read(); + ordered.verify(source).read(bytes, 0, bytes.length); + ordered.verify(source).read(bytes, 1, 2); + ordered.verify(source, never()).close(); + } + + @Test + public void nonClosingOutputStream() throws Exception { + OutputStream source = mock(OutputStream.class); + OutputStream nonClosing = StreamUtils.nonClosing(source); + nonClosing.write(1); + nonClosing.write(bytes); + nonClosing.write(bytes, 1, 2); + nonClosing.close(); + InOrder ordered = inOrder(source); + ordered.verify(source).write(1); + ordered.verify(source).write(bytes, 0, bytes.length); + ordered.verify(source).write(bytes, 1, 2); + ordered.verify(source, never()).close(); + } +} diff --git a/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java index 813f98cfad..bb87844420 100644 --- a/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java +++ b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpRequestWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import java.net.URI; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.util.Assert; -import org.springframework.util.FileCopyUtils; +import org.springframework.util.StreamUtils; /** * Simple implementation of {@link ClientHttpRequest} that wraps another request. @@ -53,8 +53,7 @@ final class BufferingClientHttpRequestWrapper extends AbstractBufferingClientHtt @Override protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException { this.request.getHeaders().putAll(headers); - OutputStream body = this.request.getBody(); - FileCopyUtils.copy(bufferedOutput, body); + StreamUtils.copy(bufferedOutput, this.request.getBody()); ClientHttpResponse response = this.request.execute(); return new BufferingClientHttpResponseWrapper(response); } diff --git a/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java index f280790fec..f075b202bd 100644 --- a/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java +++ b/spring-web/src/main/java/org/springframework/http/client/BufferingClientHttpResponseWrapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +23,7 @@ import java.io.InputStream; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.util.FileCopyUtils; +import org.springframework.util.StreamUtils; /** * Simple implementation of {@link ClientHttpResponse} that reads the request's body into memory, @@ -61,7 +62,7 @@ final class BufferingClientHttpResponseWrapper implements ClientHttpResponse { public InputStream getBody() throws IOException { if (this.body == null) { - this.body = FileCopyUtils.copyToByteArray(this.response.getBody()); + this.body = StreamUtils.copyToByteArray(this.response.getBody()); } return new ByteArrayInputStream(this.body); } diff --git a/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java index 9d39760479..a422614fe9 100644 --- a/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import java.util.List; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; -import org.springframework.util.FileCopyUtils; +import org.springframework.util.StreamUtils; /** * Wrapper for a {@link ClientHttpRequest} that has support for {@link ClientHttpRequestInterceptor}s. @@ -86,7 +86,7 @@ class InterceptingClientHttpRequest extends AbstractBufferingClientHttpRequest { delegate.getHeaders().putAll(request.getHeaders()); if (body.length > 0) { - FileCopyUtils.copy(body, delegate.getBody()); + StreamUtils.copy(body, delegate.getBody()); } return delegate.execute(); } diff --git a/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java index a5e831102c..2382365570 100644 --- a/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,7 +16,6 @@ package org.springframework.http.client; -import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; @@ -27,6 +26,7 @@ import java.util.Map; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; +import org.springframework.util.StreamUtils; /** * {@link ClientHttpRequest} implementation that uses standard J2SE facilities to execute streaming requests. @@ -77,7 +77,7 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { this.connection.connect(); this.body = this.connection.getOutputStream(); } - return new NonClosingOutputStream(this.body); + return StreamUtils.nonClosing(this.body); } private void writeHeaders(HttpHeaders headers) { @@ -106,26 +106,4 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { return new SimpleClientHttpResponse(this.connection); } - - private static class NonClosingOutputStream extends FilterOutputStream { - - private NonClosingOutputStream(OutputStream out) { - super(out); - } - - @Override - public void write(byte[] b) throws IOException { - super.write(b); - } - - @Override - public void write(byte[] b, int off, int let) throws IOException { - out.write(b, off, let); - } - - @Override - public void close() throws IOException { - } - } - } diff --git a/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java index f1ddc0080f..d1b25f7c35 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import java.io.IOException; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; -import org.springframework.util.FileCopyUtils; +import org.springframework.util.StreamUtils; /** * Implementation of {@link HttpMessageConverter} that can read and write byte arrays. @@ -49,14 +49,9 @@ public class ByteArrayHttpMessageConverter extends AbstractHttpMessageConverter< @Override public byte[] readInternal(Class clazz, HttpInputMessage inputMessage) throws IOException { long contentLength = inputMessage.getHeaders().getContentLength(); - if (contentLength >= 0) { - ByteArrayOutputStream bos = new ByteArrayOutputStream((int) contentLength); - FileCopyUtils.copy(inputMessage.getBody(), bos); - return bos.toByteArray(); - } - else { - return FileCopyUtils.copyToByteArray(inputMessage.getBody()); - } + ByteArrayOutputStream bos = new ByteArrayOutputStream(contentLength >= 0 ? (int) contentLength : StreamUtils.BUFFER_SIZE); + StreamUtils.copy(inputMessage.getBody(), bos); + return bos.toByteArray(); } @Override @@ -66,7 +61,7 @@ public class ByteArrayHttpMessageConverter extends AbstractHttpMessageConverter< @Override protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException { - FileCopyUtils.copy(bytes, outputMessage.getBody()); + StreamUtils.copy(bytes, outputMessage.getBody()); } } diff --git a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java index f66a38bf19..516eb92ab2 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.http.converter; import java.io.IOException; -import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; @@ -37,9 +36,9 @@ import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.util.Assert; -import org.springframework.util.FileCopyUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; +import org.springframework.util.StreamUtils; import org.springframework.util.StringUtils; /** @@ -170,7 +169,7 @@ public class FormHttpMessageConverter implements HttpMessageConverter parts, HttpOutputMessage outputMessage) diff --git a/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java b/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java index 9991fbcc80..69f22a92e1 100644 --- a/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java +++ b/spring-web/src/main/java/org/springframework/http/converter/ResourceHttpMessageConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.http.converter; import java.io.IOException; import java.io.InputStream; + import javax.activation.FileTypeMap; import javax.activation.MimetypesFileTypeMap; @@ -28,7 +29,7 @@ import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.util.ClassUtils; -import org.springframework.util.FileCopyUtils; +import org.springframework.util.StreamUtils; import org.springframework.util.StringUtils; /** @@ -61,7 +62,7 @@ public class ResourceHttpMessageConverter extends AbstractHttpMessageConverter clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { - byte[] body = FileCopyUtils.copyToByteArray(inputMessage.getBody()); + byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody()); return new ByteArrayResource(body); } @@ -84,7 +85,7 @@ public class ResourceHttpMessageConverter extends AbstractHttpMessageConverter clazz, HttpInputMessage inputMessage) throws IOException { Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType()); - return FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset)); + return StreamUtils.copyToString(inputMessage.getBody(), charset); } @Override @@ -105,7 +103,7 @@ public class StringHttpMessageConverter extends AbstractHttpMessageConverter Date: Mon, 11 Feb 2013 20:56:59 -0800 Subject: [PATCH 230/311] Fix @RequestMapping regex reference doc example Issue: SPR-10244 --- src/reference/docbook/mvc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index c8aebb4f8a..021249cf57 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -1062,7 +1062,7 @@ public class RelativePathUriTemplateController { example: -@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}") +@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}.{extension:\\.[a-z]}") public void handle(@PathVariable String version, @PathVariable String extension) { // ... } From 6f0b4395e5d087096e25465a8000b873f2636b7c Mon Sep 17 00:00:00 2001 From: Carson McDonald Date: Tue, 12 Feb 2013 09:04:28 -0500 Subject: [PATCH 231/311] Fix a few typos Minor changes to fix typos. Small adjustment to add a couple commas. --- .../PropertiesBeanDefinitionReader.java | 4 ++-- .../ParameterMethodNameResolver.java | 18 +++++++++--------- .../view/ResourceBundleViewResolver.java | 4 ++-- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java index 7b7822f0df..d51dc55fa7 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -165,7 +165,7 @@ public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader * class can still override this. *

Strictly speaking, the rule that a default parent setting does * not apply to a bean definition that carries a class is there for - * backwards compatiblity reasons. It still matches the typical use case. + * backwards compatibility reasons. It still matches the typical use case. */ public void setDefaultParentBean(String defaultParentBean) { this.defaultParentBean = defaultParentBean; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java index bd9405b65b..1a2e175fb1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/multiaction/ParameterMethodNameResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,14 +50,14 @@ import org.springframework.web.util.WebUtils; * *

Note that the second strategy also supports the use of submit buttons of * type 'image'. That is, an image submit button named 'reset' will normally be - * submitted by the browser as two request paramters called 'reset.x', and - * 'reset.y'. When checking for the existence of a paramter from the + * submitted by the browser as two request parameters called 'reset.x', and + * 'reset.y'. When checking for the existence of a parameter from the * {@code methodParamNames} list, to indicate that a specific method should - * be called, the code will look for request parameter in the "reset" form - * (exactly as spcified in the list), and in the "reset.x" form ('.x' appended to - * the name in the list). In this way it can handle both normal and image submit - * buttons. The actual method name resolved if there is a match will always be - * the bare form without the ".x". + * be called, the code will look for a request parameter in the "reset" form + * (exactly as specified in the list), and in the "reset.x" form ('.x' appended + * to the name in the list). In this way it can handle both normal and image + * submit buttons. The actual method name resolved, if there is a match, will + * always be the bare form without the ".x". * *

Note: If both strategies are configured, i.e. both "paramName" * and "methodParamNames" are specified, then both will be checked for any given @@ -69,7 +69,7 @@ import org.springframework.web.util.WebUtils; * *

For both resolution strategies, the method name is of course coming from * some sort of view code, (such as a JSP page). While this may be acceptable, - * it is sometimes desireable to treat this only as a 'logical' method name, + * it is sometimes desirable to treat this only as a 'logical' method name, * with a further mapping to a 'real' method name. As such, an optional * 'logical' mapping may be specified for this purpose. * diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java index 2726e0537c..77c3a67e03 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/ResourceBundleViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -160,7 +160,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver *

View definitions that define their own parent or carry their own * class can still override this. Strictly speaking, the rule that a * default parent setting does not apply to a bean definition that - * carries a class is there for backwards compatiblity reasons. + * carries a class is there for backwards compatibility reasons. * It still matches the typical use case. */ public void setDefaultParentView(String defaultParentView) { From dbe3c234d66f7023dd50998c323e04c2c376871c Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 12 Feb 2013 09:37:28 -0800 Subject: [PATCH 232/311] Polish --- .../format/datetime/DateFormatterRegistrar.java | 6 +++--- .../joda/JodaTimeFormatterRegistrar.java | 16 ++++++++-------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java index aedf118437..5e45fedee3 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java @@ -45,8 +45,8 @@ public class DateFormatterRegistrar implements FormatterRegistrar { public void registerFormatters(FormatterRegistry registry) { addDateConverters(registry); - registry.addFormatter(dateFormatter); - registry.addFormatterForFieldType(Calendar.class, dateFormatter); + registry.addFormatter(this.dateFormatter); + registry.addFormatterForFieldType(Calendar.class, this.dateFormatter); registry.addFormatterForFieldAnnotation(new DateTimeFormatAnnotationFormatterFactory()); } @@ -117,7 +117,7 @@ public class DateFormatterRegistrar implements FormatterRegistrar { private DateToCalendarConverter dateToCalendarConverter = new DateToCalendarConverter(); public Calendar convert(Long source) { - return dateToCalendarConverter.convert(new Date(source)); + return this.dateToCalendarConverter.convert(new Date(source)); } } } diff --git a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java index 51d9f9684b..2035b68b85 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java @@ -75,7 +75,7 @@ public class JodaTimeFormatterRegistrar implements FormatterRegistrar { * Default is {@link DateTimeFormat#shortDate()}. */ public void setDateStyle(String dateStyle) { - factories.get(Type.DATE).setStyle(dateStyle+"-"); + this.factories.get(Type.DATE).setStyle(dateStyle+"-"); } /** @@ -83,7 +83,7 @@ public class JodaTimeFormatterRegistrar implements FormatterRegistrar { * Default is {@link DateTimeFormat#shortTime()}. */ public void setTimeStyle(String timeStyle) { - factories.get(Type.TIME).setStyle("-"+timeStyle); + this.factories.get(Type.TIME).setStyle("-"+timeStyle); } /** @@ -92,7 +92,7 @@ public class JodaTimeFormatterRegistrar implements FormatterRegistrar { * Default is {@link DateTimeFormat#shortDateTime()}. */ public void setDateTimeStyle(String dateTimeStyle) { - factories.get(Type.DATE_TIME).setStyle(dateTimeStyle); + this.factories.get(Type.DATE_TIME).setStyle(dateTimeStyle); } /** @@ -101,9 +101,9 @@ public class JodaTimeFormatterRegistrar implements FormatterRegistrar { * If set to true, the dateStyle, timeStyle, and dateTimeStyle properties are ignored. */ public void setUseIsoFormat(boolean useIsoFormat) { - factories.get(Type.DATE).setIso(useIsoFormat ? ISO.DATE : null); - factories.get(Type.TIME).setIso(useIsoFormat ? ISO.TIME : null); - factories.get(Type.DATE_TIME).setIso(useIsoFormat ? ISO.DATE_TIME : null); + this.factories.get(Type.DATE).setIso(useIsoFormat ? ISO.DATE : null); + this.factories.get(Type.TIME).setIso(useIsoFormat ? ISO.TIME : null); + this.factories.get(Type.DATE_TIME).setIso(useIsoFormat ? ISO.DATE_TIME : null); } /** @@ -181,12 +181,12 @@ public class JodaTimeFormatterRegistrar implements FormatterRegistrar { } private DateTimeFormatter getFormatter(Type type) { - DateTimeFormatter formatter = formatters.get(type); + DateTimeFormatter formatter = this.formatters.get(type); if(formatter != null) { return formatter; } DateTimeFormatter fallbackFormatter = getFallbackFormatter(type); - return factories.get(type).createDateTimeFormatter(fallbackFormatter ); + return this.factories.get(type).createDateTimeFormatter(fallbackFormatter ); } private DateTimeFormatter getFallbackFormatter(Type type) { From 66ae626f91e0b2bbfcf9b9059cb06b07883d9b0b Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 12 Feb 2013 11:02:30 -0800 Subject: [PATCH 233/311] Only register Date converters with global format Change JodaTimeFormatterRegistrar and DateFormatterRegistrar to only register converters for the Date and Calendar types when a global format has been defined. This means that the ObjectToObject converter will handle String->Date conversion using the deprecated Date(String) constructor (as was the case with Spring 3.1). Issue: SPR-10105 --- .../datetime/DateFormatterRegistrar.java | 16 ++++--- .../joda/JodaTimeFormatterRegistrar.java | 11 ++++- .../format/datetime/DateFormattingTests.java | 47 +++++++++++++++++-- .../joda/JodaTimeFormattingTests.java | 37 +++++++++++++-- 4 files changed, 97 insertions(+), 14 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java index 5e45fedee3..b74b53262b 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/DateFormatterRegistrar.java @@ -40,20 +40,24 @@ import org.springframework.util.Assert; public class DateFormatterRegistrar implements FormatterRegistrar { - private DateFormatter dateFormatter = new DateFormatter(); + private DateFormatter dateFormatter; public void registerFormatters(FormatterRegistry registry) { addDateConverters(registry); - registry.addFormatter(this.dateFormatter); - registry.addFormatterForFieldType(Calendar.class, this.dateFormatter); registry.addFormatterForFieldAnnotation(new DateTimeFormatAnnotationFormatterFactory()); + + // In order to retain back compatibility we only register Date/Calendar + // types when a user defined formatter is specified (see SPR-10105) + if(this.dateFormatter != null) { + registry.addFormatter(this.dateFormatter); + registry.addFormatterForFieldType(Calendar.class, this.dateFormatter); + } } /** - * Set the date formatter to register. If not specified the default {@link DateFormatter} - * will be used. This method can be used if additional formatter configuration is - * required. + * Set the date formatter to register. If not specified no formatter is registered. + * This method can be used if global formatter configuration is required. * @param dateFormatter the date formatter */ public void setFormatter(DateFormatter dateFormatter) { diff --git a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java index 2035b68b85..7ad1a4e62e 100644 --- a/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java +++ b/spring-context/src/main/java/org/springframework/format/datetime/joda/JodaTimeFormatterRegistrar.java @@ -174,7 +174,16 @@ public class JodaTimeFormatterRegistrar implements FormatterRegistrar { addFormatterForFields(registry, new ReadableInstantPrinter(dateTimeFormatter), new DateTimeParser(dateTimeFormatter), - ReadableInstant.class, Date.class, Calendar.class); + ReadableInstant.class); + + // In order to retain back compatibility we only register Date/Calendar + // types when a user defined formatter is specified (see SPR-10105) + if(this.formatters.containsKey(Type.DATE_TIME)) { + addFormatterForFields(registry, + new ReadableInstantPrinter(dateTimeFormatter), + new DateTimeParser(dateTimeFormatter), + Date.class, Calendar.class); + } registry.addFormatterForFieldAnnotation( new JodaDateTimeFormatAnnotationFormatterFactory()); diff --git a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java index 5698ed0651..2803f0dc9f 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/DateFormattingTests.java @@ -16,7 +16,10 @@ package org.springframework.format.datetime; +import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.Calendar; @@ -50,9 +53,12 @@ public class DateFormattingTests { @Before public void setUp() { - DefaultConversionService.addDefaultConverters(conversionService); - DateFormatterRegistrar registrar = new DateFormatterRegistrar(); + setUp(registrar); + } + + private void setUp(DateFormatterRegistrar registrar) { + DefaultConversionService.addDefaultConverters(conversionService); registrar.registerFormatters(conversionService); SimpleDateBean bean = new SimpleDateBean(); @@ -187,13 +193,48 @@ public class DateFormattingTests { } @Test - public void dateToString() throws Exception { + public void dateToStringWithoutGlobalFormat() throws Exception { + Date date = new Date(); + Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); + String expected = date.toString(); + assertEquals(expected, actual); + } + + @Test + public void dateToStringWithGlobalFormat() throws Exception { + DateFormatterRegistrar registrar = new DateFormatterRegistrar(); + registrar.setFormatter(new DateFormatter()); + setUp(registrar); Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = new DateFormatter().print(date, Locale.US); assertEquals(expected, actual); } + @Test + @SuppressWarnings("deprecation") + public void stringToDateWithoutGlobalFormat() throws Exception { + // SPR-10105 + String string = "Sat, 12 Aug 1995 13:30:00 GM"; + Date date = this.conversionService.convert(string, Date.class); + assertThat(date, equalTo(new Date(string))); + } + + @Test + public void stringToDateWithGlobalFormat() throws Exception { + // SPR-10105 + DateFormatterRegistrar registrar = new DateFormatterRegistrar(); + DateFormatter dateFormatter = new DateFormatter(); + dateFormatter.setIso(ISO.DATE_TIME); + registrar.setFormatter(dateFormatter); + setUp(registrar); + // This is a format that cannot be parsed by new Date(String) + String string = "2009-06-01T14:23:05.003+0000"; + Date date = this.conversionService.convert(string, Date.class); + assertNotNull(date); + } + + @SuppressWarnings("unused") private static class SimpleDateBean { diff --git a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java index 237df0509f..c2aaf8d36a 100644 --- a/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java +++ b/spring-context/src/test/java/org/springframework/format/datetime/joda/JodaTimeFormattingTests.java @@ -16,6 +16,11 @@ package org.springframework.format.datetime.joda; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + import java.util.ArrayList; import java.util.Calendar; import java.util.Date; @@ -32,7 +37,6 @@ import org.joda.time.MutableDateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; - import org.springframework.beans.MutablePropertyValues; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.core.convert.TypeDescriptor; @@ -42,8 +46,6 @@ import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.support.FormattingConversionService; import org.springframework.validation.DataBinder; -import static org.junit.Assert.*; - /** * @author Keith Donald * @author Juergen Hoeller @@ -459,13 +461,40 @@ public class JodaTimeFormattingTests { } @Test - public void dateToString() throws Exception { + public void dateToStringWithFormat() throws Exception { + JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar(); + registrar.setDateTimeFormatter(org.joda.time.format.DateTimeFormat.shortDateTime()); + setUp(registrar); Date date = new Date(); Object actual = this.conversionService.convert(date, TypeDescriptor.valueOf(Date.class), TypeDescriptor.valueOf(String.class)); String expected = JodaTimeContextHolder.getFormatter(org.joda.time.format.DateTimeFormat.shortDateTime(), Locale.US).print(new DateTime(date)); assertEquals(expected, actual); } + @Test + @SuppressWarnings("deprecation") + public void stringToDateWithoutGlobalFormat() throws Exception { + // SPR-10105 + String string = "Sat, 12 Aug 1995 13:30:00 GM"; + Date date = this.conversionService.convert(string, Date.class); + assertThat(date, equalTo(new Date(string))); + } + + @Test + public void stringToDateWithGlobalFormat() throws Exception { + // SPR-10105 + JodaTimeFormatterRegistrar registrar = new JodaTimeFormatterRegistrar(); + DateTimeFormatterFactory factory = new DateTimeFormatterFactory(); + factory.setIso(ISO.DATE_TIME); + registrar.setDateTimeFormatter(factory.createDateTimeFormatter()); + setUp(registrar); + // This is a format that cannot be parsed by new Date(String) + String string = "2009-10-31T07:00:00.000-05:00"; + Date date = this.conversionService.convert(string, Date.class); + assertNotNull(date); + } + + @SuppressWarnings("unused") private static class JodaTimeBean { From e551f0408d83ca55a5e3d431ad40976306590606 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 12 Feb 2013 15:32:46 -0800 Subject: [PATCH 234/311] Protect against NPE in Tiles 3 Views Change the org.apache.tiles.request.servlet.ServletRequest created in TileView.checkResource to include the HttpServletRequest. This is required when using a TilesConfigurer with useMutableTilesContainer set to true. Without a HttpServletRequest the getRequestScope() method will always return null causing exceptions in the CachingTilesContainer class. Unfortunately the checkResource method does not provide access to the HttpServletRequest so it must be obtained via the RequestContextHolder thread-local. Issue: SPR-10223 --- .../web/servlet/view/tiles3/TilesView.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesView.java b/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesView.java index df8cd2d453..67dec59124 100644 --- a/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesView.java +++ b/spring-webmvc-tiles3/src/main/java/org/springframework/web/servlet/view/tiles3/TilesView.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,9 @@ import org.apache.tiles.request.Request; import org.apache.tiles.request.render.Renderer; import org.apache.tiles.request.servlet.ServletRequest; import org.apache.tiles.request.servlet.ServletUtil; +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.servlet.support.JstlUtils; import org.springframework.web.servlet.support.RequestContext; import org.springframework.web.servlet.support.RequestContextUtils; @@ -95,7 +98,12 @@ public class TilesView extends AbstractUrlBasedView { @Override public boolean checkResource(final Locale locale) throws Exception { - Request request = new ServletRequest(this.applicationContext, null, null) { + HttpServletRequest servletRequest = null; + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if(requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { + servletRequest = ((ServletRequestAttributes)requestAttributes).getRequest(); + } + Request request = new ServletRequest(this.applicationContext, servletRequest, null) { @Override public Locale getRequestLocale() { return locale; From 39c6341cea50f0b5e2c88b72b292240eae2c581f Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 12 Feb 2013 22:43:40 -0800 Subject: [PATCH 235/311] Fix type in "what's new in 3.2" section Issue: SPR-10283 --- src/reference/docbook/new-in-3.2.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/new-in-3.2.xml b/src/reference/docbook/new-in-3.2.xml index 4ffd3cf6cd..8d403c6ead 100644 --- a/src/reference/docbook/new-in-3.2.xml +++ b/src/reference/docbook/new-in-3.2.xml @@ -120,7 +120,7 @@ @ExceptionHandler method that handles standard Spring MVC exceptions and returns a ResponseEntity that allowing customizing and - writing the response with HTTP message converters. This servers as an + writing the response with HTTP message converters. This serves as an alternative to the DefaultHandlerExceptionResolver, which does the same but returns a ModelAndView instead. From 5334ac59f684f66dfd1d526934ebdf88edaef16d Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 13 Feb 2013 17:43:22 +0100 Subject: [PATCH 236/311] "packagesToScan" feature for Hibernate 3 and Hibernate 4 detects annotated packages as well Issue: SPR-7748 Issue: SPR-10288 --- .../orm/hibernate4/LocalSessionFactoryBuilder.java | 13 +++++++++---- .../annotation/AnnotationSessionFactoryBean.java | 13 +++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.java index e125abf2b7..b0aac2d2bb 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/LocalSessionFactoryBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,6 +68,8 @@ public class LocalSessionFactoryBuilder extends Configuration { private static final String RESOURCE_PATTERN = "/**/*.class"; + private static final String PACKAGE_INFO_SUFFIX = ".package-info"; + private static final TypeFilter[] ENTITY_TYPE_FILTERS = new TypeFilter[] { new AnnotationTypeFilter(Entity.class, false), new AnnotationTypeFilter(Embeddable.class, false), @@ -194,8 +196,11 @@ public class LocalSessionFactoryBuilder extends Configuration { if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); - if (matchesFilter(reader, readerFactory)) { - addAnnotatedClasses(this.resourcePatternResolver.getClassLoader().loadClass(className)); + if (matchesEntityTypeFilter(reader, readerFactory)) { + addAnnotatedClass(this.resourcePatternResolver.getClassLoader().loadClass(className)); + } + else if (className.endsWith(PACKAGE_INFO_SUFFIX)) { + addPackage(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length())); } } } @@ -214,7 +219,7 @@ public class LocalSessionFactoryBuilder extends Configuration { * Check whether any of the configured entity type filters matches * the current class descriptor contained in the metadata reader. */ - private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { + private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { for (TypeFilter filter : ENTITY_TYPE_FILTERS) { if (filter.match(reader, readerFactory)) { return true; diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.java index d944ef497d..72f5ee42ea 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/annotation/AnnotationSessionFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -79,6 +79,8 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem private static final String RESOURCE_PATTERN = "/**/*.class"; + private static final String PACKAGE_INFO_SUFFIX = ".package-info"; + private Class[] annotatedClasses; @@ -101,7 +103,7 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem @Override - public void setConfigurationClass(Class configurationClass) { + public void setConfigurationClass(Class configurationClass) { if (configurationClass == null || !AnnotationConfiguration.class.isAssignableFrom(configurationClass)) { throw new IllegalArgumentException( "AnnotationSessionFactoryBean only supports AnnotationConfiguration or subclasses"); @@ -191,9 +193,12 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); - if (matchesFilter(reader, readerFactory)) { + if (matchesEntityTypeFilter(reader, readerFactory)) { config.addAnnotatedClass(this.resourcePatternResolver.getClassLoader().loadClass(className)); } + else if (className.endsWith(PACKAGE_INFO_SUFFIX)) { + config.addPackage(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length())); + } } } } @@ -211,7 +216,7 @@ public class AnnotationSessionFactoryBean extends LocalSessionFactoryBean implem * Check whether any of the configured entity type filters matches * the current class descriptor contained in the metadata reader. */ - private boolean matchesFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { + private boolean matchesEntityTypeFilter(MetadataReader reader, MetadataReaderFactory readerFactory) throws IOException { if (this.entityTypeFilters != null) { for (TypeFilter filter : this.entityTypeFilters) { if (filter.match(reader, readerFactory)) { From 24ed325c0cc8fb0758a166608b7b6ff834e40fa9 Mon Sep 17 00:00:00 2001 From: Arjan van Bentem Date: Wed, 13 Feb 2013 11:40:40 -0800 Subject: [PATCH 237/311] Add HttpPutFormContentFilter note to documentation Update reference guide to include a note about the use of HttpPutFormContentFilter in combination with @RequestBody MultiValueMap and HttpEntity. Issue: SPR-8415 --- src/reference/docbook/mvc.xml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index 021249cf57..7fbd023ac8 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -2157,6 +2157,14 @@ public class EditPetForm { available through the ServletRequest.getParameter*() family of methods. + + + As HttpPutFormContentFilter consumes the body of the + request, it should not be configured for PUT or PATCH URLs that rely on other + converters for application/x-www-form-urlencoded. This includes + @RequestBody MultiValueMap<String, String> and + HttpEntity<MultiValueMap<String, String>>. +

From 92ad66bf10b570dde25af44d8ff3f958dfec2a9d Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 12 Feb 2013 20:36:12 -0800 Subject: [PATCH 238/311] Add setOutputStreaming option for HTTP factory Add setOutputStreaming on SimpleClientHttpRequestFactory to allow the disabling of 'output streaming' mode on the underlying connection so that authentication and redirection can be handled automatically. Issue: SPR-9617 --- .../SimpleBufferingClientHttpRequest.java | 9 ++++-- .../SimpleClientHttpRequestFactory.java | 24 +++++++++++++-- .../SimpleStreamingClientHttpRequest.java | 20 ++++++++----- ...BufferedSimpleHttpRequestFactoryTests.java | 29 +++++++++++++++++++ ...treamingSimpleHttpRequestFactoryTests.java | 29 +++++++++++++++++++ 5 files changed, 98 insertions(+), 13 deletions(-) create mode 100644 spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java create mode 100644 spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingStreamingSimpleHttpRequestFactoryTests.java diff --git a/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java index 989d9e4d28..c2a7864296 100644 --- a/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/SimpleBufferingClientHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -39,9 +39,12 @@ final class SimpleBufferingClientHttpRequest extends AbstractBufferingClientHttp private final HttpURLConnection connection; + private final boolean outputStreaming; - SimpleBufferingClientHttpRequest(HttpURLConnection connection) { + + SimpleBufferingClientHttpRequest(HttpURLConnection connection, boolean outputStreaming) { this.connection = connection; + this.outputStreaming = outputStreaming; } @@ -67,7 +70,7 @@ final class SimpleBufferingClientHttpRequest extends AbstractBufferingClientHttp } } - if (this.connection.getDoOutput()) { + if (this.connection.getDoOutput() && this.outputStreaming) { this.connection.setFixedLengthStreamingMode(bufferedOutput.length); } this.connection.connect(); diff --git a/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java b/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java index 22d17b50f0..3aa31d9b83 100644 --- a/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java +++ b/spring-web/src/main/java/org/springframework/http/client/SimpleClientHttpRequestFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,6 +50,8 @@ public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory private int readTimeout = -1; + private boolean outputStreaming = true; + /** * Set the {@link Proxy} to use for this request factory. @@ -104,15 +106,31 @@ public class SimpleClientHttpRequestFactory implements ClientHttpRequestFactory this.readTimeout = readTimeout; } + /** + * Set if the underlying URLConnection can be set to 'output streaming' mode. When + * output streaming is enabled, authentication and redirection cannot be handled + * automatically. If output streaming is disabled the + * {@link HttpURLConnection#setFixedLengthStreamingMode(int) + * setFixedLengthStreamingMode} and + * {@link HttpURLConnection#setChunkedStreamingMode(int) setChunkedStreamingMode} + * methods of the underlying connection will never be called. + *

Default is {@code true}. + * @param outputStreaming if output streaming is enabled + */ + public void setOutputStreaming(boolean outputStreaming) { + this.outputStreaming = outputStreaming; + } + public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException { HttpURLConnection connection = openConnection(uri.toURL(), this.proxy); prepareConnection(connection, httpMethod.name()); if (this.bufferRequestBody) { - return new SimpleBufferingClientHttpRequest(connection); + return new SimpleBufferingClientHttpRequest(connection, this.outputStreaming); } else { - return new SimpleStreamingClientHttpRequest(connection, this.chunkSize); + return new SimpleStreamingClientHttpRequest(connection, this.chunkSize, + this.outputStreaming); } } diff --git a/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java b/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java index 2382365570..f14f7e9025 100644 --- a/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java +++ b/spring-web/src/main/java/org/springframework/http/client/SimpleStreamingClientHttpRequest.java @@ -44,10 +44,14 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { private OutputStream body; + private final boolean outputStreaming; - SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize) { + + SimpleStreamingClientHttpRequest(HttpURLConnection connection, int chunkSize, + boolean outputStreaming) { this.connection = connection; this.chunkSize = chunkSize; + this.outputStreaming = outputStreaming; } public HttpMethod getMethod() { @@ -66,12 +70,14 @@ final class SimpleStreamingClientHttpRequest extends AbstractClientHttpRequest { @Override protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException { if (this.body == null) { - int contentLength = (int) headers.getContentLength(); - if (contentLength >= 0) { - this.connection.setFixedLengthStreamingMode(contentLength); - } - else { - this.connection.setChunkedStreamingMode(this.chunkSize); + if(this.outputStreaming) { + int contentLength = (int) headers.getContentLength(); + if (contentLength >= 0) { + this.connection.setFixedLengthStreamingMode(contentLength); + } + else { + this.connection.setChunkedStreamingMode(this.chunkSize); + } } writeHeaders(headers); this.connection.connect(); diff --git a/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java new file mode 100644 index 0000000000..002f33c7e8 --- /dev/null +++ b/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingBufferedSimpleHttpRequestFactoryTests.java @@ -0,0 +1,29 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.http.client; + + +public class NoOutputStreamingBufferedSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { + + @Override + protected ClientHttpRequestFactory createRequestFactory() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setOutputStreaming(false); + return factory; + } + +} diff --git a/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingStreamingSimpleHttpRequestFactoryTests.java b/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingStreamingSimpleHttpRequestFactoryTests.java new file mode 100644 index 0000000000..68111693e1 --- /dev/null +++ b/spring-web/src/test/java/org/springframework/http/client/NoOutputStreamingStreamingSimpleHttpRequestFactoryTests.java @@ -0,0 +1,29 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.http.client; + + +public class NoOutputStreamingStreamingSimpleHttpRequestFactoryTests extends AbstractHttpRequestFactoryTestCase { + + @Override + protected ClientHttpRequestFactory createRequestFactory() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setBufferRequestBody(false); + factory.setOutputStreaming(false); + return factory; + } +} From 953b2b60ad108ba45f9e8a756e86386cf8867acc Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 13 Feb 2013 11:58:21 -0800 Subject: [PATCH 239/311] Javadoc polish --- .../src/main/java/org/springframework/util/StreamUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/src/main/java/org/springframework/util/StreamUtils.java b/spring-core/src/main/java/org/springframework/util/StreamUtils.java index 8adf07159e..a3bb9c8947 100644 --- a/spring-core/src/main/java/org/springframework/util/StreamUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StreamUtils.java @@ -143,7 +143,7 @@ public abstract class StreamUtils { /** * Returns a variant of the given {@link OutputStream} where calling * {@link OutputStream#close() close()} has no effect. - * @param in the OutputStream to decorate + * @param out the OutputStream to decorate * @return a version of the OutputStream that ignores calls to close */ public static OutputStream nonClosing(OutputStream out) { From 6e5cb7fbcddb08b794d2163022bf4a9534e9ea13 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 14 Feb 2013 21:09:28 -0800 Subject: [PATCH 240/311] Protect against '//' in UriComponentsBuilder Refactor UriComponentsBuilder to ensure that paths do not contain empty segments. For example, prior to this commit: fromUriString("http://example.com/abc/").path("/x/y/z") would build the URL "http://example.com/abc//x/y/z" where as it will now build "http://example.com/abc/x/y/z". Issue: SPR-10270 --- .../web/util/UriComponentsBuilder.java | 213 ++++++++---------- .../web/util/UriComponentsBuilderTests.java | 8 + 2 files changed, 108 insertions(+), 113 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java index 4a1aa85af9..30dcac0f84 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java +++ b/spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java @@ -18,7 +18,7 @@ package org.springframework.web.util; import java.net.URI; import java.util.ArrayList; -import java.util.Collection; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; @@ -29,6 +29,7 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; +import org.springframework.web.util.HierarchicalUriComponents.PathComponent; /** * Builder for {@link UriComponents}. @@ -46,6 +47,7 @@ import org.springframework.util.StringUtils; * * @author Arjen Poutsma * @author Rossen Stoyanchev + * @author Phillip Webb * @since 3.1 * @see #newInstance() * @see #fromPath(String) @@ -91,7 +93,7 @@ public class UriComponentsBuilder { private int port = -1; - private PathComponentBuilder pathBuilder = NULL_PATH_COMPONENT_BUILDER; + private CompositePathComponentBuilder pathBuilder = new CompositePathComponentBuilder(); private final MultiValueMap queryParams = new LinkedMultiValueMap(); @@ -334,7 +336,7 @@ public class UriComponentsBuilder { this.port = uri.getPort(); } if (StringUtils.hasLength(uri.getRawPath())) { - this.pathBuilder = new FullPathComponentBuilder(uri.getRawPath()); + this.pathBuilder = new CompositePathComponentBuilder(uri.getRawPath()); } if (StringUtils.hasLength(uri.getRawQuery())) { this.queryParams.clear(); @@ -352,7 +354,7 @@ public class UriComponentsBuilder { this.userInfo = null; this.host = null; this.port = -1; - this.pathBuilder = NULL_PATH_COMPONENT_BUILDER; + this.pathBuilder = new CompositePathComponentBuilder(); this.queryParams.clear(); } @@ -436,12 +438,7 @@ public class UriComponentsBuilder { * @return this UriComponentsBuilder */ public UriComponentsBuilder path(String path) { - if (path != null) { - this.pathBuilder = this.pathBuilder.appendPath(path); - } - else { - this.pathBuilder = NULL_PATH_COMPONENT_BUILDER; - } + this.pathBuilder.addPath(path); resetSchemeSpecificPart(); return this; } @@ -453,22 +450,21 @@ public class UriComponentsBuilder { * @return this UriComponentsBuilder */ public UriComponentsBuilder replacePath(String path) { - this.pathBuilder = NULL_PATH_COMPONENT_BUILDER; - path(path); + this.pathBuilder = new CompositePathComponentBuilder(path); resetSchemeSpecificPart(); return this; } /** - * Appends the given path segments to the existing path of this builder. Each given path segments may contain URI - * template variables. + * Appends the given path segments to the existing path of this builder. Each given + * path segments may contain URI template variables. * * @param pathSegments the URI path segments * @return this UriComponentsBuilder */ public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException { Assert.notNull(pathSegments, "'segments' must not be null"); - this.pathBuilder = this.pathBuilder.appendPathSegments(pathSegments); + this.pathBuilder.addPathSegments(pathSegments); resetSchemeSpecificPart(); return this; } @@ -590,131 +586,122 @@ public class UriComponentsBuilder { return this; } - /** - * Represents a builder for {@link HierarchicalUriComponents.PathComponent} - */ + private interface PathComponentBuilder { - - HierarchicalUriComponents.PathComponent build(); - - PathComponentBuilder appendPath(String path); - - PathComponentBuilder appendPathSegments(String... pathSegments); + PathComponent build(); } - /** - * Represents a builder for full string paths. - */ - private static class FullPathComponentBuilder implements PathComponentBuilder { + private static class CompositePathComponentBuilder implements PathComponentBuilder { - private final StringBuilder path; + private LinkedList componentBuilders = new LinkedList(); - private FullPathComponentBuilder(String path) { - this.path = new StringBuilder(path); + public CompositePathComponentBuilder() { } - public HierarchicalUriComponents.PathComponent build() { - return new HierarchicalUriComponents.FullPathComponent(path.toString()); + public CompositePathComponentBuilder(String path) { + addPath(path); } - public PathComponentBuilder appendPath(String path) { - this.path.append(path); - return this; + public void addPathSegments(String... pathSegments) { + if (!ObjectUtils.isEmpty(pathSegments)) { + PathSegmentComponentBuilder psBuilder = getLastBuilder(PathSegmentComponentBuilder.class); + FullPathComponentBuilder fpBuilder = getLastBuilder(FullPathComponentBuilder.class); + if (psBuilder == null) { + psBuilder = new PathSegmentComponentBuilder(); + this.componentBuilders.add(psBuilder); + if (fpBuilder != null) { + fpBuilder.removeTrailingSlash(); + } + } + psBuilder.append(pathSegments); + } } - public PathComponentBuilder appendPathSegments(String... pathSegments) { - PathComponentCompositeBuilder builder = new PathComponentCompositeBuilder(this); - builder.appendPathSegments(pathSegments); - return builder; - } - } - - /** - * Represents a builder for paths segment paths. - */ - private static class PathSegmentComponentBuilder implements PathComponentBuilder { - - private final List pathSegments = new ArrayList(); - - private PathSegmentComponentBuilder(String... pathSegments) { - this.pathSegments.addAll(removeEmptyPathSegments(pathSegments)); + public void addPath(String path) { + if (StringUtils.hasText(path)) { + PathSegmentComponentBuilder psBuilder = getLastBuilder(PathSegmentComponentBuilder.class); + FullPathComponentBuilder fpBuilder = getLastBuilder(FullPathComponentBuilder.class); + if (psBuilder != null) { + path = path.startsWith("/") ? path : "/" + path; + } + if (fpBuilder == null) { + fpBuilder = new FullPathComponentBuilder(); + this.componentBuilders.add(fpBuilder); + } + fpBuilder.append(path); + } } - private Collection removeEmptyPathSegments(String... pathSegments) { - List result = new ArrayList(); - for (String segment : pathSegments) { - if (StringUtils.hasText(segment)) { - result.add(segment); + @SuppressWarnings("unchecked") + private T getLastBuilder(Class builderClass) { + if (!this.componentBuilders.isEmpty()) { + PathComponentBuilder last = this.componentBuilders.getLast(); + if (builderClass.isInstance(last)) { + return (T) last; } } - return result; + return null; } - public HierarchicalUriComponents.PathComponent build() { - return new HierarchicalUriComponents.PathSegmentComponent(pathSegments); - } - - public PathComponentBuilder appendPath(String path) { - PathComponentCompositeBuilder builder = new PathComponentCompositeBuilder(this); - builder.appendPath(path); - return builder; - } - - public PathComponentBuilder appendPathSegments(String... pathSegments) { - this.pathSegments.addAll(removeEmptyPathSegments(pathSegments)); - return this; - } - } - - /** - * Represents a builder for a collection of PathComponents. - */ - private static class PathComponentCompositeBuilder implements PathComponentBuilder { - - private final List pathComponentBuilders = new ArrayList(); - - private PathComponentCompositeBuilder(PathComponentBuilder builder) { - pathComponentBuilders.add(builder); - } - - public HierarchicalUriComponents.PathComponent build() { - List pathComponents = - new ArrayList(pathComponentBuilders.size()); - - for (PathComponentBuilder pathComponentBuilder : pathComponentBuilders) { - pathComponents.add(pathComponentBuilder.build()); + public PathComponent build() { + int size = this.componentBuilders.size(); + List components = new ArrayList(size); + for (int i = 0; i < size; i++) { + PathComponent pathComponent = this.componentBuilders.get(i).build(); + if (pathComponent != null) { + components.add(pathComponent); + } } - return new HierarchicalUriComponents.PathComponentComposite(pathComponents); - } - - public PathComponentBuilder appendPath(String path) { - this.pathComponentBuilders.add(new FullPathComponentBuilder(path)); - return this; - } - - public PathComponentBuilder appendPathSegments(String... pathSegments) { - this.pathComponentBuilders.add(new PathSegmentComponentBuilder(pathSegments)); - return this; + if (components.isEmpty()) { + return HierarchicalUriComponents.NULL_PATH_COMPONENT; + } + if (components.size() == 1) { + return components.get(0); + } + return new HierarchicalUriComponents.PathComponentComposite(components); } } + private static class FullPathComponentBuilder implements PathComponentBuilder { - /** - * Represents a builder for an empty path. - */ - private static PathComponentBuilder NULL_PATH_COMPONENT_BUILDER = new PathComponentBuilder() { + private StringBuilder path = new StringBuilder(); - public HierarchicalUriComponents.PathComponent build() { - return HierarchicalUriComponents.NULL_PATH_COMPONENT; + public void append(String path) { + this.path.append(path); } - public PathComponentBuilder appendPath(String path) { - return new FullPathComponentBuilder(path); + public PathComponent build() { + if (this.path.length() == 0) { + return null; + } + String path = this.path.toString().replace("//", "/"); + return new HierarchicalUriComponents.FullPathComponent(path); } - public PathComponentBuilder appendPathSegments(String... pathSegments) { - return new PathSegmentComponentBuilder(pathSegments); + public void removeTrailingSlash() { + int index = this.path.length() - 1; + if (this.path.charAt(index) == '/') { + this.path.deleteCharAt(index); + } } - }; + } + + private static class PathSegmentComponentBuilder implements PathComponentBuilder { + + private List pathSegments = new LinkedList(); + + public void append(String... pathSegments) { + for (String pathSegment : pathSegments) { + if (StringUtils.hasText(pathSegment)) { + this.pathSegments.add(pathSegment); + } + } + } + + public PathComponent build() { + return this.pathSegments.isEmpty() ? + null : new HierarchicalUriComponents.PathSegmentComponent(this.pathSegments); + } + } } diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java index 3040ee4aa9..25fbb98d59 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsBuilderTests.java @@ -346,4 +346,12 @@ public class UriComponentsBuilderTests { assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toUriString(), equalTo("http://example.com/foo/../bar")); assertThat(UriComponentsBuilder.fromUriString("http://example.com").path("foo/../bar").build().toUri().getPath(), equalTo("/foo/../bar")); } + + @Test + public void emptySegments() throws Exception { + assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").path("/x/y/z").build().toString(), equalTo("http://example.com/abc/x/y/z")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").pathSegment("x", "y", "z").build().toString(), equalTo("http://example.com/abc/x/y/z")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").path("/x/").path("/y/z").build().toString(), equalTo("http://example.com/abc/x/y/z")); + assertThat(UriComponentsBuilder.fromUriString("http://example.com/abc/").pathSegment("x").path("y").build().toString(), equalTo("http://example.com/abc/x/y")); + } } From f5c9fe69a444607af667911bd4c5074b5b073e7b Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 15 Feb 2013 06:37:04 -0500 Subject: [PATCH 241/311] Update JavaScriptUtils Add escaping for <, >, and PS/LS line terminators Issue: SPR-9983 --- .../web/util/JavaScriptUtils.java | 14 ++++ .../web/util/JavaScriptUtilsTests.java | 67 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java diff --git a/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java b/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java index 0ee697f6d9..861b46fe55 100644 --- a/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java +++ b/spring-web/src/main/java/org/springframework/web/util/JavaScriptUtils.java @@ -80,6 +80,20 @@ public class JavaScriptUtils { else if (c == '\013') { filtered.append("\\v"); } + else if (c == '<') { + filtered.append("\\u003C"); + } + else if (c == '>') { + filtered.append("\\u003E"); + } + // Unicode for PS (line terminator in ECMA-262) + else if (c == '\u2028') { + filtered.append("\\u2028"); + } + // Unicode for LS (line terminator in ECMA-262) + else if (c == '\u2029') { + filtered.append("\\u2029"); + } else { filtered.append(c); } diff --git a/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java new file mode 100644 index 0000000000..182f18eb2d --- /dev/null +++ b/spring-web/src/test/java/org/springframework/web/util/JavaScriptUtilsTests.java @@ -0,0 +1,67 @@ +/* + * Copyright 2004-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.web.util; + +import static org.junit.Assert.*; + +import java.io.UnsupportedEncodingException; + +import org.junit.Test; + +/** + * Test fixture for {@link JavaScriptUtils}. + * + * @author Rossen Stoyanchev + */ +public class JavaScriptUtilsTests { + + @Test + public void escape() { + StringBuilder sb = new StringBuilder(); + sb.append('"'); + sb.append("'"); + sb.append("\\"); + sb.append("/"); + sb.append("\t"); + sb.append("\n"); + sb.append("\r"); + sb.append("\f"); + sb.append("\b"); + sb.append("\013"); + assertEquals("\\\"\\'\\\\\\/\\t\\n\\n\\f\\b\\v", JavaScriptUtils.javaScriptEscape(sb.toString())); + } + + // SPR-9983 + + @Test + public void escapePsLsLineTerminators() { + StringBuilder sb = new StringBuilder(); + sb.append('\u2028'); + sb.append('\u2029'); + String result = JavaScriptUtils.javaScriptEscape(sb.toString()); + + assertEquals("\\u2028\\u2029", result); + } + + // SPR-9983 + + @Test + public void escapeLessThanGreaterThanSigns() throws UnsupportedEncodingException { + assertEquals("\\u003C\\u003E", JavaScriptUtils.javaScriptEscape("<>")); + } + +} From 221562dbebad4bc1a74dc537a7b348f619eae744 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 15 Feb 2013 07:25:26 -0500 Subject: [PATCH 242/311] Use default value for empty values in @RequestParam Issue: SPR-10180 --- ...tractNamedValueMethodArgumentResolver.java | 3 ++ ...questParamMethodArgumentResolverTests.java | 47 +++++++++++++++---- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java index 9e35288687..a515479210 100644 --- a/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java +++ b/spring-web/src/main/java/org/springframework/web/method/annotation/AbstractNamedValueMethodArgumentResolver.java @@ -92,6 +92,9 @@ public abstract class AbstractNamedValueMethodArgumentResolver implements Handle } arg = handleNullValue(namedValueInfo.name, arg, paramType); } + else if ("".equals(arg) && (namedValueInfo.defaultValue != null)) { + arg = resolveDefaultValue(namedValueInfo.defaultValue); + } if (binderFactory != null) { WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name); diff --git a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java index f8978d8b17..bda24d4892 100644 --- a/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java +++ b/spring-web/src/test/java/org/springframework/web/method/annotation/RequestParamMethodArgumentResolverTests.java @@ -68,6 +68,7 @@ public class RequestParamMethodArgumentResolverTests { private MethodParameter paramMultipartFileList; private MethodParameter paramServlet30Part; private MethodParameter paramRequestPartAnnot; + private MethodParameter paramRequired; private NativeWebRequest webRequest; @@ -80,7 +81,7 @@ public class RequestParamMethodArgumentResolverTests { ParameterNameDiscoverer paramNameDiscoverer = new LocalVariableTableParameterNameDiscoverer(); Method method = getClass().getMethod("params", String.class, String[].class, Map.class, MultipartFile.class, - Map.class, String.class, MultipartFile.class, List.class, Part.class, MultipartFile.class); + Map.class, String.class, MultipartFile.class, List.class, Part.class, MultipartFile.class, String.class); paramNamedDefaultValueString = new MethodParameter(method, 0); paramNamedStringArray = new MethodParameter(method, 1); @@ -96,6 +97,7 @@ public class RequestParamMethodArgumentResolverTests { paramServlet30Part = new MethodParameter(method, 8); paramServlet30Part.initParameterNameDiscovery(paramNameDiscoverer); paramRequestPartAnnot = new MethodParameter(method, 9); + paramRequired = new MethodParameter(method, 10); request = new MockHttpServletRequest(); webRequest = new ServletWebRequest(request, new MockHttpServletResponse()); @@ -257,16 +259,41 @@ public class RequestParamMethodArgumentResolverTests { assertNull(result); } + // SPR-10180 + + @Test + public void resolveEmptyValueToDefault() throws Exception { + this.request.addParameter("name", ""); + Object result = resolver.resolveArgument(paramNamedDefaultValueString, null, webRequest, null); + assertEquals("bar", result); + } + + @Test + public void resolveEmptyValueWithoutDefault() throws Exception { + this.request.addParameter("stringNotAnnot", ""); + Object result = resolver.resolveArgument(paramStringNotAnnot, null, webRequest, null); + assertEquals("", result); + } + + @Test + public void resolveEmptyValueRequiredWithoutDefault() throws Exception { + this.request.addParameter("name", ""); + Object result = resolver.resolveArgument(paramRequired, null, webRequest, null); + assertEquals("", result); + } + + public void params(@RequestParam(value = "name", defaultValue = "bar") String param1, - @RequestParam("name") String[] param2, - @RequestParam("name") Map param3, - @RequestParam(value = "file") MultipartFile param4, - @RequestParam Map param5, - String stringNotAnnot, - MultipartFile multipartFileNotAnnot, - List multipartFileList, - Part servlet30Part, - @RequestPart MultipartFile requestPartAnnot) { + @RequestParam("name") String[] param2, + @RequestParam("name") Map param3, + @RequestParam(value = "file") MultipartFile param4, + @RequestParam Map param5, + String stringNotAnnot, + MultipartFile multipartFileNotAnnot, + List multipartFileList, + Part servlet30Part, + @RequestPart MultipartFile requestPartAnnot, + @RequestParam(value = "name") String paramRequired) { } } From ff15534211dfd9d55896c7ac7651f3d3f2a9839a Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 13:01:50 +0100 Subject: [PATCH 243/311] Log4jWebConfigurer supports resolving placeholders against ServletContext init-parameters as well Introducing a ServletContextPropertyUtils helper (analogous to SystemPropertyUtils) along the way. Issue: SPR-10284 --- .../web/util/Log4jWebConfigurer.java | 10 +- .../web/util/ServletContextPropertyUtils.java | 113 ++++++++++++++++++ .../ServletContextPropertyUtilsTests.java | 50 ++++++++ 3 files changed, 167 insertions(+), 6 deletions(-) create mode 100644 spring-web/src/main/java/org/springframework/web/util/ServletContextPropertyUtils.java create mode 100644 spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java diff --git a/spring-web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java b/spring-web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java index 63211beaf5..8b50ac6fda 100644 --- a/spring-web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java +++ b/spring-web/src/main/java/org/springframework/web/util/Log4jWebConfigurer.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,10 @@ package org.springframework.web.util; import java.io.FileNotFoundException; - import javax.servlet.ServletContext; import org.springframework.util.Log4jConfigurer; import org.springframework.util.ResourceUtils; -import org.springframework.util.SystemPropertyUtils; /** * Convenience class that performs custom log4j initialization for web environments, @@ -90,6 +88,7 @@ import org.springframework.util.SystemPropertyUtils; * context-param at all) without worrying. * * @author Juergen Hoeller + * @author Marten Deinum * @since 12.08.2003 * @see org.springframework.util.Log4jConfigurer * @see Log4jConfigListener @@ -122,9 +121,8 @@ public abstract class Log4jWebConfigurer { if (location != null) { // Perform actual log4j initialization; else rely on log4j's default initialization. try { - // Resolve system property placeholders before potentially - // resolving a real path. - location = SystemPropertyUtils.resolvePlaceholders(location); + // Resolve property placeholders before potentially resolving a real path. + location = ServletContextPropertyUtils.resolvePlaceholders(location, servletContext); // Leave a URL (e.g. "classpath:" or "file:") as-is. if (!ResourceUtils.isUrl(location)) { diff --git a/spring-web/src/main/java/org/springframework/web/util/ServletContextPropertyUtils.java b/spring-web/src/main/java/org/springframework/web/util/ServletContextPropertyUtils.java new file mode 100644 index 0000000000..46105f8aa0 --- /dev/null +++ b/spring-web/src/main/java/org/springframework/web/util/ServletContextPropertyUtils.java @@ -0,0 +1,113 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.web.util; + +import javax.servlet.ServletContext; + +import org.springframework.util.PropertyPlaceholderHelper; +import org.springframework.util.SystemPropertyUtils; + +/** + * Helper class for resolving placeholders in texts. Usually applied to file paths. + * + *

A text may contain {@code ${...}} placeholders, to be resolved as servlet context + * init parameters or system properties: e.g. {@code ${user.dir}}. Default values can + * be supplied using the ":" separator between key and value. + * + * @author Juergen Hoeller + * @author Marten Deinum + * @since 3.2.2 + * @see SystemPropertyUtils + * @see ServletContext#getInitParameter(String) + */ +public abstract class ServletContextPropertyUtils { + + private static final PropertyPlaceholderHelper strictHelper = + new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX, + SystemPropertyUtils.PLACEHOLDER_SUFFIX, SystemPropertyUtils.VALUE_SEPARATOR, false); + + private static final PropertyPlaceholderHelper nonStrictHelper = + new PropertyPlaceholderHelper(SystemPropertyUtils.PLACEHOLDER_PREFIX, + SystemPropertyUtils.PLACEHOLDER_SUFFIX, SystemPropertyUtils.VALUE_SEPARATOR, true); + + + /** + * Resolve ${...} placeholders in the given text, replacing them with corresponding + * servlet context init parameter or system property values. + * @param text the String to resolve + * @param servletContext the servletContext to use for lookups. + * @return the resolved String + * @see SystemPropertyUtils#PLACEHOLDER_PREFIX + * @see SystemPropertyUtils#PLACEHOLDER_SUFFIX + * @see SystemPropertyUtils#resolvePlaceholders(String, boolean) + * @throws IllegalArgumentException if there is an unresolvable placeholder + */ + public static String resolvePlaceholders(String text, ServletContext servletContext) { + return resolvePlaceholders(text, servletContext, false); + } + + /** + * Resolve ${...} placeholders in the given text, replacing them with corresponding + * servlet context init parameter or system property values. Unresolvable placeholders + * with no default value are ignored and passed through unchanged if the flag is set to true. + * @param text the String to resolve + * @param servletContext the servletContext to use for lookups. + * @param ignoreUnresolvablePlaceholders flag to determine is unresolved placeholders are ignored + * @return the resolved String + * @see SystemPropertyUtils#PLACEHOLDER_PREFIX + * @see SystemPropertyUtils#PLACEHOLDER_SUFFIX + * @see SystemPropertyUtils#resolvePlaceholders(String, boolean) + * @throws IllegalArgumentException if there is an unresolvable placeholder and the flag is false + */ + public static String resolvePlaceholders(String text, ServletContext servletContext, boolean ignoreUnresolvablePlaceholders) { + PropertyPlaceholderHelper helper = (ignoreUnresolvablePlaceholders ? nonStrictHelper : strictHelper); + return helper.replacePlaceholders(text, new ServletContextPlaceholderResolver(text, servletContext)); + } + + + private static class ServletContextPlaceholderResolver implements PropertyPlaceholderHelper.PlaceholderResolver { + + private final String text; + + private final ServletContext servletContext; + + public ServletContextPlaceholderResolver(String text, ServletContext servletContext) { + this.text = text; + this.servletContext = servletContext; + } + + public String resolvePlaceholder(String placeholderName) { + try { + String propVal = this.servletContext.getInitParameter(placeholderName); + if (propVal == null) { + // Fall back to system properties. + propVal = System.getProperty(placeholderName); + if (propVal == null) { + // Fall back to searching the system environment. + propVal = System.getenv(placeholderName); + } + } + return propVal; + } + catch (Throwable ex) { + System.err.println("Could not resolve placeholder '" + placeholderName + "' in [" + + this.text + "] as ServletContext init-parameter or system property: " + ex); + return null; + } + } + } + +} diff --git a/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java b/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java new file mode 100644 index 0000000000..21082779a4 --- /dev/null +++ b/spring-web/src/test/java/org/springframework/web/util/ServletContextPropertyUtilsTests.java @@ -0,0 +1,50 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */package org.springframework.web.util; + +import org.junit.Test; + +import org.springframework.mock.web.test.MockServletContext; + +import static org.junit.Assert.*; + +/** + * @author Marten Deinum + * @since 3.2.2 + */ +public class ServletContextPropertyUtilsTests { + + @Test + public void resolveAsServletContextInitParameter() { + MockServletContext servletContext = new MockServletContext(); + servletContext.setInitParameter("test.prop", "bar"); + String resolved = ServletContextPropertyUtils.resolvePlaceholders("${test.prop:foo}", servletContext); + assertEquals(resolved, "bar"); + } + + @Test + public void fallbackToSystemProperties() { + MockServletContext servletContext = new MockServletContext(); + System.setProperty("test.prop", "bar"); + try { + String resolved = ServletContextPropertyUtils.resolvePlaceholders("${test.prop:foo}", servletContext); + assertEquals(resolved, "bar"); + } + finally { + System.clearProperty("test.prop"); + } + } + +} From 8987ceea935aa76b48dded4a972a81b51e65145b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 13:08:47 +0100 Subject: [PATCH 244/311] Fixed @Configurable documentation with respect to the use of a prototype-scoped bean definition. Issue: SPR-10298 --- src/reference/docbook/aop.xml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/reference/docbook/aop.xml b/src/reference/docbook/aop.xml index 7078e1535a..331fa89734 100644 --- a/src/reference/docbook/aop.xml +++ b/src/reference/docbook/aop.xml @@ -2847,8 +2847,8 @@ public class Account { When used as a marker interface in this way, Spring will configure new instances of the annotated type (Account in - this case) using a prototype-scoped bean definition with the same name - as the fully-qualified type name + this case) using a bean definition (typically prototype-scoped) with the + same name as the fully-qualified type name (com.xyz.myapp.domain.Account). Since the default name for a bean is the fully-qualified name of its type, a convenient way to declare the prototype definition is simply to omit the @@ -2875,7 +2875,7 @@ public class Account { new Account instances. You can also use autowiring to avoid having to specify a - prototype-scoped bean definition at all. To have Spring apply autowiring + dedicated bean definition at all. To have Spring apply autowiring use the 'autowire' property of the @Configurable annotation: specify either @Configurable(autowire=Autowire.BY_TYPE) or From 81a929aed334e02e7aee59255f7d860232249300 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 13:13:16 +0100 Subject: [PATCH 245/311] Removed outdated EJB reference from auto-proxying documentation. Issue: SPR-10299 --- src/reference/docbook/aop-api.xml | 36 +++++++++++++++---------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/reference/docbook/aop-api.xml b/src/reference/docbook/aop-api.xml index 4099fbc940..a616d7b30d 100644 --- a/src/reference/docbook/aop-api.xml +++ b/src/reference/docbook/aop-api.xml @@ -1405,32 +1405,32 @@ assertEquals("Added two advisors",

- Using the "autoproxy" facility + Using the "auto-proxy" facility So far we've considered explicit creation of AOP proxies using a ProxyFactoryBean or similar factory bean. - Spring also allows us to use "autoproxy" bean definitions, which can + Spring also allows us to use "auto-proxy" bean definitions, which can automatically proxy selected bean definitions. This is built on Spring "bean post processor" infrastructure, which enables modification of any bean definition as the container loads. In this model, you set up some special bean definitions in your XML bean definition file to configure the auto proxy infrastructure. This - allows you just to declare the targets eligible for autoproxying: you + allows you just to declare the targets eligible for auto-proxying: you don't need to use ProxyFactoryBean. There are two ways to do this: - Using an autoproxy creator that refers to specific beans in the + Using an auto-proxy creator that refers to specific beans in the current context. - A special case of autoproxy creation that deserves to be - considered separately; autoproxy creation driven by source-level + A special case of auto-proxy creation that deserves to be + considered separately; auto-proxy creation driven by source-level metadata attributes. @@ -1439,7 +1439,7 @@ assertEquals("Added two advisors", Autoproxy bean definitions The org.springframework.aop.framework.autoproxy - package provides the following standard autoproxy creators. + package provides the following standard auto-proxy creators.
BeanNameAutoProxyCreator @@ -1484,7 +1484,7 @@ assertEquals("Added two advisors", A more general and extremely powerful auto proxy creator is DefaultAdvisorAutoProxyCreator. This will automagically apply eligible advisors in the current context, without - the need to include specific bean names in the autoproxy advisor's + the need to include specific bean names in the auto-proxy advisor's bean definition. It offers the same merit of consistent configuration and avoidance of duplication as BeanNameAutoProxyCreator. @@ -1561,7 +1561,7 @@ assertEquals("Added two advisors", AbstractAdvisorAutoProxyCreator This is the superclass of DefaultAdvisorAutoProxyCreator. You - can create your own autoproxy creators by subclassing this class, in + can create your own auto-proxy creators by subclassing this class, in the unlikely event that advisor definitions offer insufficient customization to the behavior of the framework DefaultAdvisorAutoProxyCreator. @@ -1571,17 +1571,17 @@ assertEquals("Added two advisors",
Using metadata-driven auto-proxying - A particularly important type of autoproxying is driven by + A particularly important type of auto-proxying is driven by metadata. This produces a similar programming model to .NET - ServicedComponents. Instead of using XML deployment - descriptors as in EJB, configuration for transaction management and + ServicedComponents. Instead of defining metadata + in XML descriptors, configuration for transaction management and other enterprise services is held in source-level attributes. In this case, you use the DefaultAdvisorAutoProxyCreator, in combination with Advisors that understand metadata attributes. The metadata specifics are held in the pointcut part of the candidate advisors, rather than in the - autoproxy creation class itself. + auto-proxy creation class itself. This is really a special case of the DefaultAdvisorAutoProxyCreator, but deserves @@ -1589,8 +1589,8 @@ assertEquals("Added two advisors", contained in the advisors, not the AOP framework itself.) The /attributes directory of the JPetStore - sample application shows the use of attribute-driven autoproxying. In - this case, there's no need to use the + sample application shows the use of attribute-driven auto-proxying. + In this case, there's no need to use the TransactionProxyFactoryBean. Simply defining transactional attributes on business objects is sufficient, because of the use of metadata-aware pointcuts. The bean definitions include the @@ -1669,7 +1669,7 @@ assertEquals("Added two advisors", to that of .NET ServicedComponents. - This mechanism is extensible. It's possible to do autoproxying + This mechanism is extensible. It's possible to do auto-proxying based on custom attributes. You need to: @@ -1866,8 +1866,8 @@ System.out.println("Max pool size is " + conf.getMaxSize()); if resources are cached. - Simpler pooling is available using autoproxying. It's possible to - set the TargetSources used by any autoproxy creator. + Simpler pooling is available using auto-proxying. It's possible to + set the TargetSources used by any auto-proxy creator.
From f0787bdb86d309d7070e4054bc6be953a3d0c124 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 13:30:34 +0100 Subject: [PATCH 246/311] Fixed @Configurable documentation with respect to logging when the aspect hasn't been configured Issue: SPR-10295 --- src/reference/docbook/aop.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/reference/docbook/aop.xml b/src/reference/docbook/aop.xml index 331fa89734..fafebe6127 100644 --- a/src/reference/docbook/aop.xml +++ b/src/reference/docbook/aop.xml @@ -2969,8 +2969,8 @@ public class AppConfig { Instances of @Configurable objects created before the aspect has been configured will - result in a warning being issued to the log and no configuration of the - object taking place. An example might be a bean in the Spring + result in a message being issued to the debug log and no configuration + of the object taking place. An example might be a bean in the Spring configuration that creates domain objects when it is initialized by Spring. In this case you can use the "depends-on" bean attribute to manually specify that the bean depends on the configuration From ccca82be1b05accfca5a032237dc94f39e1ccfa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arnaud=20Cogolu=C3=A8gnes?= Date: Thu, 14 Feb 2013 12:05:34 +0100 Subject: [PATCH 247/311] Make StandaloneMockMvcBuilder interface consistent The exception resolvers can now be set using a setter that expects varargs, just like other infrastructure beans. Issue: SPR-10279 --- .../web/servlet/setup/StandaloneMockMvcBuilder.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.java index b9597c196e..079a42fc01 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/StandaloneMockMvcBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -201,15 +201,22 @@ public class StandaloneMockMvcBuilder extends DefaultMockMvcBuilder exceptionResolvers) { this.handlerExceptionResolvers = exceptionResolvers; return this; } + /** + * Set the HandlerExceptionResolver types to use as an array. + */ + public StandaloneMockMvcBuilder setHandlerExceptionResolvers(HandlerExceptionResolver... exceptionResolvers) { + this.handlerExceptionResolvers = Arrays.asList(exceptionResolvers); + return this; + } + /** * Set up view resolution with the given {@link ViewResolver}s. * If not set, an {@link InternalResourceViewResolver} is used by default. From b47d97c23a24a10305c8a82ba4acc823ce52f088 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 15 Feb 2013 09:40:51 -0500 Subject: [PATCH 248/311] Improve error message for JSON path expressions Issue: SPR-SPR-10275 --- .../test/util/JsonPathExpectationsHelper.java | 7 ++- .../util/JsonPathExpectationsHelperTests.java | 45 +++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 spring-test-mvc/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java diff --git a/spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java b/spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java index 054e3b18c9..87608730ad 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/util/JsonPathExpectationsHelper.java @@ -17,7 +17,8 @@ package org.springframework.test.util; import static org.springframework.test.util.AssertionErrors.assertEquals; -import static org.springframework.test.util.AssertionErrors.*; +import static org.springframework.test.util.AssertionErrors.assertTrue; +import static org.springframework.test.util.AssertionErrors.fail; import static org.springframework.test.util.MatcherAssertionErrors.assertThat; import java.text.ParseException; @@ -96,6 +97,10 @@ public class JsonPathExpectationsHelper { } actualValue = actualValueList.get(0); } + else if (actualValue != null && expectedValue != null) { + assertEquals("For JSON path " + this.expression + " type of value", + expectedValue.getClass(), actualValue.getClass()); + } assertEquals("JSON path" + this.expression, expectedValue, actualValue); } diff --git a/spring-test-mvc/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java b/spring-test-mvc/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java new file mode 100644 index 0000000000..b3f42091ef --- /dev/null +++ b/spring-test-mvc/src/test/java/org/springframework/test/util/JsonPathExpectationsHelperTests.java @@ -0,0 +1,45 @@ +/* + * Copyright 2004-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.junit.Test; + + +/** + * Test fixture for {@link JsonPathExpectationsHelper}. + * + * @author Rossen Stoyanchev + */ +public class JsonPathExpectationsHelperTests { + + + @Test + public void test() throws Exception { + try { + new JsonPathExpectationsHelper("$.nr").assertValue("{ \"nr\" : 5 }", "5"); + fail("Expected exception"); + } + catch (AssertionError ex) { + assertEquals("For JSON path $.nr type of value expected: but was:", + ex.getMessage()); + } + } + +} From eda53ec1d833df66848ff17fc0436cb7f4508c25 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 15 Feb 2013 09:41:29 -0500 Subject: [PATCH 249/311] Allow merge of MockMultipart- w/ Mock- request builder Issue: SPR-10280 --- ...ockMultipartHttpServletRequestBuilder.java | 15 +++--- ...ltipartHttpServletRequestBuilderTests.java | 51 +++++++++++++++++++ 2 files changed, 59 insertions(+), 7 deletions(-) create mode 100644 spring-test-mvc/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java index 8be3cf86ea..78ff9d2d56 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java @@ -84,15 +84,16 @@ public class MockMultipartHttpServletRequestBuilder extends MockHttpServletReque if (parent == null) { return this; } - if (!(parent instanceof MockMultipartHttpServletRequestBuilder)) { + if (parent instanceof MockHttpServletRequestBuilder) { + super.merge(parent); + if (parent instanceof MockMultipartHttpServletRequestBuilder) { + MockMultipartHttpServletRequestBuilder parentBuilder = (MockMultipartHttpServletRequestBuilder) parent; + this.files.addAll(parentBuilder.files); + } + } + else { throw new IllegalArgumentException("Cannot merge with [" + parent.getClass().getName() + "]"); } - - super.merge(parent); - - MockMultipartHttpServletRequestBuilder parentBuilder = (MockMultipartHttpServletRequestBuilder) parent; - this.files.addAll(parentBuilder.files); - return this; } diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java new file mode 100644 index 0000000000..e73e3dd4c3 --- /dev/null +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilderTests.java @@ -0,0 +1,51 @@ +/* + * Copyright 2004-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.test.web.servlet.request; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Test; +import org.springframework.http.HttpMethod; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockServletContext; + + +/** + * Test fixture for {@link MockMultipartHttpServletRequestBuilder}. + * + * @author Rossen Stoyanchev + */ +public class MockMultipartHttpServletRequestBuilderTests { + + + @Test + public void test() { + MockHttpServletRequestBuilder parent = new MockHttpServletRequestBuilder(HttpMethod.GET, "/"); + parent.characterEncoding("UTF-8"); + Object result = new MockMultipartHttpServletRequestBuilder("/fileUpload").merge(parent); + + assertNotNull(result); + assertEquals(MockMultipartHttpServletRequestBuilder.class, result.getClass()); + + MockMultipartHttpServletRequestBuilder builder = (MockMultipartHttpServletRequestBuilder) result; + MockHttpServletRequest request = builder.buildRequest(new MockServletContext()); + + assertEquals("UTF-8", request.getCharacterEncoding()); + } + +} \ No newline at end of file From 5b1165b1029263ff0020562da95bd30380f303e4 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 15 Feb 2013 11:31:32 -0500 Subject: [PATCH 250/311] Ignore path parameters in request mappings Before this change the presence of path params (e.g. "/foo;q=1/bar") expected the request mapping to contain a URI variable in the place of semicolon content (e.g. either "/{foo}/bar" or "/{foo};{fooParams}"). The change ensures path params are ignored in @RequestMapping patterns so that "/foo/bar" matches to "/foo;q=1/bar" as well as "/foo;q=1;p=2/bar". Along with this change, the RequestMappingHandlerMapping no longer defaults to having semicolon content removed from the URL, which means @MatrixVariable is supported by default without the need for any further configuration. Issue: SPR-10234 --- .../web/util/UrlPathHelper.java | 6 ++-- .../AnnotationDrivenBeanDefinitionParser.java | 1 - .../WebMvcConfigurationSupport.java | 1 - .../handler/AbstractHandlerMapping.java | 1 + .../handler/AbstractHandlerMethodMapping.java | 7 ++++ .../condition/PatternsRequestCondition.java | 36 +++++++++++-------- .../PatternsRequestConditionTests.java | 11 ++++++ ...RequestMappingInfoHandlerMappingTests.java | 1 - 8 files changed, 42 insertions(+), 22 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java index 7f98ee2369..362b933658 100644 --- a/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java +++ b/spring-web/src/main/java/org/springframework/web/util/UrlPathHelper.java @@ -441,10 +441,8 @@ public class UrlPathHelper { * @return the updated URI string */ public String removeSemicolonContent(String requestUri) { - if (this.removeSemicolonContent) { - return removeSemicolonContentInternal(requestUri); - } - return removeJsessionid(requestUri); + return this.removeSemicolonContent ? + removeSemicolonContentInternal(requestUri) : removeJsessionid(requestUri); } private String removeSemicolonContentInternal(String requestUri) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java index 9d409a3fec..7fef39364c 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java @@ -154,7 +154,6 @@ class AnnotationDrivenBeanDefinitionParser implements BeanDefinitionParser { handlerMappingDef.setSource(source); handlerMappingDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); handlerMappingDef.getPropertyValues().add("order", 0); - handlerMappingDef.getPropertyValues().add("removeSemicolonContent", false); handlerMappingDef.getPropertyValues().add("contentNegotiationManager", contentNegotiationManager); String methodMappingName = parserContext.getReaderContext().registerWithGeneratedName(handlerMappingDef); diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java index e85f189126..c3d1fc0883 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java @@ -192,7 +192,6 @@ public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping(); handlerMapping.setOrder(0); - handlerMapping.setRemoveSemicolonContent(false); handlerMapping.setInterceptors(getInterceptors()); handlerMapping.setContentNegotiationManager(mvcContentNegotiationManager()); return handlerMapping; diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java index ea079c4938..b790a1e62b 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java @@ -127,6 +127,7 @@ public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport /** * Set if ";" (semicolon) content should be stripped from the request URI. + *

The default value is {@code false}. * @see org.springframework.web.util.UrlPathHelper#setRemoveSemicolonContent(boolean) */ public void setRemoveSemicolonContent(boolean removeSemicolonContent) { diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java index c8f11c8175..ccdec77d51 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java @@ -37,6 +37,7 @@ import org.springframework.util.ReflectionUtils.MethodFilter; import org.springframework.web.method.HandlerMethod; import org.springframework.web.method.HandlerMethodSelector; import org.springframework.web.servlet.HandlerMapping; +import org.springframework.web.util.UrlPathHelper; /** * Abstract base class for {@link HandlerMapping} implementations that define a @@ -61,6 +62,12 @@ public abstract class AbstractHandlerMethodMapping extends AbstractHandlerMap private final MultiValueMap urlMap = new LinkedMultiValueMap(); + public AbstractHandlerMethodMapping() { + UrlPathHelper pathHelper = new UrlPathHelper(); + pathHelper.setRemoveSemicolonContent(false); + setUrlPathHelper(pathHelper); + } + /** * Whether to detect handler methods in beans in ancestor ApplicationContexts. *

Default is "false": Only beans in the current ApplicationContext are diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java index 357e31fe36..53642385ca 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java @@ -42,9 +42,16 @@ import org.springframework.web.util.UrlPathHelper; */ public final class PatternsRequestCondition extends AbstractRequestCondition { + private static UrlPathHelper pathHelperNoSemicolonContent; + + static { + pathHelperNoSemicolonContent = new UrlPathHelper(); + pathHelperNoSemicolonContent.setRemoveSemicolonContent(true); + } + private final Set patterns; - private final UrlPathHelper urlPathHelper; + private final UrlPathHelper pathHelper; private final PathMatcher pathMatcher; @@ -105,7 +112,7 @@ public final class PatternsRequestCondition extends AbstractRequestCondition fileExtensions) { this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns)); - this.urlPathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper(); + this.pathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper(); this.pathMatcher = pathMatcher != null ? pathMatcher : new AntPathMatcher(); this.useSuffixPatternMatch = useSuffixPatternMatch; this.useTrailingSlashMatch = useTrailingSlashMatch; @@ -179,7 +186,7 @@ public final class PatternsRequestCondition extends AbstractRequestCondition matches = new ArrayList(); for (String pattern : patterns) { String match = getMatchingPattern(pattern, lookupPath); + if (match == null && lookupPathNoSemicolonContent != null) { + match = getMatchingPattern(pattern, lookupPathNoSemicolonContent); + } if (match != null) { matches.add(match); } } Collections.sort(matches, this.pathMatcher.getPatternComparator(lookupPath)); return matches.isEmpty() ? null : - new PatternsRequestCondition(matches, this.urlPathHelper, this.pathMatcher, this.useSuffixPatternMatch, + new PatternsRequestCondition(matches, this.pathHelper, this.pathMatcher, this.useSuffixPatternMatch, this.useTrailingSlashMatch, this.fileExtensions); } @@ -225,7 +239,7 @@ public final class PatternsRequestCondition extends AbstractRequestCondition patternComparator = this.pathMatcher.getPatternComparator(lookupPath); Iterator iterator = patterns.iterator(); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java index 9c38b7c39c..72f6639713 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/condition/PatternsRequestConditionTests.java @@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletRequest; import org.junit.Test; import org.springframework.mock.web.test.MockHttpServletRequest; +import org.springframework.web.util.UrlPathHelper; /** * @author Rossen Stoyanchev @@ -185,6 +186,16 @@ public class PatternsRequestConditionTests { assertNull(match); } + @Test + public void matchIgnorePathParams() { + UrlPathHelper pathHelper = new UrlPathHelper(); + pathHelper.setRemoveSemicolonContent(false); + PatternsRequestCondition condition = new PatternsRequestCondition(new String[] {"/foo/bar"}, pathHelper, null, true, true); + PatternsRequestCondition match = condition.getMatchingCondition(new MockHttpServletRequest("GET", "/foo;q=1/bar;s=1")); + + assertNotNull(match); + } + @Test public void compareEqualPatterns() { PatternsRequestCondition c1 = new PatternsRequestCondition("/foo*"); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index 2db8412a82..0998bf59f0 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -90,7 +90,6 @@ public class RequestMappingInfoHandlerMappingTests { this.handlerMapping = new TestRequestMappingInfoHandlerMapping(); this.handlerMapping.registerHandler(testController); - this.handlerMapping.setRemoveSemicolonContent(false); } @Test From 06c6cbb6b92655e1b0f5b76380d2e5f1c4b7b493 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 18:17:00 +0100 Subject: [PATCH 251/311] AbstractCachingViewResolver does not use global lock for accessing existing View instances anymore Issue: SPR-3145 --- .../view/AbstractCachingViewResolver.java | 75 +++++++++++++------ 1 file changed, 52 insertions(+), 23 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java index c0a66c5216..51b6cbc2f2 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/AbstractCachingViewResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,9 @@ package org.springframework.web.servlet.view; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import org.springframework.web.context.support.WebApplicationObjectSupport; import org.springframework.web.servlet.View; @@ -42,19 +45,38 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu /** Default maximum number of entries for the view cache: 1024 */ public static final int DEFAULT_CACHE_LIMIT = 1024; + /** Dummy marker object for unresolved views in the cache Maps */ + private static final View UNRESOLVED_VIEW = new View() { + public String getContentType() { + return null; + } + public void render(Map model, HttpServletRequest request, HttpServletResponse response) { + } + }; + + /** The maximum number of entries in the cache */ private volatile int cacheLimit = DEFAULT_CACHE_LIMIT; /** Whether we should refrain from resolving views again if unresolved once */ private boolean cacheUnresolved = true; - /** Map from view key to View instance */ + /** Fast access cache for Views, returning already cached instances without a global lock */ + private final Map viewAccessCache = new ConcurrentHashMap(DEFAULT_CACHE_LIMIT); + + /** Map from view key to View instance, synchronized for View creation */ @SuppressWarnings("serial") - private final Map viewCache = + private final Map viewCreationCache = new LinkedHashMap(DEFAULT_CACHE_LIMIT, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry eldest) { - return size() > getCacheLimit(); + if (size() > getCacheLimit()) { + viewAccessCache.remove(eldest.getKey()); + return true; + } + else { + return false; + } } }; @@ -122,20 +144,27 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu } else { Object cacheKey = getCacheKey(viewName, locale); - synchronized (this.viewCache) { - View view = this.viewCache.get(cacheKey); - if (view == null && (!this.cacheUnresolved || !this.viewCache.containsKey(cacheKey))) { - // Ask the subclass to create the View object. - view = createView(viewName, locale); - if (view != null || this.cacheUnresolved) { - this.viewCache.put(cacheKey, view); - if (logger.isTraceEnabled()) { - logger.trace("Cached view [" + cacheKey + "]"); + View view = this.viewAccessCache.get(cacheKey); + if (view == null) { + synchronized (this.viewCreationCache) { + view = this.viewCreationCache.get(cacheKey); + if (view == null) { + // Ask the subclass to create the View object. + view = createView(viewName, locale); + if (view == null && this.cacheUnresolved) { + view = UNRESOLVED_VIEW; + } + if (view != null) { + this.viewAccessCache.put(cacheKey, view); + this.viewCreationCache.put(cacheKey, view); + if (logger.isTraceEnabled()) { + logger.trace("Cached view [" + cacheKey + "]"); + } } } } - return view; } + return (view != UNRESOLVED_VIEW ? view : null); } } @@ -166,17 +195,16 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu else { Object cacheKey = getCacheKey(viewName, locale); Object cachedView; - synchronized (this.viewCache) { - cachedView = this.viewCache.remove(cacheKey); + synchronized (this.viewCreationCache) { + this.viewAccessCache.remove(cacheKey); + cachedView = this.viewCreationCache.remove(cacheKey); } - if (cachedView == null) { + if (logger.isDebugEnabled()) { // Some debug output might be useful... - if (logger.isDebugEnabled()) { + if (cachedView == null) { logger.debug("No cached instance for view '" + cacheKey + "' was found"); } - } - else { - if (logger.isDebugEnabled()) { + else { logger.debug("Cache for view " + cacheKey + " has been cleared"); } } @@ -189,8 +217,9 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu */ public void clearCache() { logger.debug("Clearing entire view cache"); - synchronized (this.viewCache) { - this.viewCache.clear(); + synchronized (this.viewCreationCache) { + this.viewAccessCache.clear(); + this.viewCreationCache.clear(); } } From acffcdaa01d665efb971d422aeb1d945188cf76b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 18:23:10 +0100 Subject: [PATCH 252/311] Polished *JdbcCall/Insert classes --- .../jdbc/core/simple/AbstractJdbcCall.java | 7 +- .../jdbc/core/simple/AbstractJdbcInsert.java | 133 ++++++++---------- .../jdbc/core/simple/SimpleJdbcCall.java | 4 +- .../jdbc/core/simple/SimpleJdbcInsert.java | 6 +- 4 files changed, 67 insertions(+), 83 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java index 7c80a14d0f..12e1dbd85e 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcCall.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -97,7 +97,7 @@ public abstract class AbstractJdbcCall { /** - * Get the configured {@link JdbcTemplate} + * Get the configured {@link JdbcTemplate}. */ public JdbcTemplate getJdbcTemplate() { return this.jdbcTemplate; @@ -110,7 +110,6 @@ public abstract class AbstractJdbcCall { return this.callableStatementFactory; } - /** * Set the name of the stored procedure. */ @@ -294,7 +293,7 @@ public abstract class AbstractJdbcCall { this.callMetaDataContext.createReturnResultSetParameter(entry.getKey(), entry.getValue()); this.declaredParameters.add(resultSetParameter); } - callMetaDataContext.processParameters(this.declaredParameters); + this.callMetaDataContext.processParameters(this.declaredParameters); this.callString = this.callMetaDataContext.createCallString(); if (logger.isDebugEnabled()) { diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java index 98f0e5991e..cb66d803c7 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/AbstractJdbcInsert.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -74,9 +74,9 @@ public abstract class AbstractJdbcInsert { private final List declaredColumns = new ArrayList(); /** - * Has this operation been compiled? Compilation means at - * least checking that a DataSource or JdbcTemplate has been provided, - * but subclasses may also implement their own custom validation. + * Has this operation been compiled? Compilation means at least checking + * that a DataSource or JdbcTemplate has been provided, but subclasses + * may also implement their own custom validation. */ private boolean compiled = false; @@ -108,9 +108,16 @@ public abstract class AbstractJdbcInsert { //------------------------------------------------------------------------- - // Methods dealing with configuaration properties + // Methods dealing with configuration properties //------------------------------------------------------------------------- + /** + * Get the {@link JdbcTemplate} that is configured to be used. + */ + public JdbcTemplate getJdbcTemplate() { + return this.jdbcTemplate; + } + /** * Set the name of the table for this insert */ @@ -230,41 +237,31 @@ public abstract class AbstractJdbcInsert { return this.insertTypes; } - /** - * Get the {@link JdbcTemplate} that is configured to be used - */ - protected JdbcTemplate getJdbcTemplate() { - return this.jdbcTemplate; - } - //------------------------------------------------------------------------- // Methods handling compilation issues //------------------------------------------------------------------------- /** - * Compile this JdbcInsert using provided parameters and meta data plus other settings. This - * finalizes the configuration for this object and subsequent attempts to compile are ignored. - * This will be implicitly called the first time an un-compiled insert is executed. - * @throws org.springframework.dao.InvalidDataAccessApiUsageException if the object hasn't - * been correctly initialized, for example if no DataSource has been provided + * Compile this JdbcInsert using provided parameters and meta data plus other settings. + * This finalizes the configuration for this object and subsequent attempts to compile are + * ignored. This will be implicitly called the first time an un-compiled insert is executed. + * @throws InvalidDataAccessApiUsageException if the object hasn't been correctly initialized, + * for example if no DataSource has been provided */ public synchronized final void compile() throws InvalidDataAccessApiUsageException { if (!isCompiled()) { if (getTableName() == null) { throw new InvalidDataAccessApiUsageException("Table name is required"); } - try { this.jdbcTemplate.afterPropertiesSet(); } catch (IllegalArgumentException ex) { throw new InvalidDataAccessApiUsageException(ex.getMessage()); } - compileInternal(); this.compiled = true; - if (logger.isDebugEnabled()) { logger.debug("JdbcInsert for table [" + getTableName() + "] compiled"); } @@ -272,21 +269,17 @@ public abstract class AbstractJdbcInsert { } /** - * Method to perform the actual compilation. Subclasses can override this template method to perform - * their own compilation. Invoked after this base class's compilation is complete. + * Method to perform the actual compilation. Subclasses can override this template method + * to perform their own compilation. Invoked after this base class's compilation is complete. */ protected void compileInternal() { - - tableMetaDataContext.processMetaData(getJdbcTemplate().getDataSource(), getColumnNames(), getGeneratedKeyNames()); - - insertString = tableMetaDataContext.createInsertString(getGeneratedKeyNames()); - - insertTypes = tableMetaDataContext.createInsertTypes(); - + this.tableMetaDataContext.processMetaData( + getJdbcTemplate().getDataSource(), getColumnNames(), getGeneratedKeyNames()); + this.insertString = this.tableMetaDataContext.createInsertString(getGeneratedKeyNames()); + this.insertTypes = this.tableMetaDataContext.createInsertTypes(); if (logger.isDebugEnabled()) { - logger.debug("Compiled JdbcInsert. Insert string is [" + getInsertString() + "]"); + logger.debug("Compiled insert object: insert string is [" + getInsertString() + "]"); } - onCompileInternal(); } @@ -318,12 +311,13 @@ public abstract class AbstractJdbcInsert { } /** - * Method to check whether we are allowd to make any configuration changes at this time. If the class has been - * compiled, then no further changes to the configuration are allowed. + * Method to check whether we are allowd to make any configuration changes at this time. + * If the class has been compiled, then no further changes to the configuration are allowed. */ protected void checkIfConfigurationModificationIsAllowed() { if (isCompiled()) { - throw new InvalidDataAccessApiUsageException("Configuration can't be altered once the class has been compiled or used."); + throw new InvalidDataAccessApiUsageException( + "Configuration can't be altered once the class has been compiled or used"); } } @@ -334,7 +328,6 @@ public abstract class AbstractJdbcInsert { /** * Method that provides execution of the insert using the passed in Map of parameters - * * @param args Map with parameter names and values to be used in insert * @return number of rows affected */ @@ -346,7 +339,6 @@ public abstract class AbstractJdbcInsert { /** * Method that provides execution of the insert using the passed in {@link SqlParameterSource} - * * @param parameterSource parameter names and values to be used in insert * @return number of rows affected */ @@ -357,14 +349,13 @@ public abstract class AbstractJdbcInsert { } /** - * Method to execute the insert + * Method to execute the insert. */ private int executeInsertInternal(List values) { if (logger.isDebugEnabled()) { logger.debug("The following parameters are used for insert " + getInsertString() + " with: " + values); } - int updateCount = jdbcTemplate.update(getInsertString(), values.toArray(), getInsertTypes()); - return updateCount; + return getJdbcTemplate().update(getInsertString(), values.toArray(), getInsertTypes()); } /** @@ -428,8 +419,8 @@ public abstract class AbstractJdbcInsert { return kh.getKey(); } else { - throw new DataIntegrityViolationException("Unable to retrieve the generated key for the insert: " + - getInsertString()); + throw new DataIntegrityViolationException( + "Unable to retrieve the generated key for the insert: " + getInsertString()); } } @@ -442,7 +433,7 @@ public abstract class AbstractJdbcInsert { } final KeyHolder keyHolder = new GeneratedKeyHolder(); if (this.tableMetaDataContext.isGetGeneratedKeysSupported()) { - jdbcTemplate.update( + getJdbcTemplate().update( new PreparedStatementCreator() { public PreparedStatement createPreparedStatement(Connection con) throws SQLException { PreparedStatement ps = prepareStatementForGeneratedKeys(con); @@ -467,22 +458,20 @@ public abstract class AbstractJdbcInsert { getGeneratedKeyNames().length + " columns specified: " + Arrays.asList(getGeneratedKeyNames())); } // This is a hack to be able to get the generated key from a database that doesn't support - // get generated keys feature. HSQL is one, PostgreSQL is another. Postgres uses a RETURNING + // get generated keys feature. HSQL is one, PostgreSQL is another. Postgres uses a RETURNING // clause while HSQL uses a second query that has to be executed with the same connection. - final String keyQuery = tableMetaDataContext.getSimulationQueryForGetGeneratedKey( - tableMetaDataContext.getTableName(), - getGeneratedKeyNames()[0]); + final String keyQuery = this.tableMetaDataContext.getSimulationQueryForGetGeneratedKey( + this.tableMetaDataContext.getTableName(), getGeneratedKeyNames()[0]); Assert.notNull(keyQuery, "Query for simulating get generated keys can't be null"); if (keyQuery.toUpperCase().startsWith("RETURNING")) { - Long key = jdbcTemplate.queryForLong( - getInsertString() + " " + keyQuery, - values.toArray(new Object[values.size()])); - HashMap keys = new HashMap(1); + Long key = getJdbcTemplate().queryForObject(getInsertString() + " " + keyQuery, + values.toArray(new Object[values.size()]), Long.class); + Map keys = new HashMap(1); keys.put(getGeneratedKeyNames()[0], key); keyHolder.getKeyList().add(keys); } else { - jdbcTemplate.execute(new ConnectionCallback() { + getJdbcTemplate().execute(new ConnectionCallback() { public Object doInConnection(Connection con) throws SQLException, DataAccessException { // Do the insert PreparedStatement ps = null; @@ -490,13 +479,14 @@ public abstract class AbstractJdbcInsert { ps = con.prepareStatement(getInsertString()); setParameterValues(ps, values, getInsertTypes()); ps.executeUpdate(); - } finally { + } + finally { JdbcUtils.closeStatement(ps); } //Get the key Statement keyStmt = null; ResultSet rs = null; - HashMap keys = new HashMap(1); + Map keys = new HashMap(1); try { keyStmt = con.createStatement(); rs = keyStmt.executeQuery(keyQuery); @@ -505,7 +495,8 @@ public abstract class AbstractJdbcInsert { keys.put(getGeneratedKeyNames()[0], key); keyHolder.getKeyList().add(keys); } - } finally { + } + finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(keyStmt); } @@ -547,14 +538,14 @@ public abstract class AbstractJdbcInsert { } /** - * Method that provides execution of a batch insert using the passed in Maps of parameters - * + * Method that provides execution of a batch insert using the passed in Maps of parameters. * @param batch array of Maps with parameter names and values to be used in batch insert * @return array of number of rows affected */ + @SuppressWarnings("unchecked") protected int[] doExecuteBatch(Map[] batch) { checkCompiled(); - List[] batchValues = new ArrayList[batch.length]; + List[] batchValues = new ArrayList[batch.length]; int i = 0; for (Map args : batch) { List values = matchInParameterValuesWithInsertColumns(args); @@ -565,13 +556,13 @@ public abstract class AbstractJdbcInsert { /** * Method that provides execution of a batch insert using the passed in array of {@link SqlParameterSource} - * * @param batch array of SqlParameterSource with parameter names and values to be used in insert * @return array of number of rows affected */ + @SuppressWarnings("unchecked") protected int[] doExecuteBatch(SqlParameterSource[] batch) { checkCompiled(); - List[] batchValues = new ArrayList[batch.length]; + List[] batchValues = new ArrayList[batch.length]; int i = 0; for (SqlParameterSource parameterSource : batch) { List values = matchInParameterValuesWithInsertColumns(parameterSource); @@ -581,27 +572,22 @@ public abstract class AbstractJdbcInsert { } /** - * Method to execute the batch insert + * Method to execute the batch insert. */ - //TODO synchronize parameter setters with the SimpleJdbcTemplate private int[] executeBatchInternal(final List[] batchValues) { if (logger.isDebugEnabled()) { logger.debug("Executing statement " + getInsertString() + " with batch of size: " + batchValues.length); } - int[] updateCounts = jdbcTemplate.batchUpdate( - getInsertString(), + return getJdbcTemplate().batchUpdate(getInsertString(), new BatchPreparedStatementSetter() { - public void setValues(PreparedStatement ps, int i) throws SQLException { List values = batchValues[i]; setParameterValues(ps, values, getInsertTypes()); } - public int getBatchSize() { return batchValues.length; } }); - return updateCounts; } /** @@ -611,6 +597,7 @@ public abstract class AbstractJdbcInsert { */ private void setParameterValues(PreparedStatement preparedStatement, List values, int[] columnTypes) throws SQLException { + int colIndex = 0; for (Object value : values) { colIndex++; @@ -624,25 +611,23 @@ public abstract class AbstractJdbcInsert { } /** - * Match the provided in parameter values with regitered parameters and parameters defined via metedata - * processing. - * + * Match the provided in parameter values with regitered parameters and parameters defined + * via metadata processing. * @param parameterSource the parameter vakues provided as a {@link SqlParameterSource} * @return Map with parameter names and values */ protected List matchInParameterValuesWithInsertColumns(SqlParameterSource parameterSource) { - return tableMetaDataContext.matchInParameterValuesWithInsertColumns(parameterSource); + return this.tableMetaDataContext.matchInParameterValuesWithInsertColumns(parameterSource); } /** - * Match the provided in parameter values with regitered parameters and parameters defined via metedata - * processing. - * + * Match the provided in parameter values with regitered parameters and parameters defined + * via metadata processing. * @param args the parameter values provided in a Map * @return Map with parameter names and values */ protected List matchInParameterValuesWithInsertColumns(Map args) { - return tableMetaDataContext.matchInParameterValuesWithInsertColumns(args); + return this.tableMetaDataContext.matchInParameterValuesWithInsertColumns(args); } } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcCall.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcCall.java index d687dbc2f6..6ace2d863e 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcCall.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcCall.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -128,7 +128,7 @@ public class SimpleJdbcCall extends AbstractJdbcCall implements SimpleJdbcCallOp /** * @deprecated in favor of {@link #returningResultSet(String, org.springframework.jdbc.core.RowMapper)} */ - @Deprecated + @Deprecated public SimpleJdbcCall returningResultSet(String parameterName, ParameterizedRowMapper rowMapper) { addDeclaredRowMapper(parameterName, rowMapper); return this; diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsert.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsert.java index 7d29df8301..98b89e9f1f 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsert.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsert.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,9 +33,9 @@ import org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor; * name of the table and a Map containing the column names and the column values. * *

The meta data processing is based on the DatabaseMetaData provided by the - * JDBC driver. As long as the JBDC driver can provide the names of the columns + * JDBC driver. As long as the JBDC driver can provide the names of the columns * for a specified table than we can rely on this auto-detection feature. If that - * is not the case then the column names must be specified explicitly. + * is not the case, then the column names must be specified explicitly. * *

The actual insert is being handled using Spring's * {@link org.springframework.jdbc.core.JdbcTemplate}. From add6a7faa0c485428dc87842b9b87bd7d050018e Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 18:24:11 +0100 Subject: [PATCH 253/311] Updated note on Bean Validation 1.1 --- .../beanvalidation/MethodValidationInterceptor.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java b/spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java index 58cd161175..3d4b907fa2 100644 --- a/spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java +++ b/spring-context/src/main/java/org/springframework/validation/beanvalidation/MethodValidationInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,8 +46,8 @@ import org.springframework.validation.annotation.Validated; * of that class. By default, JSR-303 will validate against its default group only. * *

As of Spring 3.1, this functionality requires Hibernate Validator 4.2 or higher. - * In Spring 3.1.2, this class will autodetect a Bean Validation 1.1 compliant provider - * and automatically use the standard method validation support there (once available). + * Once Bean Validation 1.1 becomes available, this class will autodetect a compliant + * provider and automatically use the standard method validation support there. * * @author Juergen Hoeller * @since 3.1 From 5e64723e0291e216b403d234a0677837bf69ffb1 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 18:31:22 +0100 Subject: [PATCH 254/311] Catch ASM ClassReader's IllegalArgumentException and turn it into a more expressive exception, hinting at the class file version Issue: SPR-10292 --- .../core/type/classreading/SimpleMetadataReader.java | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/type/classreading/SimpleMetadataReader.java b/spring-core/src/main/java/org/springframework/core/type/classreading/SimpleMetadataReader.java index b2bf4405da..af2d4c62d8 100644 --- a/spring-core/src/main/java/org/springframework/core/type/classreading/SimpleMetadataReader.java +++ b/spring-core/src/main/java/org/springframework/core/type/classreading/SimpleMetadataReader.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.io.IOException; import java.io.InputStream; import org.springframework.asm.ClassReader; +import org.springframework.core.NestedIOException; import org.springframework.core.io.Resource; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.ClassMetadata; @@ -47,10 +48,14 @@ final class SimpleMetadataReader implements MetadataReader { SimpleMetadataReader(Resource resource, ClassLoader classLoader) throws IOException { InputStream is = new BufferedInputStream(resource.getInputStream()); - ClassReader classReader = null; + ClassReader classReader; try { classReader = new ClassReader(is); } + catch (IllegalArgumentException ex) { + throw new NestedIOException("ASM ClassReader failed to parse class file - " + + "probably due to a new Java class file version that isn't supported yet: " + resource, ex); + } finally { is.close(); } @@ -64,6 +69,7 @@ final class SimpleMetadataReader implements MetadataReader { this.resource = resource; } + public Resource getResource() { return this.resource; } From 7d20c7a62f966a66372b2c9046be1f01eb233bc7 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 15 Feb 2013 18:31:49 +0100 Subject: [PATCH 255/311] Module POMs, etc --- src/dist/changelog.txt | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 5cfeae864b..7002f57645 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -7,6 +7,8 @@ Changes in version 3.2.2 (2013-03-07) -------------------------------------- * official support for Hibernate 4.2 (SPR-10255) +* fixed missing inter-dependencies in module POMs (SPR-10218) +* marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) * ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) * ConfigurationClassPostProcessor detects covariant return type mismatch, avoiding infinite recursion (SPR-10261) * ConfigurationClassPostProcessor allows for overriding of scoped-proxy bean definitions (SPR-10265) @@ -22,14 +24,16 @@ Changes in version 3.2.2 (2013-03-07) * SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) * deprecated (NamedParameter)JdbcTemplate's queryForInt/Long operations in favor of queryForObject (SPR-10257) * added useful query variants without parameters to NamedParameterJdbcTemplate, for convenience in DAOs (SPR-10256) +* "packagesToScan" feature for Hibernate 3 and Hibernate 4 detects annotated packages as well (SPR-7748, SPR-10288) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) * added "mappedClass" property to Jaxb2Marshaller, introducing support for partial unmarshalling (SPR-10282) * added "entityResolver", "classDescriptorResolver", "doctypes" and further properties to CastorMarshaller (SPR-8470) * deprecated CastorMarshaller's "object" property in favor of "rootObject" (SPR-8470) * MediaType throws dedicated InvalidMediaTypeException instead of generic IllegalArgumentException (SPR-10226) -* marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) +* AbstractCachingViewResolver does not use global lock for accessing existing View instances anymore (SPR-3145) * MappingJackson(2)JsonView allows subclasses to access the ObjectMapper and to override content writing (SPR-7619) +* Log4jWebConfigurer supports resolving placeholders against ServletContext init-parameters as well (SPR-10284) * consistent use of LinkedHashMaps and independent getAttributeNames Enumeration in Servlet/Portlet mocks (SPR-10224) From 893574be0e010053f57bcda9943845c3d57d963f Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Fri, 15 Feb 2013 12:31:47 -0800 Subject: [PATCH 256/311] Protect against ArrayIndexOutOfBoundsException Update logic in AbstractAutowireCapableBeanFactory.predictBeanType to protect against a ArrayIndexOutOfBoundsException. Issue: SPR-10304 --- .../support/AbstractAutowireCapableBeanFactory.java | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index 9d11eeb520..f6291331bf 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -573,13 +573,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac @Override protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class... typesToMatch) { - Class beanClass; - if (mbd.getFactoryMethodName() != null) { - beanClass = getTypeForFactoryMethod(beanName, mbd, typesToMatch); - } - else { - beanClass = resolveBeanClass(mbd, beanName, typesToMatch); - } + Class beanClass = (mbd.getFactoryMethodName() != null ? + getTypeForFactoryMethod(beanName, mbd, typesToMatch) : + resolveBeanClass(mbd, beanName, typesToMatch)); // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { @@ -587,7 +583,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Class predictedType = ibp.predictBeanType(beanClass, beanName); - if (predictedType != null && (typesToMatch.length > 1 || + if (predictedType != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) || FactoryBean.class.isAssignableFrom(predictedType))) { return predictedType; } From 608dab28bffb1a61372a38c8b02d7b428ceda7c9 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 19 Feb 2013 09:18:15 -0800 Subject: [PATCH 257/311] Protect against ArrayIndexOutOfBoundsException Update logic in AbstractAutowireCapableBeanFactory.predictBeanType to protect against a ArrayIndexOutOfBoundsException. Issue: SPR-10304 --- .../factory/support/AbstractAutowireCapableBeanFactory.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index f6291331bf..8193abc4ed 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -583,8 +583,9 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Class predictedType = ibp.predictBeanType(beanClass, beanName); - if (predictedType != null && (typesToMatch.length != 1 || - !FactoryBean.class.equals(typesToMatch[0]) || FactoryBean.class.isAssignableFrom(predictedType))) { + if (predictedType != null && (typesToMatch.length > 1 || + (typesToMatch.length > 0 && !FactoryBean.class.equals(typesToMatch[0])) || + FactoryBean.class.isAssignableFrom(predictedType))) { return predictedType; } } From 5008005df0d5d39f7de4a6638fb49d5f46888761 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 19 Feb 2013 09:20:09 -0800 Subject: [PATCH 258/311] Protect against 'has not been resolved to a Class' Update AbstractAutowireCapableBeanFactory.getTypeForFactoryBean to check AbstractBeanDefinition.hasBeanClass() before calling getBeanClass(). The protects against a 'Bean class name [] has not been resolved into an actual Class' IllegalStateException. Issue: SPR-10304 --- .../factory/support/AbstractAutowireCapableBeanFactory.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index 8193abc4ed..f0f519e2a1 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -683,7 +683,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac if (factoryBeanName != null && factoryMethodName != null) { // Try to obtain the FactoryBean's object type without instantiating it at all. BeanDefinition fbDef = getBeanDefinition(factoryBeanName); - if (fbDef instanceof AbstractBeanDefinition) { + if (fbDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) fbDef).hasBeanClass()) { Class fbClass = ((AbstractBeanDefinition) fbDef).getBeanClass(); if (ClassUtils.isCglibProxyClass(fbClass)) { // CGLIB subclass methods hide generic parameters. look at the superclass. From 7e2022b9a7f342ffcc36a0bd99d3a9909abdb2d1 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 19 Feb 2013 11:48:55 -0800 Subject: [PATCH 259/311] Fix @RequestMapping regex reference doc example Issue: SPR-10244 --- src/reference/docbook/mvc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index 7fbd023ac8..fb7d5e96cb 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -1062,7 +1062,7 @@ public class RelativePathUriTemplateController { example: -@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}.{extension:\\.[a-z]}") +@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{extension:\\.[a-z]+}") public void handle(@PathVariable String version, @PathVariable String extension) { // ... } From 5b7969e726edf9080e999730f53f6d449172279d Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 19 Feb 2013 13:19:42 -0800 Subject: [PATCH 260/311] Fix UriComponents.equals() method Fix HierarchicalUriComponents and OpaqueUriComponents .equals() methods. Issue: SPR-10313 --- .../web/util/HierarchicalUriComponents.java | 32 ++++++------------- .../web/util/OpaqueUriComponents.java | 20 ++++-------- .../web/util/UriComponentsTests.java | 29 ++++++++++++++++- 3 files changed, 45 insertions(+), 36 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index dce503962c..60e67878b3 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -39,6 +39,7 @@ import org.springframework.util.StringUtils; * Extension of {@link UriComponents} for hierarchical URIs. * * @author Arjen Poutsma + * @author Phillip Webb * @since 3.1.3 * @see Hierarchical URIs */ @@ -430,28 +431,15 @@ final class HierarchicalUriComponents extends UriComponents { return false; } HierarchicalUriComponents other = (HierarchicalUriComponents) obj; - if (ObjectUtils.nullSafeEquals(getScheme(), other.getScheme())) { - return false; - } - if (ObjectUtils.nullSafeEquals(getUserInfo(), other.getUserInfo())) { - return false; - } - if (ObjectUtils.nullSafeEquals(getHost(), other.getHost())) { - return false; - } - if (this.port != other.port) { - return false; - } - if (!this.path.equals(other.path)) { - return false; - } - if (!this.queryParams.equals(other.queryParams)) { - return false; - } - if (ObjectUtils.nullSafeEquals(getFragment(), other.getFragment())) { - return false; - } - return true; + boolean rtn = true; + rtn &= ObjectUtils.nullSafeEquals(getScheme(), other.getScheme()); + rtn &= ObjectUtils.nullSafeEquals(getUserInfo(), other.getUserInfo()); + rtn &= ObjectUtils.nullSafeEquals(getHost(), other.getHost()); + rtn &= getPort() == other.getPort(); + rtn &= this.path.equals(other.path); + rtn &= this.queryParams.equals(other.queryParams); + rtn &= ObjectUtils.nullSafeEquals(getFragment(), other.getFragment()); + return rtn; } @Override diff --git a/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java index 6e51c77dff..54d788d624 100644 --- a/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/OpaqueUriComponents.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,6 +30,7 @@ import org.springframework.util.ObjectUtils; * Extension of {@link UriComponents} for opaque URIs. * * @author Arjen Poutsma + * @author Phillip Webb * @since 3.2 * @see Hierarchical vs Opaque URIs */ @@ -145,18 +146,11 @@ final class OpaqueUriComponents extends UriComponents { } OpaqueUriComponents other = (OpaqueUriComponents) obj; - - if (ObjectUtils.nullSafeEquals(getScheme(), other.getScheme())) { - return false; - } - if (ObjectUtils.nullSafeEquals(this.ssp, other.ssp)) { - return false; - } - if (ObjectUtils.nullSafeEquals(getFragment(), other.getFragment())) { - return false; - } - - return true; + boolean rtn = true; + rtn &= ObjectUtils.nullSafeEquals(getScheme(), other.getScheme()); + rtn &= ObjectUtils.nullSafeEquals(this.ssp, other.ssp); + rtn &= ObjectUtils.nullSafeEquals(getFragment(), other.getFragment()); + return rtn; } @Override diff --git a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java index c1ad072e8b..2013e6df65 100644 --- a/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java +++ b/spring-web/src/test/java/org/springframework/web/util/UriComponentsTests.java @@ -26,9 +26,14 @@ import java.net.URISyntaxException; import org.junit.Test; import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; import static org.junit.Assert.*; -/** @author Arjen Poutsma */ +/** + * @author Arjen Poutsma + * @author Phillip Webb + */ public class UriComponentsTests { @Test @@ -92,4 +97,26 @@ public class UriComponentsTests { assertThat(uriComponents.toString(), equalTo(readObject.toString())); } + @Test + public void equalsHierarchicalUriComponents() throws Exception { + UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build(); + UriComponents uriComponents2 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bar={baz}").build(); + UriComponents uriComponents3 = UriComponentsBuilder.fromUriString("http://example.com").path("/{foo}").query("bin={baz}").build(); + assertThat(uriComponents1, instanceOf(HierarchicalUriComponents.class)); + assertThat(uriComponents1, equalTo(uriComponents1)); + assertThat(uriComponents1, equalTo(uriComponents2)); + assertThat(uriComponents1, not(equalTo(uriComponents3))); + } + + @Test + public void equalsOpaqueUriComponents() throws Exception { + UriComponents uriComponents1 = UriComponentsBuilder.fromUriString("http:example.com/foo/bar").build(); + UriComponents uriComponents2 = UriComponentsBuilder.fromUriString("http:example.com/foo/bar").build(); + UriComponents uriComponents3 = UriComponentsBuilder.fromUriString("http:example.com/foo/bin").build(); + assertThat(uriComponents1, instanceOf(OpaqueUriComponents.class)); + assertThat(uriComponents1, equalTo(uriComponents1)); + assertThat(uriComponents1, equalTo(uriComponents2)); + assertThat(uriComponents1, not(equalTo(uriComponents3))); + } + } From 6a45d5bfb06babc4a3ced34eccfc53fe964bec54 Mon Sep 17 00:00:00 2001 From: Carson McDonald Date: Wed, 20 Feb 2013 08:53:30 -0500 Subject: [PATCH 261/311] Minor changes to fix typos --- .../jdbc/core/metadata/CallMetaDataProvider.java | 16 ++++++++-------- .../core/metadata/TableMetaDataProvider.java | 10 +++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProvider.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProvider.java index a3da020588..29accf8ffa 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProvider.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/CallMetaDataProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -56,33 +56,33 @@ public interface CallMetaDataProvider { /** * Provide any modification of the procedure name passed in to match the meta data currently used. - * This could include alterig the case. + * This could include altering the case. */ String procedureNameToUse(String procedureName); /** * Provide any modification of the catalog name passed in to match the meta data currently used. - * This could include alterig the case. + * This could include altering the case. */ String catalogNameToUse(String catalogName); /** * Provide any modification of the schema name passed in to match the meta data currently used. - * This could include alterig the case. + * This could include altering the case. */ String schemaNameToUse(String schemaName); /** * Provide any modification of the catalog name passed in to match the meta data currently used. - * The reyurned value will be used for meta data lookups. This could include alterig the case used - * or providing a base catalog if mone provided. + * The returned value will be used for meta data lookups. This could include altering the case used + * or providing a base catalog if none is provided. */ String metaDataCatalogNameToUse(String catalogName) ; /** * Provide any modification of the schema name passed in to match the meta data currently used. - * The reyurned value will be used for meta data lookups. This could include alterig the case used - * or providing a base schema if mone provided. + * The returned value will be used for meta data lookups. This could include altering the case used + * or providing a base schema if none is provided. */ String metaDataSchemaNameToUse(String schemaName) ; diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataProvider.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataProvider.java index 0dff1678c4..c7365bed5b 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataProvider.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/TableMetaDataProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -76,8 +76,8 @@ public interface TableMetaDataProvider { /** * Provide any modification of the catalog name passed in to match the meta data currently used. - * The reyurned value will be used for meta data lookups. This could include alterig the case used or - * providing a base catalog if mone provided. + * The returned value will be used for meta data lookups. This could include altering the case used or + * providing a base catalog if none is provided. * * @param catalogName * @return catalog name to use @@ -86,8 +86,8 @@ public interface TableMetaDataProvider { /** * Provide any modification of the schema name passed in to match the meta data currently used. - * The reyurned value will be used for meta data lookups. This could include alterig the case used or - * providing a base schema if mone provided. + * The returned value will be used for meta data lookups. This could include altering the case used or + * providing a base schema if none is provided. * * @param schemaName * @return schema name to use From 720714b43456d3216f12fa679546cf29bb4b2c65 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 11:26:59 -0800 Subject: [PATCH 262/311] Add JdbcTestUtils.deleteRowsInTableWhere method Issue: SPR-10302 --- .../test/jdbc/JdbcTestUtils.java | 37 +++++++++++++++++- .../test/jdbc/JdbcTestUtilsTests.java | 39 ++++++++++++++++++- 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java b/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java index 532a82c01f..e096df5caa 100644 --- a/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java +++ b/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,13 +23,13 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; - import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.core.io.support.EncodedResource; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.SqlParameterValue; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.util.StringUtils; @@ -103,6 +103,39 @@ public class JdbcTestUtils { return totalRowCount; } + /** + * Delete rows from the given table, using the provided {@code WHERE} clause. + *

If the provided {@code WHERE} clause contains text, it will be prefixed + * with {@code " WHERE "} and then appended to the generated {@code DELETE} + * statement. For example, if the provided table name is {@code "person"} and + * the provided where clause is {@code "name = 'Bob' and age > 25"}, the + * resulting SQL statement to execute will be + * {@code "DELETE FROM person WHERE name = 'Bob' and age > 25"}. + *

As an alternative to hard-coded values, the {@code "?"} placeholder can + * be used within the {@code WHERE} clause, binding to the given arguments. + * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations + * @param tableName the name of the table to delete rows in + * @param whereClause the {@code WHERE} clause to append to the query + * @param args arguments to bind to the query (leaving it to the PreparedStatement + * to guess the corresponding SQL type); may also contain {@link SqlParameterValue} + * objects which indicate not only the argument value but also the SQL type and + * optionally the scale. + * @return the number of rows deleted from the table + */ + public static int deleteFromTableWhere(JdbcTemplate jdbcTemplate, String tableName, + String whereClause, Object... args) { + String sql = "DELETE FROM " + tableName; + if(StringUtils.hasText(whereClause)) { + sql += " WHERE " + whereClause; + } + int rowCount = (args != null && args.length > 0 ? jdbcTemplate.update(sql, args) + : jdbcTemplate.update(sql)); + if (logger.isInfoEnabled()) { + logger.info("Deleted " + rowCount + " rows from table " + tableName); + } + return rowCount; + } + /** * Drop the specified tables. * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations diff --git a/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java b/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java index d5fd1b68e4..6ebdf91819 100644 --- a/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java +++ b/spring-test/src/test/java/org/springframework/test/jdbc/JdbcTestUtilsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,25 +16,38 @@ package org.springframework.test.jdbc; -import static org.junit.Assert.*; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.BDDMockito.given; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.EncodedResource; +import org.springframework.jdbc.core.JdbcTemplate; /** * Unit tests for {@link JdbcTestUtils}. * * @author Thomas Risberg * @author Sam Brannen + * @author Phillip Webb * @since 2.5.4 */ +@RunWith(MockitoJUnitRunner.class) public class JdbcTestUtilsTests { + @Mock + private JdbcTemplate jdbcTemplate; + @Test public void containsDelimiters() { assertTrue("test with ';' is wrong", !JdbcTestUtils.containsSqlScriptDelimiters("select 1\n select ';'", ';')); @@ -104,4 +117,26 @@ public class JdbcTestUtilsTests { assertEquals("statement 4 not split correctly", statement4, statements.get(3)); } + @Test + public void testDeleteNoWhere() throws Exception { + given(jdbcTemplate.update("DELETE FROM person")).willReturn(10); + int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", null); + assertThat(deleted, equalTo(10)); + } + + @Test + public void testDeleteWhere() throws Exception { + given(jdbcTemplate.update("DELETE FROM person WHERE name = 'Bob' and age > 25")).willReturn(10); + int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", "name = 'Bob' and age > 25"); + assertThat(deleted, equalTo(10)); + } + + @Test + public void deleteWhereAndArguments() throws Exception { + given(jdbcTemplate.update("DELETE FROM person WHERE name = ? and age > ?", "Bob", 25)).willReturn(10); + int deleted = JdbcTestUtils.deleteFromTableWhere(jdbcTemplate, "person", "name = ? and age > ?", "Bob", 25); + assertThat(deleted, equalTo(10)); + } + + } From e2e4cbe6b3cb017f7567ddb2f73b2dc9cdf3c9d9 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 11:56:57 -0800 Subject: [PATCH 263/311] Deprecate HttpStatus.MOVED_TEMPORARILY Deprecate HttpStatus.MOVED_TEMPORARILY in favor of HttpStatus.FOUND since HttpStatus.valueOf(302) will always return FOUND. The name of the 302 status code was changed between HTTP 1.0 and HTTP 1.1 but the underlying meaning remains the same. Issue: SPR-10300 --- .../src/main/java/org/springframework/http/HttpStatus.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/spring-web/src/main/java/org/springframework/http/HttpStatus.java b/spring-web/src/main/java/org/springframework/http/HttpStatus.java index 74dc2af2c2..225fbccd9f 100644 --- a/spring-web/src/main/java/org/springframework/http/HttpStatus.java +++ b/spring-web/src/main/java/org/springframework/http/HttpStatus.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -125,7 +125,9 @@ public enum HttpStatus { /** * {@code 302 Moved Temporarily}. * @see HTTP/1.0 + * @deprecated In favor of {@link #FOUND} which will be returned from {@code HttpStatus.valueOf(302)} */ + @Deprecated MOVED_TEMPORARILY(302, "Moved Temporarily"), /** * {@code 303 See Other}. From 9a6c6b9ee63caa30b9e37960348f8f1a1259e123 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 13:17:40 -0800 Subject: [PATCH 264/311] StringToEnumConverterFactory class from enum value Update StringToEnumConverterFactory to search superclasses until Class.isEnum() returns true. This allows conversion when the enum class is obtained from the enum value: public static enum SubFoo { BAR { String s() { return "x"; } }; abstract String s(); } conversionService.convert("BAR", SubFoo.BAR.getClass()) This fix is particularly important when converting collections of enums. Issue: SPR-10329 --- .../support/StringToEnumConverterFactory.java | 11 +++++++-- .../support/DefaultConversionTests.java | 24 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java b/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java index 62cf4748ea..7326b3f045 100644 --- a/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java +++ b/spring-core/src/main/java/org/springframework/core/convert/support/StringToEnumConverterFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2009 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.core.convert.support; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.ConverterFactory; +import org.springframework.util.Assert; /** * Converts from a String to a java.lang.Enum by calling {@link Enum#valueOf(Class, String)}. @@ -29,7 +30,13 @@ import org.springframework.core.convert.converter.ConverterFactory; final class StringToEnumConverterFactory implements ConverterFactory { public Converter getConverter(Class targetType) { - return new StringToEnum(targetType); + Class enumType = targetType; + while(enumType != null && !enumType.isEnum()) { + enumType = enumType.getSuperclass(); + } + Assert.notNull(enumType, "The target type " + targetType.getName() + + " does not refer to an enum"); + return new StringToEnum(enumType); } private class StringToEnum implements Converter { diff --git a/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java b/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java index 7b2ff0490a..ba42cddf9d 100644 --- a/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java +++ b/spring-core/src/test/java/org/springframework/core/convert/support/DefaultConversionTests.java @@ -17,6 +17,7 @@ package org.springframework.core.convert.support; import static org.hamcrest.Matchers.equalTo; +import static org.junit.Assert.*; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -212,6 +213,11 @@ public class DefaultConversionTests { assertEquals(Foo.BAR, conversionService.convert("BAR", Foo.class)); } + @Test + public void testStringToEnumWithSubclss() throws Exception { + assertEquals(SubFoo.BAZ, conversionService.convert("BAZ", SubFoo.BAR.getClass())); + } + @Test public void testStringToEnumEmptyString() { assertEquals(null, conversionService.convert("", Foo.class)); @@ -226,6 +232,24 @@ public class DefaultConversionTests { BAR, BAZ; } + public static enum SubFoo { + + BAR { + @Override + String s() { + return "x"; + } + }, + BAZ { + @Override + String s() { + return "y"; + } + }; + + abstract String s(); + } + @Test public void testStringToLocale() { assertEquals(Locale.ENGLISH, conversionService.convert("en", Locale.class)); From 82bd06f255896c0b3399935967fbf06811356f69 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 14:25:47 -0800 Subject: [PATCH 265/311] Protect against missing SpEL selection expression Update InternalSpelExpressionParser to ensure that SPeL selections ('$[...]', '^[...]', '?[...]') always include a nested expression. Issue: SPR-10328 --- .../org/springframework/expression/spel/SpelMessage.java | 3 ++- .../springframework/expression/spel/ast/Selection.java | 7 +++++-- .../spel/standard/InternalSpelExpressionParser.java | 3 +++ .../springframework/expression/spel/SpelReproTests.java | 9 +++++++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java b/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java index d9ae1a2efb..3f89bed512 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java @@ -109,7 +109,8 @@ public enum SpelMessage { OPERAND_NOT_DECREMENTABLE(Kind.ERROR,1067,"the expression component ''{0}'' does not support decrement"), // NOT_ASSIGNABLE(Kind.ERROR,1068,"the expression component ''{0}'' is not assignable"), // MISSING_CHARACTER(Kind.ERROR,1069,"missing expected character ''{0}''"), - LEFT_OPERAND_PROBLEM(Kind.ERROR,1070, "Problem parsing left operand"); + LEFT_OPERAND_PROBLEM(Kind.ERROR,1070, "Problem parsing left operand"), + MISSING_SELECTION_EXPRESSION(Kind.ERROR, 1071, "A required selection expression has not been specified"); private Kind kind; private int code; diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java index 7489c6ba69..710e975921 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/ast/Selection.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,6 +29,7 @@ import org.springframework.expression.TypedValue; import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.SpelEvaluationException; import org.springframework.expression.spel.SpelMessage; +import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -54,7 +55,9 @@ public class Selection extends SpelNodeImpl { private final boolean nullSafe; public Selection(boolean nullSafe, int variant,int pos,SpelNodeImpl expression) { - super(pos,expression); + super(pos, expression != null ? new SpelNodeImpl[] { expression } + : new SpelNodeImpl[] {}); + Assert.notNull(expression, "Expression must not be null"); this.nullSafe = nullSafe; this.variant = variant; } diff --git a/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java b/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java index c243b5d7f4..7915a3c015 100644 --- a/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java +++ b/spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java @@ -557,6 +557,9 @@ class InternalSpelExpressionParser extends TemplateAwareExpressionParser { } nextToken(); SpelNodeImpl expr = eatExpression(); + if(expr == null) { + raiseInternalException(toPos(t), SpelMessage.MISSING_SELECTION_EXPRESSION); + } eatToken(TokenKind.RSQUARE); if (t.kind==TokenKind.SELECT_FIRST) { constructedNodes.push(new Selection(nullSafeNavigation,Selection.FIRST,toPos(t),expr)); diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 549b44aa53..62e00b0eb3 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -27,6 +27,7 @@ import static org.junit.Assert.fail; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; @@ -1744,6 +1745,14 @@ public class SpelReproTests extends ExpressionTestCase { parseExpression.getValue(context); } + @Test + public void SPR_10328() throws Exception { + thrown.expect(SpelParseException.class); + thrown.expectMessage("EL1071E:(pos 2): A required selection expression has not been specified"); + Expression exp = parser.parseExpression("$[]"); + exp.getValue(Arrays.asList("foo", "bar", "baz")); + } + public static class BooleanHolder { private Boolean simpleProperty = true; From 29f4374bcfadccfe822197e2f85cff6e73cd4972 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 15:25:02 -0800 Subject: [PATCH 266/311] MergePlugin uses project source not jar source Update gradle MergePlugin to use the 'project.sourceSets.main.output' for jar content rather than 'project.jar.source'. This prevents superfluous MANIFEST.MF files from appearing in the merged jar. Issue: SPR-10324 --- .../org/springframework/build/gradle/MergePlugin.groovy | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy b/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy index 510a2698c6..4143780702 100644 --- a/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy +++ b/buildSrc/src/main/groovy/org/springframework/build/gradle/MergePlugin.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -110,7 +110,7 @@ class MergePlugin implements Plugin { // update 'into' project artifacts to contain the source artifact contents project.merge.into.sourcesJar.from(project.sourcesJar.source) - project.merge.into.jar.from(project.jar.source) + project.merge.into.jar.from(project.sourceSets.main.output) project.merge.into.javadoc { source += project.javadoc.source classpath += project.javadoc.classpath From 009d2a5efd456a37c29fd984be3087f09082c325 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 15:35:13 -0800 Subject: [PATCH 267/311] Remove unnecessary null check in SysEnvPropSource Remove unnecessary null check and dead code from SystemEnvironmentPropertySource. Issue: SPR-10318 --- .../core/env/SystemEnvironmentPropertySource.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java b/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java index 09082aad5c..0baba6a8c1 100644 --- a/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java +++ b/spring-core/src/main/java/org/springframework/core/env/SystemEnvironmentPropertySource.java @@ -88,10 +88,6 @@ public class SystemEnvironmentPropertySource extends MapPropertySource { public Object getProperty(String name) { Assert.notNull(name, "property name must not be null"); String actualName = resolvePropertyName(name); - if (actualName == null) { - // at this point we know the property does not exist - return null; - } if (logger.isDebugEnabled() && !name.equals(actualName)) { logger.debug(String.format( "PropertySource [%s] does not contain '%s', but found equivalent '%s'", From da034eb020d29fdc29856e16a0bd6d4d32cb0bae Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Mon, 25 Feb 2013 16:31:45 -0800 Subject: [PATCH 268/311] Replace references to SimpleJdbcTemplate in docs Rework JDBC section of the manual to remove references to the now deprecated SimpleJdbcTemplate class. Issue: SPR-10317 --- src/reference/docbook/jdbc.xml | 151 ++++----------------------------- 1 file changed, 18 insertions(+), 133 deletions(-) diff --git a/src/reference/docbook/jdbc.xml b/src/reference/docbook/jdbc.xml index e3b3d7f03c..f4af0e3b23 100644 --- a/src/reference/docbook/jdbc.xml +++ b/src/reference/docbook/jdbc.xml @@ -159,19 +159,12 @@ parameters for an SQL statement. - - SimpleJdbcTemplate combines - the most frequently used operations of JdbcTemplate and - NamedParameterJdbcTemplate. - - SimpleJdbcInsert and SimpleJdbcCall optimize database metadata to limit the amount of necessary configuration. This approach simplifies coding so that you only need to provide the name of the table or procedure - and provide a map of parameters matching the column names. + and provide a map of parameters matching the column names. This only works if the database provides adequate metadata. If the database doesn't provide this metadata, you will have to provide explicit configuration of the parameters. @@ -201,8 +194,7 @@ TR: OK. I removed the sentence since it isn;t entirely accurate. The implementat contains the JdbcTemplate class and its various callback interfaces, plus a variety of related classes. A subpackage named org.springframework.jdbc.core.simple contains - the SimpleJdbcTemplate class and the related - SimpleJdbcInsert and + the SimpleJdbcInsert and SimpleJdbcCall classes. Another subpackage named org.springframework.jdbc.core.namedparam contains the NamedParameterJdbcTemplate class and the related @@ -434,8 +426,6 @@ private static final class ActorMapper implements RowMapper<Actor> { A common practice when using the JdbcTemplate class (and the associated SimpleJdbcTemplate - and NamedParameterJdbcTemplate classes) is to configure a DataSource in your Spring configuration file, and then dependency-inject that @@ -693,107 +683,6 @@ public int countOfActors(Actor exampleActor) { of an application. -

- <classname>SimpleJdbcTemplate</classname> - - The SimpleJdbcTemplate class wraps the - classic JdbcTemplate and leverages Java 5 - language features such as varargs and autoboxing. - - - In Spring 3.0, the original JdbcTemplate - also supports Java 5-enhanced syntax with generics and varargs. - However, the SimpleJdbcTemplate provides a - simpler API that works best when you do not need access to all the - methods that the JdbcTemplate offers. Also, because the - SimpleJdbcTemplate was designed for Java 5, it - has more methods that take advantage of varargs due to different - ordering of the parameters. - - - The value-add of the SimpleJdbcTemplate - class in the area of syntactic-sugar is best illustrated with a - before-and-after example. The next code snippet shows data access code - that uses the classic JdbcTemplate, followed by a - code snippet that does the same job with the - SimpleJdbcTemplate. - - // classic JdbcTemplate-style... -private JdbcTemplate jdbcTemplate; - -public void setDataSource(DataSource dataSource) { - this.jdbcTemplate = new JdbcTemplate(dataSource); -} - -public Actor findActor(String specialty, int age) { - - String sql = "select id, first_name, last_name from T_ACTOR" + - " where specialty = ? and age = ?"; - - RowMapper<Actor> mapper = new RowMapper<Actor>() { - public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { - Actor actor = new Actor(); - actor.setId(rs.getLong("id")); - actor.setFirstName(rs.getString("first_name")); - actor.setLastName(rs.getString("last_name")); - return actor; - } - }; - - - // notice the wrapping up of the arguments in an array - return (Actor) jdbcTemplate.queryForObject(sql, new Object[] {specialty, age}, mapper); -} - - Here is the same method, with the - SimpleJdbcTemplate. - - // SimpleJdbcTemplate-style... -private SimpleJdbcTemplate simpleJdbcTemplate; - -public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); -} - -public Actor findActor(String specialty, int age) { - - String sql = "select id, first_name, last_name from T_ACTOR" + - " where specialty = ? and age = ?"; - RowMapper<Actor> mapper = new RowMapper<Actor>() { - public Actor mapRow(ResultSet rs, int rowNum) throws SQLException { - Actor actor = new Actor(); - actor.setId(rs.getLong("id")); - actor.setFirstName(rs.getString("first_name")); - actor.setLastName(rs.getString("last_name")); - return actor; - } - }; - - // notice the use of varargs since the parameter values now come - // after the RowMapper parameter - return this.simpleJdbcTemplate.queryForObject(sql, mapper, specialty, age); -} - - See for guidelines on - how to use the SimpleJdbcTemplate class in the - context of an application. - - - The SimpleJdbcTemplate class only offers - a subset of the methods exposed on the - JdbcTemplate class. If you need to use a method - from the JdbcTemplate that is not defined on - the SimpleJdbcTemplate, you can always access - the underlying JdbcTemplate by calling the - getJdbcOperations() method on the - SimpleJdbcTemplate, which then allows you to - invoke the method that you want. The only downside is that the methods - on the JdbcOperations interface are not - generic, so you are back to casting and so on. - -
-
<interfacename>SQLExceptionTranslator</interfacename> @@ -1370,9 +1259,7 @@ dataSource.setPassword(""); Most JDBC drivers provide improved performance if you batch multiple calls to the same prepared statement. By grouping updates into batches you - limit the number of round trips to the database. This section covers batch - processing using both the JdbcTemplate and the - SimpleJdbcTemplate. + limit the number of round trips to the database.
Basic batch operations with the JdbcTemplate @@ -1579,11 +1466,11 @@ TR: Revised, please review.-->For this example, the initializing method is the you will see examples of multiple ones later. public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource).withTableName("t_actor"); } @@ -1618,11 +1505,11 @@ TR: Revised, please review.-->For this example, the initializing method is the usingGeneratedKeyColumns method. public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1658,11 +1545,11 @@ TR: Revised, please review.-->For this example, the initializing method is the column names with the usingColumns method: public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1697,11 +1584,11 @@ TR: Revised, please review.-->For this example, the initializing method is the to extract the parameter values. Here is an example: public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1721,11 +1608,11 @@ TR: Revised, please review.-->For this example, the initializing method is the can be chained. public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcInsert insertActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.insertActor = new SimpleJdbcInsert(dataSource) .withTableName("t_actor") @@ -1786,11 +1673,11 @@ END;The in_id parameter contains the procedure. public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcCall procReadActor; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); this.procReadActor = new SimpleJdbcCall(dataSource) .withProcedureName("read_actor"); @@ -2004,11 +1891,11 @@ END; method. public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; + private JdbcTemplate jdbcTemplate; private SimpleJdbcCall funcGetActorName; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + this.jdbcTemplate = new JdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.setResultsMapCaseInsensitive(true); this.funcGetActorName = @@ -2062,11 +1949,9 @@ END;To call this procedure you declare the newInstance method. public class JdbcActorDao implements ActorDao { - private SimpleJdbcTemplate simpleJdbcTemplate; private SimpleJdbcCall procReadAllActors; public void setDataSource(DataSource dataSource) { - this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.setResultsMapCaseInsensitive(true); this.procReadAllActors = @@ -2679,7 +2564,7 @@ clobReader.close();]]> or you need to generate the SQL string dynamically once you know how many placeholders are required. The named parameter support provided in the NamedParameterJdbcTemplate and - SimpleJdbcTemplate takes the latter approach. + JdbcTemplate takes the latter approach. Pass in the values as a java.util.List of primitive objects. This list will be used to insert the required placeholders and pass in the values during the statement From 3100d89d0710c8306cf8fb363eef5bc34d0a5a38 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 12:33:05 +0100 Subject: [PATCH 269/311] Clean up console output for spring-beans tests --- .../factory/DefaultListableBeanFactoryTests.java | 1 - .../factory/parsing/CustomProblemReporterTests.java | 3 --- spring-beans/src/test/resources/log4j.xml | 12 ++---------- 3 files changed, 2 insertions(+), 14 deletions(-) diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java index 4045578c8c..94f6376ce1 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java @@ -591,7 +591,6 @@ public class DefaultListableBeanFactoryTests { fail("Should throw exception on invalid property"); } catch (BeanCreationException ex) { - ex.printStackTrace(); assertTrue(ex.getCause() instanceof NotWritablePropertyException); NotWritablePropertyException cause = (NotWritablePropertyException) ex.getCause(); // expected diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java index cc009917fd..550e87375b 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/parsing/CustomProblemReporterTests.java @@ -29,7 +29,6 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.Resource; import org.springframework.tests.sample.beans.TestBean; - /** * @author Rob Harrop * @author Chris Beams @@ -78,7 +77,6 @@ public final class CustomProblemReporterTests { @Override public void error(Problem problem) { - System.out.println(problem); this.errors.add(problem); } @@ -88,7 +86,6 @@ public final class CustomProblemReporterTests { @Override public void warning(Problem problem) { - System.out.println(problem); this.warnings.add(problem); } } diff --git a/spring-beans/src/test/resources/log4j.xml b/spring-beans/src/test/resources/log4j.xml index 37f573d2ae..6f012e9924 100644 --- a/spring-beans/src/test/resources/log4j.xml +++ b/spring-beans/src/test/resources/log4j.xml @@ -11,21 +11,13 @@ - - - - - - - - - + - + From 3a192a07016d0bc9d6dbc9bc4d12059fa2d221ef Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 12:53:20 +0100 Subject: [PATCH 270/311] Update Eclipse import organization rules The following changes have been made to the JDT UI prefs to conform to existing conventions throughout the codebase: - always favor .* syntax for static imports - always list static imports last Re-run `gradle eclipse` and refresh projects within Eclipse to make this change take effect. --- src/eclipse/org.eclipse.jdt.ui.prefs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/eclipse/org.eclipse.jdt.ui.prefs b/src/eclipse/org.eclipse.jdt.ui.prefs index 4aa12d7db5..7631dce007 100644 --- a/src/eclipse/org.eclipse.jdt.ui.prefs +++ b/src/eclipse/org.eclipse.jdt.ui.prefs @@ -55,8 +55,8 @@ eclipse.preferences.version=1 formatter_profile=_Spring formatter_settings_version=12 org.eclipse.jdt.ui.ignorelowercasenames=true -org.eclipse.jdt.ui.importorder=java;javax;org;com; +org.eclipse.jdt.ui.importorder=java;javax;org;com;\#; org.eclipse.jdt.ui.javadoc=true org.eclipse.jdt.ui.ondemandthreshold=9999 -org.eclipse.jdt.ui.staticondemandthreshold=9999 +org.eclipse.jdt.ui.staticondemandthreshold=1 org.eclipse.jdt.ui.text.custom_code_templates= From 58ab8b691c1d01f9237306a55eb835f01c6705c9 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 12:15:53 +0100 Subject: [PATCH 271/311] Re-enable ignored SecurityManager-related test Prior to this change, CallbacksSecurityTests#testContainerPrivileges was @Ignored because it caused the build to fail under Gradle. After some analysis, the root cause was determined to be the fact that (a) a restrictive SecurityManager is active during the running of this test, and (b), Gradle intercepts System.out and routes it through its internal LogBack-based logging system. LogBack requires a call to Class#getClassLoader when handling logging statements, and the SecurityManager disallows this call, thus raising the error that fails the build. This commit solves the problem by eliminating the System.out.println call in question and removing the @Ignore annotation from the test. The console output was diagnostic in nature anyway, and not required for the successful execution of the test's assertions. Issue: SPR-10074 --- .../support/security/CallbacksSecurityTests.java | 13 +++---------- .../support/security/support/ConstructorBean.java | 4 ++-- 2 files changed, 5 insertions(+), 12 deletions(-) diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java index c8c6595e45..d0439fa93e 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/CallbacksSecurityTests.java @@ -16,12 +16,6 @@ package org.springframework.beans.factory.support.security; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - import java.lang.reflect.Method; import java.net.URL; import java.security.AccessControlContext; @@ -39,8 +33,8 @@ import javax.security.auth.AuthPermission; import javax.security.auth.Subject; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.BeanCreationException; @@ -60,6 +54,8 @@ import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; +import static org.junit.Assert.*; + /** * Security test case. Checks whether the container uses its privileges for its * internal work but does not leak them when touching/calling user code. @@ -456,9 +452,6 @@ public class CallbacksSecurityTests { } @Test - @Ignore("passes under Eclipse, but fails under Gradle with https://gist.github.com/1664133") - // TODO [SPR-10074] passes under Eclipse, but fails under Gradle with - // https://gist.github.com/1664133 public void testContainerPrivileges() throws Exception { AccessControlContext acc = provider.getAccessControlContext(); diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/support/ConstructorBean.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/support/ConstructorBean.java index 0b65929fdd..a68028c592 100644 --- a/spring-beans/src/test/java/org/springframework/beans/factory/support/security/support/ConstructorBean.java +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/security/support/ConstructorBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.springframework.beans.factory.support.security.support; /** @@ -25,6 +26,5 @@ public class ConstructorBean { } public ConstructorBean(Object obj) { - System.out.println("Received object " + obj); } } From 0e8c950f7d57e770d2da6441b836c4ef84623975 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 12:51:32 +0100 Subject: [PATCH 272/311] Re-enable JaxWsSupportTests These tests still fail under Eclipse for unknown reasons, but do work under Gradle, so are thus re-enabled by removing the @Ignore. Issue: SPR-10074 --- .../remoting/jaxws/JaxWsSupportTests.java | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java index 7ae30114de..66637e04b2 100644 --- a/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java +++ b/spring-web/src/test/java/org/springframework/remoting/jaxws/JaxWsSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,6 @@ package org.springframework.remoting.jaxws; -import static org.junit.Assert.*; - import java.net.MalformedURLException; import java.net.URL; @@ -28,7 +26,6 @@ import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceRef; import javax.xml.ws.soap.AddressingFeature; -import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.support.GenericBeanDefinition; @@ -36,12 +33,12 @@ import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.annotation.AnnotationConfigUtils; import org.springframework.context.support.GenericApplicationContext; +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @since 2.5 */ -// TODO [SPR-10074] see https://gist.github.com/1150858 -@Ignore("see https://gist.github.com/1150858") public class JaxWsSupportTests { @Test From 9c2b5b240696431bd5842ed1ea6a66b48f12e197 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 14:19:07 +0100 Subject: [PATCH 273/311] Update @Ignore'd JPA+AspectJ tests Issue: SPR-10074, SPR-10333 --- ...rFactoryWithAspectJWeavingIntegrationTests.java | 14 +++++--------- ...kMultiEntityManagerFactoryIntegrationTests.java | 6 +++--- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java index 20d9e5f029..ec94bba49f 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,17 +19,13 @@ package org.springframework.orm.jpa.openjpa; import org.junit.Ignore; /** - * Test that AspectJ weaving (in particular the currently shipped aspects) work with JPA (see SPR-3873 for more details). + * Test that AspectJ weaving (in particular the currently shipped aspects) work with JPA + * (see SPR-3873 for more details). * * @author Ramnivas Laddad + * @author Chris Beams */ -// TODO [SPR-10074] this test causes gradle to hang. -// When run independently e.g. `./gradlew :spring-orm:test -Dtest.single=OpenJpaEntity...` -// it works fine. When run together with all other tests e.g. `./gradlew :spring-orm:test` -// it hangs on the 'testCanSerializeProxies' test method. Note that this test DOES pass in -// Eclipse, even when the entire 'spring-orm' module is run. Run gradle with '-i' to -// get more details when reproducing the hanging test. -@Ignore("this test causes gradle to hang") +@Ignore("This test causes gradle to hang. See SPR-103333.") public class OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests extends OpenJpaEntityManagerFactoryIntegrationTests { @Override diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java index 78e8f86af5..13d9226bce 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,9 +26,9 @@ import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrat * Toplink-specific JPA tests with multiple EntityManagerFactory instances. * * @author Costin Leau + * @author Chris Beams */ -// TODO [SPR-10074] this test causes gradle to hang. See OJEMFWAJWIT. -@Ignore("this test causes gradle to hang. See OJEMFWAJWIT.") +@Ignore("This test causes gradle to hang. See SPR-103333.") public class TopLinkMultiEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests { From cbe03093ba2529b07ea897945c3a9e5eeac946d0 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 16:09:16 +0100 Subject: [PATCH 274/311] Revert "Revert "Re-enable ignored JMX tests"" This reverts commit cc814519c8c5b943a2f5bb3950b2dde97db854bf. Issue: SPR-8089 Conflicts: spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTestsIgnore.java spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTestsIgnore.java --- .../access/MBeanClientInterceptorTests.java | 14 ++--------- ...=> RemoteMBeanClientInterceptorTests.java} | 13 ++-------- ...a => ConnectorServerFactoryBeanTests.java} | 12 ++------- ...MBeanServerConnectionFactoryBeanTests.java | 25 +++---------------- 4 files changed, 9 insertions(+), 55 deletions(-) rename spring-context/src/test/java/org/springframework/jmx/access/{RemoteMBeanClientInterceptorTestsIgnore.java => RemoteMBeanClientInterceptorTests.java} (77%) rename spring-context/src/test/java/org/springframework/jmx/support/{ConnectorServerFactoryBeanTestsIgnore.java => ConnectorServerFactoryBeanTests.java} (86%) diff --git a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java index 7842ee328c..9fa283af25 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -29,7 +29,6 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.JmxException; @@ -187,16 +186,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } - // TODO [SPR-8089] Clean up ignored JMX tests. - // - // @Ignore should have no effect for JUnit 3.8 tests; however, it appears - // that tests on the CI server -- as well as those in Eclipse -- do in - // fact get ignored. So we leave @Ignore here so that developers can - // easily search for ignored tests. - // - // Once fixed, renamed to test* instead of ignore*. - @Ignore("Requires jmxremote_optional.jar; see comments in AbstractMBeanServerTests for details.") - public void ignoreTestLazyConnectionToRemote() throws Exception { + public void testTestLazyConnectionToRemote() throws Exception { if (!runTests) return; diff --git a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTestsIgnore.java b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java similarity index 77% rename from spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTestsIgnore.java rename to spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java index 7082efec13..aa261ee3f3 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTestsIgnore.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -26,19 +26,10 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; - /** * @author Rob Harrop */ -// TODO [SPR-8089] Clean up ignored JMX tests. -// -// @Ignore should have no effect for JUnit 3.8 tests; however, it appears -// that tests on the CI server -- as well as those in Eclipse -- do in -// fact get ignored. So we leave @Ignore here so that developers can -// easily search for ignored tests. -@Ignore("Requires jmxremote_optional.jar; see comments in AbstractMBeanServerTests for details.") -public class RemoteMBeanClientInterceptorTestsIgnore extends MBeanClientInterceptorTests { +public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTests { private static final String SERVICE_URL = "service:jmx:jmxmp://localhost:9876"; diff --git a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTestsIgnore.java b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java similarity index 86% rename from spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTestsIgnore.java rename to spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java index ef244b085e..1e0787c870 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTestsIgnore.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -28,20 +28,12 @@ import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; import org.springframework.jmx.AbstractMBeanServerTests; /** * @author Rob Harrop */ -// TODO [SPR-8089] Clean up ignored JMX tests. -// -// @Ignore should have no effect for JUnit 3.8 tests; however, it appears -// that tests on the CI server -- as well as those in Eclipse -- do in -// fact get ignored. So we leave @Ignore here so that developers can -// easily search for ignored tests. -@Ignore("Requires jmxremote_optional.jar; see comments in AbstractMBeanServerTests for details.") -public class ConnectorServerFactoryBeanTestsIgnore extends AbstractMBeanServerTests { +public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { private static final String OBJECT_NAME = "spring:type=connector,name=test"; diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java index 598bc73e8c..1203fc4a96 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,7 +23,6 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; -import org.junit.Ignore; import org.springframework.aop.support.AopUtils; import org.springframework.jmx.AbstractMBeanServerTests; @@ -43,16 +42,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe return JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer()); } - // TODO [SPR-8089] Clean up ignored JMX tests. - // - // @Ignore should have no effect for JUnit 3.8 tests; however, it appears - // that tests on the CI server -- as well as those in Eclipse -- do in - // fact get ignored. So we leave @Ignore here so that developers can - // easily search for ignored tests. - // - // Once fixed, renamed to test* instead of ignore*. - @Ignore("Requires jmxremote_optional.jar; see comments in AbstractMBeanServerTests for details.") - public void ignoreTestValidConnection() throws Exception { + public void testTestValidConnection() throws Exception { JMXConnectorServer connectorServer = getConnectorServer(); connectorServer.start(); @@ -85,16 +75,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } - // TODO [SPR-8089] Clean up ignored JMX tests. - // - // @Ignore should have no effect for JUnit 3.8 tests; however, it appears - // that tests on the CI server -- as well as those in Eclipse -- do in - // fact get ignored. So we leave @Ignore here so that developers can - // easily search for ignored tests. - // - // Once fixed, renamed to test* instead of ignore*. - @Ignore("Requires jmxremote_optional.jar; see comments in AbstractMBeanServerTests for details.") - public void ignoreTestWithLazyConnection() throws Exception { + public void testTestWithLazyConnection() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(SERVICE_URL); bean.setConnectOnStartup(false); From 55caf7bdb0b418d64967f057832eba40de7ff825 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 16:10:23 +0100 Subject: [PATCH 275/311] Improve diagnostics for invalid testGroup values --- .../test/java/org/springframework/tests/TestGroup.java | 10 ++++++++-- .../java/org/springframework/tests/TestGroupTests.java | 4 +++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/spring-core/src/test/java/org/springframework/tests/TestGroup.java b/spring-core/src/test/java/org/springframework/tests/TestGroup.java index dcc376eea4..7bd0ccdfd5 100644 --- a/spring-core/src/test/java/org/springframework/tests/TestGroup.java +++ b/spring-core/src/test/java/org/springframework/tests/TestGroup.java @@ -21,6 +21,10 @@ import java.util.EnumSet; import java.util.HashSet; import java.util.Set; +import org.springframework.util.StringUtils; + +import static java.lang.String.*; + /** * A test group used to limit when certain tests are run. * @@ -64,8 +68,10 @@ public enum TestGroup { try { groups.add(valueOf(group.trim().toUpperCase())); } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Unable to find test group '" + group.trim() - + "' when parsing '" + value + "'"); + throw new IllegalArgumentException(format( + "Unable to find test group '%s' when parsing testGroups value: '%s'. " + + "Available groups include: [%s]", group.trim(), value, + StringUtils.arrayToCommaDelimitedString(TestGroup.values()))); } } return groups; diff --git a/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java b/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java index 2b4860fd72..7f9fe924c4 100644 --- a/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java +++ b/spring-core/src/test/java/org/springframework/tests/TestGroupTests.java @@ -62,7 +62,9 @@ public class TestGroupTests { @Test public void parseMissing() throws Exception { thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("Unable to find test group 'missing' when parsing 'performance, missing'"); + thrown.expectMessage("Unable to find test group 'missing' when parsing " + + "testGroups value: 'performance, missing'. Available groups include: " + + "[LONG_RUNNING,PERFORMANCE,JMXMP]"); TestGroup.parse("performance, missing"); } From 10648942c34385d5d64b23e0c9d875d8b03d0d15 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 16:21:21 +0100 Subject: [PATCH 276/311] Update AbstractMBeanServerTests hierarchy to JUnit 4 This commit lays the groundwork for introducing TestGroup#JMXMP and related assumptions in select JMX-related tests in a subsequent commit; JUnit assumptions require JUnit 4+ to function properly, so the entire AbstractMBeanServerTests hierarchy must be moved over to JUnit 4+ style. Issue: SPR-8089 --- .../jmx/AbstractMBeanServerTests.java | 17 +++++---- .../access/MBeanClientInterceptorTests.java | 14 ++++++++ .../RemoteMBeanClientInterceptorTests.java | 1 + .../export/CustomEditorConfigurerTests.java | 5 +++ .../export/MBeanExporterOperationsTests.java | 2 ++ .../jmx/export/MBeanExporterTests.java | 36 +++++++++++++++++++ .../jmx/export/NotificationListenerTests.java | 16 +++++++++ .../export/NotificationPublisherTests.java | 8 +++++ .../PropertyPlaceholderConfigurerTests.java | 8 ++++- .../AnnotationMetadataAssemblerTests.java | 13 +++++-- .../assembler/AbstractJmxAssemblerTests.java | 17 +++++++++ .../AbstractMetadataAssemblerTests.java | 18 ++++++++++ ...aceBasedMBeanInfoAssemblerCustomTests.java | 8 ++++- ...aceBasedMBeanInfoAssemblerMappedTests.java | 12 ++++++- ...ExclusionMBeanInfoAssemblerComboTests.java | 9 ++++- ...xclusionMBeanInfoAssemblerMappedTests.java | 9 ++++- ...usionMBeanInfoAssemblerNotMappedTests.java | 9 ++++- ...ethodExclusionMBeanInfoAssemblerTests.java | 8 ++++- ...ameBasedMBeanInfoAssemblerMappedTests.java | 13 +++++-- ...ethodNameBasedMBeanInfoAssemblerTests.java | 7 ++++ .../ConnectorServerFactoryBeanTests.java | 6 ++++ ...MBeanServerConnectionFactoryBeanTests.java | 4 +++ 22 files changed, 222 insertions(+), 18 deletions(-) diff --git a/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java index 12dbf05a50..8010dca2e7 100644 --- a/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,13 +20,15 @@ import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; -import junit.framework.TestCase; - +import org.junit.After; +import org.junit.Before; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.util.MBeanTestUtils; +import static org.junit.Assert.*; + /** * Note: the JMX test suite requires the presence of the * {@code jmxremote_optional.jar} in your classpath. Thus, if you @@ -40,12 +42,13 @@ import org.springframework.util.MBeanTestUtils; * @author Rob Harrop * @author Juergen Hoeller * @author Sam Brannen + * @author Chris Beams */ -public abstract class AbstractMBeanServerTests extends TestCase { +public abstract class AbstractMBeanServerTests { protected MBeanServer server; - @Override + @Before public final void setUp() throws Exception { this.server = MBeanServerFactory.createMBeanServer(); try { @@ -64,8 +67,8 @@ public abstract class AbstractMBeanServerTests extends TestCase { return ctx; } - @Override - protected void tearDown() throws Exception { + @After + public void tearDown() throws Exception { releaseServer(); onTearDown(); } diff --git a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java index 9fa283af25..c8d7b1c6b0 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java @@ -29,6 +29,7 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; +import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.JmxException; @@ -40,6 +41,7 @@ import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssem * @author Rob Harrop * @author Juergen Hoeller * @author Sam Brannen + * @author Chris Beams */ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { @@ -77,6 +79,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { return (IJmxTestBean) factory.getObject(); } + @Test public void testProxyClassIsDifferent() throws Exception { if (!runTests) return; @@ -84,6 +87,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertTrue("The proxy class should be different than the base class", (proxy.getClass() != IJmxTestBean.class)); } + @Test public void testDifferentProxiesSameClass() throws Exception { if (!runTests) return; @@ -94,6 +98,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertSame("The proxy classes should be the same", proxy1.getClass(), proxy2.getClass()); } + @Test public void testGetAttributeValue() throws Exception { if (!runTests) return; @@ -102,6 +107,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The age should be 100", 100, age); } + @Test public void testSetAttributeValue() throws Exception { if (!runTests) return; @@ -110,6 +116,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The name of the bean should have been updated", "Rob Harrop", target.getName()); } + @Test public void testSetAttributeValueWithRuntimeException() throws Exception { if (!runTests) return; @@ -122,6 +129,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testSetAttributeValueWithCheckedException() throws Exception { if (!runTests) return; @@ -134,6 +142,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testSetAttributeValueWithIOException() throws Exception { if (!runTests) return; @@ -146,6 +155,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testSetReadOnlyAttribute() throws Exception { if (!runTests) return; @@ -158,6 +168,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testInvokeNoArgs() throws Exception { if (!runTests) return; @@ -166,6 +177,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The operation should return 1", 1, result); } + @Test public void testInvokeArgs() throws Exception { if (!runTests) return; @@ -174,6 +186,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { assertEquals("The operation should return 3", 3, result); } + @Test public void testInvokeUnexposedMethodWithException() throws Exception { if (!runTests) return; @@ -186,6 +199,7 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { } } + @Test public void testTestLazyConnectionToRemote() throws Exception { if (!runTests) return; diff --git a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java index aa261ee3f3..c36e788f1e 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java @@ -28,6 +28,7 @@ import javax.management.remote.JMXServiceURL; /** * @author Rob Harrop + * @author Chris Beams */ public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTests { diff --git a/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java index 2c71236d78..1901901114 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java @@ -22,8 +22,11 @@ import java.util.Date; import javax.management.ObjectName; +import org.junit.Test; import org.springframework.jmx.AbstractJmxTests; +import static org.junit.Assert.*; + /** * @author Rob Harrop */ @@ -36,6 +39,7 @@ public class CustomEditorConfigurerTests extends AbstractJmxTests { return "org/springframework/jmx/export/customConfigurer.xml"; } + @Test public void testDatesInJmx() throws Exception { // System.out.println(getServer().getClass().getName()); ObjectName oname = new ObjectName("bean:name=dateRange"); @@ -47,6 +51,7 @@ public class CustomEditorConfigurerTests extends AbstractJmxTests { assertEquals("endDate ", getEndDate(), endJmx); } + @Test public void testGetDates() throws Exception { DateRange dr = (DateRange) getContext().getBean("dateRange"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java index 59740fa0db..f2bee32668 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterOperationsTests.java @@ -28,6 +28,8 @@ import org.springframework.jmx.JmxTestBean; import org.springframework.jmx.export.naming.ObjectNamingStrategy; import org.springframework.jmx.support.ObjectNameManager; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Juergen Hoeller diff --git a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java index 2d7d9e2639..c08a9f73b2 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/MBeanExporterTests.java @@ -33,6 +33,7 @@ import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; @@ -50,6 +51,8 @@ import org.springframework.jmx.support.RegistrationPolicy; import org.springframework.tests.aop.interceptor.NopInterceptor; import org.springframework.tests.sample.beans.TestBean; +import static org.junit.Assert.*; + /** * Integration tests for the {@link MBeanExporter} class. * @@ -66,6 +69,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { private static final String OBJECT_NAME = "spring:test=jmxMBeanAdaptor"; @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNonNotificationListenerType() throws Exception { Map listeners = new HashMap(); // put a non-NotificationListener instance in as a value... @@ -80,6 +84,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNullNotificationListenerType() throws Exception { Map listeners = new HashMap(); // put null in as a value... @@ -94,6 +99,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerForNonExistentMBean() throws Exception { Map listeners = new HashMap(); NotificationListener dummyListener = new NotificationListener() { @@ -117,6 +123,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testWithSuppliedMBeanServer() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(getBeanMap()); @@ -127,6 +134,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } /** Fails if JVM platform MBean server has been started already + @Test public void testWithLocatedMBeanServer() throws Exception { MBeanExporter adaptor = new MBeanExporter(); adaptor.setBeans(getBeanMap()); @@ -136,6 +144,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } */ + @Test public void testUserCreatedMBeanRegWithDynamicMBean() throws Exception { Map map = new HashMap(); map.put("spring:name=dynBean", new TestDynamicMBean()); @@ -153,6 +162,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertFalse("Assembler should not have been invoked", asm.invoked); } + @Test public void testAutodetectMBeans() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("autodetectMBeans.xml", getClass())); @@ -170,6 +180,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testAutodetectWithExclude() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("autodetectMBeans.xml", getClass())); @@ -189,6 +200,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testAutodetectLazyMBeans() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("autodetectLazyMBeans.xml", getClass())); @@ -210,6 +222,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testAutodetectNoMBeans() throws Exception { DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(bf).loadBeanDefinitions(new ClassPathResource("autodetectNoMBeans.xml", getClass())); @@ -220,6 +233,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testWithMBeanExporterListeners() throws Exception { MockMBeanExporterListener listener1 = new MockMBeanExporterListener(); MockMBeanExporterListener listener2 = new MockMBeanExporterListener(); @@ -235,6 +249,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertListener(listener2); } + @Test public void testExportJdkProxy() throws Exception { JmxTestBean bean = new JmxTestBean(); bean.setName("Rob Harrop"); @@ -260,6 +275,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertEquals("Rob Harrop", nameValue); } + @Test public void testSelfNaming() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); SelfNamingTestBean testBean = new SelfNamingTestBean(); @@ -278,6 +294,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertNotNull(instance); } + @Test public void testRegisterIgnoreExisting() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); @@ -311,6 +328,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertEquals("Rob Harrop", server.getAttribute(objectName, "Name")); } + @Test public void testRegisterReplaceExisting() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(OBJECT_NAME); @@ -339,6 +357,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertEquals("Sally Greenwood", server.getAttribute(objectName, "Name")); } + @Test public void testWithExposeClassLoader() throws Exception { String name = "Rob Harrop"; String otherName = "Juergen Hoeller"; @@ -368,6 +387,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { assertEquals("Incorrect updated name.", otherName, bean.getName()); } + @Test public void testBonaFideMBeanIsNotExportedWhenAutodetectIsTotallyTurnedOff() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); @@ -386,6 +406,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { exporter.afterPropertiesSet(); } + @Test public void testOnlyBonaFideMBeanIsExportedWhenAutodetectIsMBeanOnly() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); @@ -405,6 +426,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { ObjectNameManager.getInstance(exportedBeanName)); } + @Test public void testBonaFideMBeanAndRegularBeanExporterWithAutodetectAll() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); @@ -428,6 +450,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { ObjectNameManager.getInstance(notToBeExportedBeanName)); } + @Test public void testBonaFideMBeanIsNotExportedWithAutodetectAssembler() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); @@ -450,6 +473,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { /** * Want to ensure that said MBean is not exported twice. */ + @Test public void testBonaFideMBeanExplicitlyExportedAndAutodetectionIsOn() throws Exception { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(Person.class); DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); @@ -468,6 +492,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { ObjectNameManager.getInstance(OBJECT_NAME)); } + @Test public void testSetAutodetectModeToOutOfRangeNegativeValue() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -478,6 +503,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeToOutOfRangePositiveValue() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -488,6 +514,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToNull() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -498,6 +525,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToAnEmptyString() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -508,6 +536,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToAWhitespacedString() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -518,6 +547,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testSetAutodetectModeNameToARubbishValue() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -528,6 +558,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testNotRunningInBeanFactoryAndPassedBeanNameToExport() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -541,6 +572,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { } } + @Test public void testNotRunningInBeanFactoryAndAutodetectionIsOn() throws Exception { try { MBeanExporter exporter = new MBeanExporter(); @@ -555,6 +587,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { /** * SPR-2158 */ + @Test public void testMBeanIsNotUnregisteredSpuriouslyIfSomeExternalProcessHasUnregisteredMBean() throws Exception { MBeanExporter exporter = new MBeanExporter(); exporter.setBeans(getBeanMap()); @@ -574,6 +607,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { /** * SPR-3302 */ + @Test public void testBeanNameCanBeUsedInNotificationListenersMap() throws Exception { String beanName = "charlesDexterWard"; BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class); @@ -595,6 +629,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { exporter.afterPropertiesSet(); } + @Test public void testWildcardCanBeUsedInNotificationListenersMap() throws Exception { String beanName = "charlesDexterWard"; BeanDefinitionBuilder testBean = BeanDefinitionBuilder.rootBeanDefinition(JmxTestBean.class); @@ -619,6 +654,7 @@ public final class MBeanExporterTests extends AbstractMBeanServerTests { /* * SPR-3625 */ + @Test public void testMBeanIsUnregisteredForRuntimeExceptionDuringInitialization() throws Exception { BeanDefinitionBuilder builder1 = BeanDefinitionBuilder.rootBeanDefinition(Person.class); BeanDefinitionBuilder builder2 = BeanDefinitionBuilder diff --git a/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java index 4524412307..a6423dcee8 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/NotificationListenerTests.java @@ -26,6 +26,7 @@ import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectName; +import org.junit.Test; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.jmx.JmxTestBean; @@ -33,6 +34,8 @@ import org.springframework.jmx.access.NotificationListenerRegistrar; import org.springframework.jmx.export.naming.SelfNaming; import org.springframework.jmx.support.ObjectNameManager; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Mark Fisher @@ -41,6 +44,7 @@ import org.springframework.jmx.support.ObjectNameManager; public class NotificationListenerTests extends AbstractMBeanServerTests { @SuppressWarnings({"rawtypes", "unchecked"}) + @Test public void testRegisterNotificationListenerForMBean() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); @@ -66,6 +70,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerWithWildcard() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); @@ -90,6 +95,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertEquals("Listener not notified", 1, listener.getCount(attributeName)); } + @Test public void testRegisterNotificationListenerWithHandback() throws Exception { String objectName = "spring:name=Test"; JmxTestBean bean = new JmxTestBean(); @@ -120,6 +126,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertEquals("Handback object not transmitted correctly", handback, listener.getLastHandback(attributeName)); } + @Test public void testRegisterNotificationListenerForAllMBeans() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); @@ -146,6 +153,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings("serial") + @Test public void testRegisterNotificationListenerWithFilter() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); @@ -186,6 +194,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertEquals("Listener incorrectly notified for Age", 0, listener.getCount(ageAttribute)); } + @Test public void testCreationWithNoNotificationListenerSet() { try { new NotificationListenerBean().afterPropertiesSet(); @@ -195,6 +204,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerWithBeanNameAndBeanNameInBeansMap() throws Exception { String beanName = "testBean"; ObjectName objectName = ObjectName.getInstance("spring:name=Test"); @@ -225,6 +235,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerWithBeanNameAndBeanInstanceInBeansMap() throws Exception { String beanName = "testBean"; ObjectName objectName = ObjectName.getInstance("spring:name=Test"); @@ -255,6 +266,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerWithBeanNameBeforeObjectNameMappedToSameBeanInstance() throws Exception { String beanName = "testBean"; ObjectName objectName = ObjectName.getInstance("spring:name=Test"); @@ -286,6 +298,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerWithObjectNameBeforeBeanNameMappedToSameBeanInstance() throws Exception { String beanName = "testBean"; ObjectName objectName = ObjectName.getInstance("spring:name=Test"); @@ -317,6 +330,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { } @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test public void testRegisterNotificationListenerWithTwoBeanNamesMappedToDifferentBeanInstances() throws Exception { String beanName1 = "testBean1"; String beanName2 = "testBean2"; @@ -359,6 +373,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertEquals("Listener not notified for testBean2", 2, listener.getCount("Age")); } + @Test public void testNotificationListenerRegistrar() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); JmxTestBean bean = new JmxTestBean(); @@ -391,6 +406,7 @@ public class NotificationListenerTests extends AbstractMBeanServerTests { assertEquals("Listener notified after destruction", 1, listener.getCount(attributeName)); } + @Test public void testNotificationListenerRegistrarWithMultipleNames() throws Exception { ObjectName objectName = ObjectName.getInstance("spring:name=Test"); ObjectName objectName2 = ObjectName.getInstance("spring:name=Test2"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java b/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java index a6abda7ed2..2237fcc155 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java @@ -32,12 +32,15 @@ import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationListener; import javax.management.ReflectionException; +import org.junit.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.jmx.AbstractMBeanServerTests; import org.springframework.jmx.export.notification.NotificationPublisher; import org.springframework.jmx.export.notification.NotificationPublisherAware; import org.springframework.jmx.support.ObjectNameManager; +import static org.junit.Assert.*; + /** * Integration tests for the Spring JMX {@link NotificationPublisher} functionality. * @@ -48,6 +51,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { private CountingNotificationListener listener = new CountingNotificationListener(); + @Test public void testSimpleBean() throws Exception { // start the MBeanExporter ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml"); @@ -60,6 +64,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { assertEquals("Notification not sent", 1, listener.count); } + @Test public void testSimpleBeanRegisteredManually() throws Exception { // start the MBeanExporter ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml"); @@ -74,6 +79,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { assertEquals("Notification not sent", 1, listener.count); } + @Test public void testMBean() throws Exception { // start the MBeanExporter ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml"); @@ -86,6 +92,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { } /* + @Test public void testStandardMBean() throws Exception { // start the MBeanExporter ApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/notificationPublisherTests.xml"); @@ -97,6 +104,7 @@ public class NotificationPublisherTests extends AbstractMBeanServerTests { } */ + @Test public void testLazyInit() throws Exception { // start the MBeanExporter ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherLazyTests.xml"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java index c95000c59d..256372eb1b 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -18,11 +18,15 @@ package org.springframework.jmx.export; import javax.management.ObjectName; +import org.junit.Test; import org.springframework.jmx.AbstractJmxTests; import org.springframework.jmx.IJmxTestBean; +import static org.junit.Assert.*; + /** * @author Rob Harrop + * @author Chris Beams */ public class PropertyPlaceholderConfigurerTests extends AbstractJmxTests { @@ -31,6 +35,7 @@ public class PropertyPlaceholderConfigurerTests extends AbstractJmxTests { return "org/springframework/jmx/export/propertyPlaceholderConfigurer.xml"; } + @Test public void testPropertiesReplaced() { IJmxTestBean bean = (IJmxTestBean) getContext().getBean("testBean"); @@ -38,6 +43,7 @@ public class PropertyPlaceholderConfigurerTests extends AbstractJmxTests { assertEquals("Age is incorrect", 100, bean.getAge()); } + @Test public void testPropertiesCorrectInJmx() throws Exception { ObjectName oname = new ObjectName("bean:name=proxyTestBean1"); Object name = getServer().getAttribute(oname, "Name"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java index d74787b7f8..11c68dcb99 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -20,15 +20,22 @@ import javax.management.modelmbean.ModelMBeanInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; +import org.junit.Test; import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.export.assembler.AbstractMetadataAssemblerTests; import org.springframework.jmx.export.metadata.JmxAttributeSource; -/** @author Rob Harrop */ +import static org.junit.Assert.*; + +/** + * @author Rob Harrop + * @author Chris Beams + */ public class AnnotationMetadataAssemblerTests extends AbstractMetadataAssemblerTests { private static final String OBJECT_NAME = "bean:name=testBean4"; + @Test public void testAttributeFromInterface() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute("Colour"); @@ -36,12 +43,14 @@ public class AnnotationMetadataAssemblerTests extends AbstractMetadataAssemblerT assertTrue("The name attribute should be readable", attr.isReadable()); } + @Test public void testOperationFromInterface() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanOperationInfo op = inf.getOperation("fromInterface"); assertNotNull(op); } + @Test public void testOperationOnGetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanOperationInfo op = inf.getOperation("getExpensiveToCalculate"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java index 2c4a06e0be..42962c5f64 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java @@ -28,12 +28,16 @@ import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; +import org.junit.Test; import org.springframework.jmx.AbstractJmxTests; import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.support.ObjectNameManager; +import static org.junit.Assert.*; + /** * @author Rob Harrop + * @author Chris Beams */ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { @@ -43,12 +47,14 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { protected abstract String getObjectName(); + @Test public void testMBeanRegistration() throws Exception { // beans are registered at this point - just grab them from the server ObjectInstance instance = getObjectInstance(); assertNotNull("Bean should not be null", instance); } + @Test public void testRegisterOperations() throws Exception { IJmxTestBean bean = getBean(); assertNotNull(bean); @@ -57,6 +63,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { getExpectedOperationCount(), inf.getOperations().length); } + @Test public void testRegisterAttributes() throws Exception { IJmxTestBean bean = getBean(); assertNotNull(bean); @@ -65,11 +72,13 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { getExpectedAttributeCount(), inf.getAttributes().length); } + @Test public void testGetMBeanInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); assertNotNull("MBeanInfo should not be null", info); } + @Test public void testGetMBeanAttributeInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanAttributeInfo[] inf = info.getAttributes(); @@ -84,6 +93,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { } } + @Test public void testGetMBeanOperationInfo() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); MBeanOperationInfo[] inf = info.getOperations(); @@ -98,6 +108,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { } } + @Test public void testDescriptionNotNull() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); @@ -105,6 +116,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { info.getDescription()); } + @Test public void testSetAttribute() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); getServer().setAttribute(objectName, new Attribute(NAME_ATTRIBUTE, "Rob Harrop")); @@ -112,6 +124,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { assertEquals("Rob Harrop", bean.getName()); } + @Test public void testGetAttribute() throws Exception { ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); getBean().setName("John Smith"); @@ -119,6 +132,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { assertEquals("Incorrect result", "John Smith", val); } + @Test public void testOperationInvocation() throws Exception{ ObjectName objectName = ObjectNameManager.getInstance(getObjectName()); Object result = getServer().invoke(objectName, "add", @@ -126,6 +140,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { assertEquals("Incorrect result", new Integer(50), result); } + @Test public void testAttributeInfoHasDescriptors() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); @@ -141,6 +156,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { desc.getFieldValue("setMethod")); } + @Test public void testAttributeHasCorrespondingOperations() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); @@ -159,6 +175,7 @@ public abstract class AbstractJmxAssemblerTests extends AbstractJmxTests { assertEquals("set operation should have role \"setter\"", "setter", set.getDescriptor().getFieldValue("role")); } + @Test public void testNotificationMetadata() throws Exception { ModelMBeanInfo info = (ModelMBeanInfo) getMBeanInfo(); MBeanNotificationInfo[] notifications = info.getNotifications(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java index 99cefe7158..0c3ece7839 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerTests.java @@ -26,6 +26,7 @@ import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; import javax.management.modelmbean.ModelMBeanOperationInfo; +import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; import org.springframework.jmx.IJmxTestBean; import org.springframework.jmx.JmxTestBean; @@ -34,6 +35,8 @@ import org.springframework.jmx.export.metadata.JmxAttributeSource; import org.springframework.jmx.support.ObjectNameManager; import org.springframework.tests.aop.interceptor.NopInterceptor; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Chris Beams @@ -44,12 +47,14 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble protected static final String CACHE_ENTRIES_METRIC = "CacheEntries"; + @Test public void testDescription() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); assertEquals("The descriptions are not the same", "My Managed Bean", info.getDescription()); } + @Test public void testAttributeDescriptionOnSetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(AGE_ATTRIBUTE); @@ -57,6 +62,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble "The Age Attribute", attr.getDescription()); } + @Test public void testAttributeDescriptionOnGetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(NAME_ATTRIBUTE); @@ -67,12 +73,14 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble /** * Tests the situation where the attribute is only defined on the getter. */ + @Test public void testReadOnlyAttribute() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(AGE_ATTRIBUTE); assertFalse("The age attribute should not be writable", attr.isWritable()); } + @Test public void testReadWriteAttribute() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute(NAME_ATTRIBUTE); @@ -83,6 +91,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble /** * Tests the situation where the property only has a getter. */ + @Test public void testWithOnlySetter() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = inf.getAttribute("NickName"); @@ -92,12 +101,14 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble /** * Tests the situation where the property only has a setter. */ + @Test public void testWithOnlyGetter() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute("Superman"); assertNotNull("Attribute should not be null", attr); } + @Test public void testManagedResourceDescriptor() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getMBeanDescriptor(); @@ -111,6 +122,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble assertEquals("Persist Name should be bar", "bar.jmx", desc.getFieldValue("persistName")); } + @Test public void testAttributeDescriptor() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getAttribute(NAME_ATTRIBUTE).getDescriptor(); @@ -121,6 +133,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble assertEquals("Persist Period should be 300", "300", desc.getFieldValue("persistPeriod")); } + @Test public void testOperationDescriptor() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getOperation("myOperation").getDescriptor(); @@ -129,6 +142,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble assertEquals("Role should be \"operation\"", "operation", desc.getFieldValue("role")); } + @Test public void testOperationParameterMetadata() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanOperationInfo oper = info.getOperation("add"); @@ -142,6 +156,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble assertEquals("Incorrect type for y param", int.class.getName(), params[1].getType()); } + @Test public void testWithCglibProxy() throws Exception { IJmxTestBean tb = createJmxTestBean(); ProxyFactory pf = new ProxyFactory(); @@ -169,6 +184,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble assertTrue("Not included in autodetection", assembler.includeBean(proxy.getClass(), "some bean name")); } + @Test public void testMetricDescription() throws Exception { ModelMBeanInfo inf = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo metric = inf.getAttribute(QUEUE_SIZE_METRIC); @@ -179,6 +195,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble "The QueueSize metric", operation.getDescription()); } + @Test public void testMetricDescriptor() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getAttribute(QUEUE_SIZE_METRIC).getDescriptor(); @@ -191,6 +208,7 @@ public abstract class AbstractMetadataAssemblerTests extends AbstractJmxAssemble assertEquals("Metric Category should be utilization", "utilization",desc.getFieldValue("metricCategory")); } + @Test public void testMetricDescriptorDefaults() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); Descriptor desc = info.getAttribute(CACHE_ENTRIES_METRIC).getDescriptor(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java index d4034ed449..e7bb1d68c9 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerCustomTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -19,8 +19,13 @@ package org.springframework.jmx.export.assembler; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; + +import static org.junit.Assert.*; + /** * @author Rob Harrop + * @author Chris Beams */ public class InterfaceBasedMBeanInfoAssemblerCustomTests extends AbstractJmxAssemblerTests { @@ -48,6 +53,7 @@ public class InterfaceBasedMBeanInfoAssemblerCustomTests extends AbstractJmxAsse return assembler; } + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java index 5cd8488eb7..1a485f377e 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/InterfaceBasedMBeanInfoAssemblerMappedTests.java @@ -22,13 +22,19 @@ import javax.management.MBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; + +import static org.junit.Assert.*; + /** * @author Rob Harrop + * @author Chris Beams */ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAssemblerTests { protected static final String OBJECT_NAME = "bean:name=testBean4"; + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); @@ -37,6 +43,7 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse assertFalse("Age is not writable", attr.isWritable()); } + @Test public void testWithUnknownClass() throws Exception { try { getWithMapping("com.foo.bar.Unknown"); @@ -47,6 +54,7 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse } } + @Test public void testWithNonInterface() throws Exception { try { getWithMapping("JmxTestBean"); @@ -57,7 +65,8 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse } } - public void ignoreTestWithFallThrough() throws Exception { + @Test + public void testWithFallThrough() throws Exception { InterfaceBasedMBeanInfoAssembler assembler = getWithMapping("foobar", "org.springframework.jmx.export.assembler.ICustomJmxBean"); assembler.setManagedInterfaces(new Class[] {IAdditionalTestMethods.class}); @@ -68,6 +77,7 @@ public class InterfaceBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAsse assertNickName(attr); } + @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java index 2c2a8618eb..ea234b09e8 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerComboTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,14 +22,20 @@ import javax.management.MBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; + +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @author Rob Harrop + * @author Chris Beams */ public class MethodExclusionMBeanInfoAssemblerComboTests extends AbstractJmxAssemblerTests { protected static final String OBJECT_NAME = "bean:name=testBean4"; + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); @@ -37,6 +43,7 @@ public class MethodExclusionMBeanInfoAssemblerComboTests extends AbstractJmxAsse assertFalse("Age is not writable", attr.isWritable()); } + @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java index 35fe108270..aa1e2d57c2 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerMappedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,13 +22,19 @@ import javax.management.MBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; + +import static org.junit.Assert.*; + /** * @author Rob Harrop + * @author Chris Beams */ public class MethodExclusionMBeanInfoAssemblerMappedTests extends AbstractJmxAssemblerTests { protected static final String OBJECT_NAME = "bean:name=testBean4"; + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); @@ -36,6 +42,7 @@ public class MethodExclusionMBeanInfoAssemblerMappedTests extends AbstractJmxAss assertFalse("Age is not writable", attr.isWritable()); } + @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java index f037d87bcb..6b12c74d97 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerNotMappedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,14 +22,20 @@ import javax.management.MBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; + +import static org.junit.Assert.*; + /** * @author Juergen Hoeller * @author Rob Harrop + * @author Chris Beams */ public class MethodExclusionMBeanInfoAssemblerNotMappedTests extends AbstractJmxAssemblerTests { protected static final String OBJECT_NAME = "bean:name=testBean4"; + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); @@ -37,6 +43,7 @@ public class MethodExclusionMBeanInfoAssemblerNotMappedTests extends AbstractJmx assertTrue("Age is not writable", attr.isWritable()); } + @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java index 8a49293006..53335e50d7 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodExclusionMBeanInfoAssemblerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,11 +22,15 @@ import java.util.Properties; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; import org.springframework.jmx.JmxTestBean; +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author Rick Evans + * @author Chris Beams */ public class MethodExclusionMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests { @@ -60,6 +64,7 @@ public class MethodExclusionMBeanInfoAssemblerTests extends AbstractJmxAssembler return assembler; } + @Test public void testSupermanIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute("Superman"); @@ -71,6 +76,7 @@ public class MethodExclusionMBeanInfoAssemblerTests extends AbstractJmxAssembler /* * http://opensource.atlassian.com/projects/spring/browse/SPR-2754 */ + @Test public void testIsNotIgnoredDoesntIgnoreUnspecifiedBeanMethods() throws Exception { final String beanKey = "myTestBean"; MethodExclusionMBeanInfoAssembler assembler = new MethodExclusionMBeanInfoAssembler(); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java index 062a45febd..10b1985515 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of @@ -16,18 +16,25 @@ package org.springframework.jmx.export.assembler; +import java.util.Properties; + import javax.management.MBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; -import java.util.Properties; + +import org.junit.Test; + +import static org.junit.Assert.*; /** * @author Rob Harrop + * @author Chris Beams */ public class MethodNameBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAssemblerTests { protected static final String OBJECT_NAME = "bean:name=testBean4"; + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); @@ -36,6 +43,7 @@ public class MethodNameBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAss assertFalse("Age is not writable", attr.isWritable()); } + @Test public void testWithFallThrough() throws Exception { MethodNameBasedMBeanInfoAssembler assembler = getWithMapping("foobar", "add,myOperation,getName,setName,getAge"); @@ -47,6 +55,7 @@ public class MethodNameBasedMBeanInfoAssemblerMappedTests extends AbstractJmxAss assertNickName(attr); } + @Test public void testNickNameIsExposed() throws Exception { ModelMBeanInfo inf = (ModelMBeanInfo) getMBeanInfo(); MBeanAttributeInfo attr = inf.getAttribute("NickName"); diff --git a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java index 72da54f6f3..d85f42b508 100644 --- a/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java @@ -20,9 +20,14 @@ import javax.management.MBeanOperationInfo; import javax.management.modelmbean.ModelMBeanAttributeInfo; import javax.management.modelmbean.ModelMBeanInfo; +import org.junit.Test; + +import static org.junit.Assert.*; + /** * @author Rob Harrop * @author David Boden + * @author Chris Beams */ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssemblerTests { @@ -50,6 +55,7 @@ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssembler return assembler; } + @Test public void testGetAgeIsReadOnly() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); ModelMBeanAttributeInfo attr = info.getAttribute(AGE_ATTRIBUTE); @@ -58,6 +64,7 @@ public class MethodNameBasedMBeanInfoAssemblerTests extends AbstractJmxAssembler assertFalse(attr.isWritable()); } + @Test public void testSetNameParameterIsNamed() throws Exception { ModelMBeanInfo info = getMBeanInfoFromAssembler(); diff --git a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java index 1e0787c870..6bf72b5dbf 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java @@ -28,15 +28,18 @@ import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; +import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; /** * @author Rob Harrop + * @author Chris Beams */ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { private static final String OBJECT_NAME = "spring:type=connector,name=test"; + @Test public void testStartupWithLocatedServer() throws Exception { ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean(); bean.afterPropertiesSet(); @@ -48,6 +51,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { } } + @Test public void testStartupWithSuppliedServer() throws Exception { //Added a brief snooze here - seems to fix occasional //java.net.BindException: Address already in use errors @@ -64,6 +68,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { } } + @Test public void testRegisterWithMBeanServer() throws Exception { //Added a brief snooze here - seems to fix occasional //java.net.BindException: Address already in use errors @@ -81,6 +86,7 @@ public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { } } + @Test public void testNoRegisterWithMBeanServer() throws Exception { ConnectorServerFactoryBean bean = new ConnectorServerFactoryBean(); bean.afterPropertiesSet(); diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java index 1203fc4a96..0a346b6fc1 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java @@ -23,6 +23,7 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; +import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.jmx.AbstractMBeanServerTests; @@ -42,6 +43,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe return JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer()); } + @Test public void testTestValidConnection() throws Exception { JMXConnectorServer connectorServer = getConnectorServer(); connectorServer.start(); @@ -65,6 +67,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } + @Test public void testWithNoServiceUrl() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); try { @@ -97,6 +100,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } + @Test public void testWithLazyConnectionAndNoAccess() throws Exception { MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(SERVICE_URL); From 9a48c10dcb903d3410b1114e432a48d62752b526 Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Tue, 26 Feb 2013 16:24:43 +0100 Subject: [PATCH 277/311] Segregate tests that depend on the jmxmp: protocol This commit introduces TestGroup#JMXMP and adds assumptions to related tests accordingly. These tests require the jmxoptional_remote jar on the classpath, and are run nightly in the SPR-PERF build. Issue: SPR-8089 --- .../jmx/AbstractMBeanServerTests.java | 17 ++++++++++------- .../access/MBeanClientInterceptorTests.java | 6 ++++++ .../RemoteMBeanClientInterceptorTests.java | 14 ++++++++++++-- .../ConnectorServerFactoryBeanTests.java | 18 ++++++++++++++++++ .../MBeanServerConnectionFactoryBeanTests.java | 7 +++++++ .../org/springframework/tests/TestGroup.java | 8 +++++++- 6 files changed, 60 insertions(+), 10 deletions(-) diff --git a/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java index 8010dca2e7..ab05a3ea6e 100644 --- a/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/AbstractMBeanServerTests.java @@ -25,18 +25,21 @@ import org.junit.Before; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericApplicationContext; +import org.springframework.tests.TestGroup; import org.springframework.util.MBeanTestUtils; import static org.junit.Assert.*; /** - * Note: the JMX test suite requires the presence of the - * {@code jmxremote_optional.jar} in your classpath. Thus, if you - * run into the "Unsupported protocol: jmxmp" error, you will - * need to download the - * JMX Remote API 1.0.1_04 Reference Implementation - * from Oracle and extract {@code jmxremote_optional.jar} into your - * classpath, for example in the {@code lib/ext} folder of your JVM. + * Note: certain tests throughout this hierarchy require the presence of + * the {@code jmxremote_optional.jar} in your classpath. For this reason, these tests are + * run only if {@link TestGroup#JMXMP} is enabled. If you wish to run these tests, follow + * the instructions in the TestGroup class to enable JMXMP tests. If you run into the + * "Unsupported protocol: jmxmp" error, you will need to download the + * + * JMX Remote API 1.0.1_04 Reference Implementation from Oracle and extract + * {@code jmxremote_optional.jar} into your classpath, for example in the {@code lib/ext} + * folder of your JVM. * See also EBR-349. * * @author Rob Harrop diff --git a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java index c8d7b1c6b0..e1bd521a1d 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/MBeanClientInterceptorTests.java @@ -36,6 +36,10 @@ import org.springframework.jmx.JmxException; import org.springframework.jmx.JmxTestBean; import org.springframework.jmx.export.MBeanExporter; import org.springframework.jmx.export.assembler.AbstractReflectiveMBeanInfoAssembler; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; + +import static org.junit.Assert.*; /** * @author Rob Harrop @@ -204,6 +208,8 @@ public class MBeanClientInterceptorTests extends AbstractMBeanServerTests { if (!runTests) return; + Assume.group(TestGroup.JMXMP); + JMXServiceURL url = new JMXServiceURL("service:jmx:jmxmp://localhost:9876"); JMXConnectorServer connector = JMXConnectorServerFactory.newJMXConnectorServer(url, null, getServer()); diff --git a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java index c36e788f1e..74a29b0be0 100644 --- a/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/access/RemoteMBeanClientInterceptorTests.java @@ -26,6 +26,9 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; + /** * @author Rob Harrop * @author Chris Beams @@ -40,6 +43,9 @@ public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTes @Override public void onSetUp() throws Exception { + runTests = false; + Assume.group(TestGroup.JMXMP); + runTests = true; super.onSetUp(); this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(getServiceUrl(), null, getServer()); try { @@ -65,8 +71,12 @@ public class RemoteMBeanClientInterceptorTests extends MBeanClientInterceptorTes if (this.connector != null) { this.connector.close(); } - this.connectorServer.stop(); - super.tearDown(); + if (this.connectorServer != null) { + this.connectorServer.stop(); + } + if (runTests) { + super.tearDown(); + } } } diff --git a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java index 6bf72b5dbf..6d66caa79c 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/ConnectorServerFactoryBeanTests.java @@ -30,6 +30,10 @@ import javax.management.remote.JMXServiceURL; import org.junit.Test; import org.springframework.jmx.AbstractMBeanServerTests; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; + +import static org.junit.Assert.*; /** * @author Rob Harrop @@ -38,6 +42,20 @@ import org.springframework.jmx.AbstractMBeanServerTests; public class ConnectorServerFactoryBeanTests extends AbstractMBeanServerTests { private static final String OBJECT_NAME = "spring:type=connector,name=test"; + private boolean runTests = false; + + @Override + protected void onSetUp() throws Exception { + Assume.group(TestGroup.JMXMP); + runTests = true; + } + + @Override + public void tearDown() throws Exception { + if (runTests) { + super.tearDown(); + } + } @Test public void testStartupWithLocatedServer() throws Exception { diff --git a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java index 0a346b6fc1..c9c83cffae 100644 --- a/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java +++ b/spring-context/src/test/java/org/springframework/jmx/support/MBeanServerConnectionFactoryBeanTests.java @@ -26,6 +26,10 @@ import javax.management.remote.JMXServiceURL; import org.junit.Test; import org.springframework.aop.support.AopUtils; import org.springframework.jmx.AbstractMBeanServerTests; +import org.springframework.tests.Assume; +import org.springframework.tests.TestGroup; + +import static org.junit.Assert.*; /** * @author Rob Harrop @@ -45,6 +49,7 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe @Test public void testTestValidConnection() throws Exception { + Assume.group(TestGroup.JMXMP); JMXConnectorServer connectorServer = getConnectorServer(); connectorServer.start(); @@ -78,7 +83,9 @@ public class MBeanServerConnectionFactoryBeanTests extends AbstractMBeanServerTe } } + @Test public void testTestWithLazyConnection() throws Exception { + Assume.group(TestGroup.JMXMP); MBeanServerConnectionFactoryBean bean = new MBeanServerConnectionFactoryBean(); bean.setServiceUrl(SERVICE_URL); bean.setConnectOnStartup(false); diff --git a/spring-core/src/test/java/org/springframework/tests/TestGroup.java b/spring-core/src/test/java/org/springframework/tests/TestGroup.java index 7bd0ccdfd5..662f0dab53 100644 --- a/spring-core/src/test/java/org/springframework/tests/TestGroup.java +++ b/spring-core/src/test/java/org/springframework/tests/TestGroup.java @@ -48,7 +48,13 @@ public enum TestGroup { * {@code StopWatch}, etc. should be considered a candidate as their successful * execution is likely to be based on events occurring within a given time window. */ - PERFORMANCE; + PERFORMANCE, + + /** + * Tests requiring the presence of jmxremote_optional.jar in jre/lib/ext in order to + * avoid "Unsupported protocol: jmxmp" errors. + */ + JMXMP; /** From 01a6a110c9757dffcfa2f55bcd19ec55de44f7b2 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Tue, 26 Feb 2013 09:46:23 -0800 Subject: [PATCH 278/311] Upgrade docbook-reference-plugin to 0.2.6 --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index b6e1b8a03f..48c22671a7 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { } dependencies { classpath("org.springframework.build.gradle:propdeps-plugin:0.0.3") - classpath("org.springframework.build.gradle:docbook-reference-plugin:0.2.4") + classpath("org.springframework.build.gradle:docbook-reference-plugin:0.2.6") } } From 0d69a630ad41ff266ec66c9211fb0a4d4a83ecf8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Tue, 26 Feb 2013 22:30:48 +0100 Subject: [PATCH 279/311] DefaultJdoDialect supports the JDO 2.2+ isolation level feature out of the box Issue: SPR-10323 --- .../orm/jdo/DefaultJdoDialect.java | 47 ++++++++++++++----- .../orm/jdo/JdoTransactionManagerTests.java | 40 ++++++---------- 2 files changed, 51 insertions(+), 36 deletions(-) diff --git a/spring-orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java b/spring-orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java index 38d0f7263a..9d058158b9 100644 --- a/spring-orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java +++ b/spring-orm/src/main/java/org/springframework/orm/jdo/DefaultJdoDialect.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ package org.springframework.orm.jdo; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; +import javax.jdo.Constants; import javax.jdo.JDOException; import javax.jdo.PersistenceManager; import javax.jdo.Query; @@ -32,7 +33,6 @@ import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.jdbc.datasource.ConnectionHandle; import org.springframework.jdbc.support.JdbcUtils; import org.springframework.jdbc.support.SQLExceptionTranslator; -import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.util.ClassUtils; @@ -40,13 +40,13 @@ import org.springframework.util.ReflectionUtils; /** * Default implementation of the {@link JdoDialect} interface. - * Updated to build on JDO 2.0 or higher, as of Spring 2.5. + * Requires JDO 2.0; explicitly supports JDO API features up until 3.0. * Used as default dialect by {@link JdoAccessor} and {@link JdoTransactionManager}. * *

Simply begins a standard JDO transaction in {@code beginTransaction}. * Returns a handle for a JDO2 DataStoreConnection on {@code getJdbcConnection}. * Calls the corresponding JDO2 PersistenceManager operation on {@code flush} - * Ignores a given query timeout in {@code applyQueryTimeout}. + * Translates {@code applyQueryTimeout} to JDO 3.0's {@code setTimeoutMillis}. * Uses a Spring SQLExceptionTranslator for exception translation, if applicable. * *

Note that, even with JDO2, vendor-specific subclasses are still necessary @@ -122,24 +122,49 @@ public class DefaultJdoDialect implements JdoDialect, PersistenceExceptionTransl //------------------------------------------------------------------------- /** - * This implementation invokes the standard JDO {@code Transaction.begin} - * method. Throws an InvalidIsolationLevelException if a non-default isolation - * level is set. + * This implementation invokes the standard JDO {@link Transaction#begin()} + * method and also {@link Transaction#setIsolationLevel(String)} if necessary. * @see javax.jdo.Transaction#begin * @see org.springframework.transaction.InvalidIsolationLevelException */ public Object beginTransaction(Transaction transaction, TransactionDefinition definition) throws JDOException, SQLException, TransactionException { - if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { - throw new InvalidIsolationLevelException( - "Standard JDO does not support custom isolation levels: " + - "use a special JdoDialect implementation for your JDO provider"); + String jdoIsolationLevel = getJdoIsolationLevel(definition); + if (jdoIsolationLevel != null) { + transaction.setIsolationLevel(jdoIsolationLevel); } transaction.begin(); return null; } + /** + * Determine the JDO isolation level String to use for the given + * Spring transaction definition. + * @param definition the Spring transaction definition + * @return the corresponding JDO isolation level String, or {@code null} + * to indicate that no isolation level should be set explicitly + * @see Transaction#setIsolationLevel(String) + * @see Constants#TX_SERIALIZABLE + * @see Constants#TX_REPEATABLE_READ + * @see Constants#TX_READ_COMMITTED + * @see Constants#TX_READ_UNCOMMITTED + */ + protected String getJdoIsolationLevel(TransactionDefinition definition) { + switch (definition.getIsolationLevel()) { + case TransactionDefinition.ISOLATION_SERIALIZABLE: + return Constants.TX_SERIALIZABLE; + case TransactionDefinition.ISOLATION_REPEATABLE_READ: + return Constants.TX_REPEATABLE_READ; + case TransactionDefinition.ISOLATION_READ_COMMITTED: + return Constants.TX_READ_COMMITTED; + case TransactionDefinition.ISOLATION_READ_UNCOMMITTED: + return Constants.TX_READ_UNCOMMITTED; + default: + return null; + } + } + /** * This implementation does nothing, as the default beginTransaction implementation * does not require any cleanup. diff --git a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java index 538ce2572b..46003776b0 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jdo/JdoTransactionManagerTests.java @@ -16,17 +16,6 @@ package org.springframework.orm.jdo; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.DatabaseMetaData; @@ -34,7 +23,7 @@ import java.sql.SQLException; import java.sql.Savepoint; import java.util.ArrayList; import java.util.List; - +import javax.jdo.Constants; import javax.jdo.JDOFatalDataStoreException; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; @@ -48,6 +37,7 @@ import javax.transaction.UserTransaction; import org.junit.After; import org.junit.Before; import org.junit.Test; + import org.springframework.jdbc.datasource.ConnectionHandle; import org.springframework.jdbc.datasource.ConnectionHolder; import org.springframework.jdbc.datasource.SimpleConnectionHandle; @@ -55,7 +45,6 @@ import org.springframework.orm.jdo.support.SpringPersistenceManagerProxyBean; import org.springframework.orm.jdo.support.StandardPersistenceManagerProxyBean; import org.springframework.tests.sample.beans.TestBean; import org.springframework.tests.transaction.MockJtaTransaction; -import org.springframework.transaction.InvalidIsolationLevelException; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; @@ -65,6 +54,12 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + /** * @author Juergen Hoeller * @author Phillip Webb @@ -620,24 +615,19 @@ public class JdoTransactionManagerTests { } @Test - public void testInvalidIsolation() { + public void testIsolationLevel() { given(pmf.getPersistenceManager()).willReturn(pm); given(pm.currentTransaction()).willReturn(tx); PlatformTransactionManager tm = new JdoTransactionManager(pmf); TransactionTemplate tt = new TransactionTemplate(tm); tt.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); - try { - tt.execute(new TransactionCallbackWithoutResult() { - @Override - protected void doInTransactionWithoutResult(TransactionStatus status) { - } - }); - fail("Should have thrown InvalidIsolationLevelException"); - } - catch (InvalidIsolationLevelException ex) { - // expected - } + tt.execute(new TransactionCallbackWithoutResult() { + @Override + protected void doInTransactionWithoutResult(TransactionStatus status) { + } + }); + verify(tx).setIsolationLevel(Constants.TX_SERIALIZABLE); verify(pm).close(); } From 096972d2b10d5a3df38c855f63a4e4340b1df136 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 27 Feb 2013 00:22:18 +0100 Subject: [PATCH 280/311] HibernateTransactionManager for Hibernate 4 supports "entityInterceptor(BeanName)" property Issue: SPR-10301 --- .../HibernateTransactionManager.java | 92 +- .../HibernateTransactionManagerTests.java | 1006 +++++++---------- 2 files changed, 470 insertions(+), 628 deletions(-) diff --git a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java index 6d3e7ccf25..5871bb8a87 100644 --- a/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java +++ b/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/HibernateTransactionManager.java @@ -22,12 +22,16 @@ import javax.sql.DataSource; import org.hibernate.ConnectionReleaseMode; import org.hibernate.FlushMode; import org.hibernate.HibernateException; +import org.hibernate.Interceptor; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.transaction.spi.TransactionContext; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.beans.factory.InitializingBean; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; @@ -100,7 +104,7 @@ import org.springframework.transaction.support.TransactionSynchronizationManager */ @SuppressWarnings("serial") public class HibernateTransactionManager extends AbstractPlatformTransactionManager - implements ResourceTransactionManager, InitializingBean { + implements ResourceTransactionManager, BeanFactoryAware, InitializingBean { private SessionFactory sessionFactory; @@ -112,6 +116,14 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana private boolean hibernateManagedSession = false; + private Object entityInterceptor; + + /** + * Just needed for entityInterceptorBeanName. + * @see #setEntityInterceptorBeanName + */ + private BeanFactory beanFactory; + /** * Create a new HibernateTransactionManager instance. @@ -229,7 +241,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana * to always return a proper Session when called for a Spring-managed transaction; * transaction begin will fail if the {@code getCurrentSession()} call fails. *

This mode will typically be used in combination with a custom Hibernate - * {@link org.hibernate.context.CurrentSessionContext} implementation that stores + * {@link org.hibernate.context.spi.CurrentSessionContext} implementation that stores * Sessions in a place other than Spring's TransactionSynchronizationManager. * It may also be used in combination with Spring's Open-Session-in-View support * (using Spring's default {@link SpringSessionContext}), in which case it subtly @@ -242,10 +254,81 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana this.hibernateManagedSession = hibernateManagedSession; } + /** + * Set the bean name of a Hibernate entity interceptor that allows to inspect + * and change property values before writing to and reading from the database. + * Will get applied to any new Session created by this transaction manager. + *

Requires the bean factory to be known, to be able to resolve the bean + * name to an interceptor instance on session creation. Typically used for + * prototype interceptors, i.e. a new interceptor instance per session. + *

Can also be used for shared interceptor instances, but it is recommended + * to set the interceptor reference directly in such a scenario. + * @param entityInterceptorBeanName the name of the entity interceptor in + * the bean factory + * @see #setBeanFactory + * @see #setEntityInterceptor + */ + public void setEntityInterceptorBeanName(String entityInterceptorBeanName) { + this.entityInterceptor = entityInterceptorBeanName; + } + + /** + * Set a Hibernate entity interceptor that allows to inspect and change + * property values before writing to and reading from the database. + * Will get applied to any new Session created by this transaction manager. + *

Such an interceptor can either be set at the SessionFactory level, + * i.e. on LocalSessionFactoryBean, or at the Session level, i.e. on + * HibernateTemplate, HibernateInterceptor, and HibernateTransactionManager. + * It's preferable to set it on LocalSessionFactoryBean or HibernateTransactionManager + * to avoid repeated configuration and guarantee consistent behavior in transactions. + * @see LocalSessionFactoryBean#setEntityInterceptor + */ + public void setEntityInterceptor(Interceptor entityInterceptor) { + this.entityInterceptor = entityInterceptor; + } + + /** + * Return the current Hibernate entity interceptor, or {@code null} if none. + * Resolves an entity interceptor bean name via the bean factory, + * if necessary. + * @throws IllegalStateException if bean name specified but no bean factory set + * @throws BeansException if bean name resolution via the bean factory failed + * @see #setEntityInterceptor + * @see #setEntityInterceptorBeanName + * @see #setBeanFactory + */ + public Interceptor getEntityInterceptor() throws IllegalStateException, BeansException { + if (this.entityInterceptor instanceof Interceptor) { + return (Interceptor) entityInterceptor; + } + else if (this.entityInterceptor instanceof String) { + if (this.beanFactory == null) { + throw new IllegalStateException("Cannot get entity interceptor via bean name if no bean factory set"); + } + String beanName = (String) this.entityInterceptor; + return this.beanFactory.getBean(beanName, Interceptor.class); + } + else { + return null; + } + } + + /** + * The bean factory just needs to be known for resolving entity interceptor + * bean names. It does not need to be set for any other mode of operation. + * @see #setEntityInterceptorBeanName + */ + public void setBeanFactory(BeanFactory beanFactory) { + this.beanFactory = beanFactory; + } + public void afterPropertiesSet() { if (getSessionFactory() == null) { throw new IllegalArgumentException("Property 'sessionFactory' is required"); } + if (this.entityInterceptor instanceof String && this.beanFactory == null) { + throw new IllegalArgumentException("Property 'beanFactory' is required for 'entityInterceptorBeanName'"); + } // Check for SessionFactory's DataSource. if (this.autodetectDataSource && getDataSource() == null) { @@ -325,7 +408,10 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana try { if (txObject.getSessionHolder() == null || txObject.getSessionHolder().isSynchronizedWithTransaction()) { - Session newSession = getSessionFactory().openSession(); + Interceptor entityInterceptor = getEntityInterceptor(); + Session newSession = (entityInterceptor != null ? + getSessionFactory().withOptions().interceptor(entityInterceptor).openSession() : + getSessionFactory().openSession()); if (logger.isDebugEnabled()) { logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction"); } diff --git a/spring-orm-hibernate4/src/test/java/org/springframework/orm/hibernate4/HibernateTransactionManagerTests.java b/spring-orm-hibernate4/src/test/java/org/springframework/orm/hibernate4/HibernateTransactionManagerTests.java index 26bdd97e29..f235fc196e 100644 --- a/spring-orm-hibernate4/src/test/java/org/springframework/orm/hibernate4/HibernateTransactionManagerTests.java +++ b/spring-orm-hibernate4/src/test/java/org/springframework/orm/hibernate4/HibernateTransactionManagerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,17 +25,21 @@ import java.util.List; import java.util.Properties; import javax.sql.DataSource; -import junit.framework.TestCase; -import org.easymock.MockControl; import org.hibernate.FlushMode; +import org.hibernate.Interceptor; import org.hibernate.Query; import org.hibernate.Session; +import org.hibernate.SessionBuilder; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.dialect.HSQLDialect; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.exception.ConstraintViolationException; +import org.junit.After; +import org.junit.Test; +import org.mockito.InOrder; +import org.springframework.beans.factory.BeanFactory; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.datasource.ConnectionHolder; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -50,63 +54,42 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @since 3.2 */ -public class HibernateTransactionManagerTests extends TestCase { +public class HibernateTransactionManagerTests { + @After + public void tearDown() { + assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); + assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); + assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + } + + @Test public void testTransactionCommit() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - con.getTransactionIsolation(); - conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED); - con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - conControl.setVoidCallable(1); - con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - conControl.setVoidCallable(1); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.getTransaction(); - sessionControl.setReturnValue(tx, 1); - tx.setTimeout(10); - txControl.setVoidCallable(1); - tx.begin(); - txControl.setVoidCallable(1); - session.connection(); - sessionControl.setReturnValue(con, 3); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED); + given(sf.openSession()).willReturn(session); + given(session.getTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.isConnected()).willReturn(true); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -143,42 +126,27 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + + verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + verify(tx).setTimeout(10); + verify(tx).begin(); + verify(tx).commit(); + verify(session).close(); } + @Test public void testTransactionRollback() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -201,40 +169,23 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testTransactionRollbackOnly() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -252,40 +203,24 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).flush(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testParticipatingTransactionWithCommit() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -316,38 +251,24 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Correct result list", result == l); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).flush(); + verify(session).close(); + verify(tx).commit(); } + @Test public void testParticipatingTransactionWithRollback() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -369,41 +290,27 @@ public class HibernateTransactionManagerTests extends TestCase { // expected } - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).rollback(); } + @Test public void testParticipatingTransactionWithRollbackOnly() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); + final List l = new ArrayList(); + l.add("test"); try { tt.execute(new TransactionCallback() { @@ -424,55 +331,28 @@ public class HibernateTransactionManagerTests extends TestCase { // expected } - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).rollback(); } - public void testParticipatingTransactionWithWithRequiresNew() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(ImplementingSession.class); - ImplementingSession session1 = (ImplementingSession) session1Control.getMock(); - MockControl session2Control = MockControl.createControl(ImplementingSession.class); - ImplementingSession session2 = (ImplementingSession) session2Control.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + @Test + public void testParticipatingTransactionWithRequiresNew() throws Exception { + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session1 = mock(ImplementingSession.class); + ImplementingSession session2 = mock(ImplementingSession.class); + Connection con = mock(Connection.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - sf.openSession(); - sfControl.setReturnValue(session2, 1); - session1.beginTransaction(); - session1Control.setReturnValue(tx, 1); - session2.beginTransaction(); - session2Control.setReturnValue(tx, 1); - session2.flush(); - session2Control.setVoidCallable(1); - session1.close(); - session1Control.setReturnValue(null, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(2); - session1.isConnected(); - session1Control.setReturnValue(true, 1); - session1.connection(); - session1Control.setReturnValue(con, 2); - session2.isConnected(); - session2Control.setReturnValue(true, 1); - session2.connection(); - session2Control.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 2); - - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); - conControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session1, session2); + given(session1.beginTransaction()).willReturn(tx); + given(session1.isOpen()).willReturn(true); + given(session2.beginTransaction()).willReturn(tx); + given(session2.isOpen()).willReturn(true); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); + given(session1.isConnected()).willReturn(true); + given(session1.connection()).willReturn(con); + given(session2.isConnected()).willReturn(true); + given(session2.connection()).willReturn(con); PlatformTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -506,42 +386,26 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); - conControl.verify(); - txControl.verify(); + verify(session2).flush(); + verify(session1).close(); + verify(session2).close(); + verify(tx, times(2)).commit(); } - public void testParticipatingTransactionWithWithNotSupported() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + @Test + public void testParticipatingTransactionWithNotSupported() throws Exception { + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Connection con = mock(Connection.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - conControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.AUTO); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(sf); final TransactionTemplate tt = new TransactionTemplate(tm); @@ -574,25 +438,18 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + verify(session).close(); + verify(tx).commit(); } + @Test public void testTransactionWithPropagationSupports() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.flush(); - sessionControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - sfControl.replay(); - sessionControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.getSessionFactory()).willReturn(sf); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -623,47 +480,27 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sfProxy)); - sfControl.verify(); - sessionControl.verify(); + InOrder ordered = inOrder(session); + ordered.verify(session).flush(); + ordered.verify(session).close(); } + @Test public void testTransactionWithPropagationSupportsAndInnerTransaction() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl session1Control = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session1 = (ImplementingSession) session1Control.getMock(); - MockControl session2Control = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session2 = (ImplementingSession) session2Control.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final ImplementingSession session1 = mock(ImplementingSession.class); + final ImplementingSession session2 = mock(ImplementingSession.class); + Connection con = mock(Connection.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session1, 1); - session1.flush(); - session1Control.setVoidCallable(1); - session1.close(); - session1Control.setReturnValue(null, 1); - - sf.openSession(); - sfControl.setReturnValue(session2, 1); - session2.beginTransaction(); - session2Control.setReturnValue(tx, 1); - session2.connection(); - session2Control.setReturnValue(con, 2); - session2.flush(); - session2Control.setVoidCallable(1); - tx.commit(); - txControl.setVoidCallable(1); - session2.isConnected(); - session2Control.setReturnValue(true, 1); - session2.close(); - session2Control.setReturnValue(null, 1); - sfControl.replay(); - session1Control.replay(); - session2Control.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session1, session2); + given(session1.getSessionFactory()).willReturn(sf); + given(session1.getFlushMode()).willReturn(FlushMode.AUTO); + given(session2.beginTransaction()).willReturn(tx); + given(session2.connection()).willReturn(con); + given(session2.getFlushMode()).willReturn(FlushMode.AUTO); + given(session2.isOpen()).willReturn(true); + given(session2.isConnected()).willReturn(true); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean() { @Override @@ -710,56 +547,117 @@ public class HibernateTransactionManagerTests extends TestCase { }); assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); - sfControl.verify(); - session1Control.verify(); - session2Control.verify(); - txControl.verify(); + verify(session1).flush(); + verify(session1).close(); + verify(session2).flush(); + verify(session2).close(); + verify(tx).commit(); } + @Test + public void testTransactionCommitWithEntityInterceptor() throws Exception { + Interceptor entityInterceptor = mock(Interceptor.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + SessionBuilder options = mock(SessionBuilder.class); + Transaction tx = mock(Transaction.class); + + given(sf.withOptions()).willReturn(options); + given(options.interceptor(entityInterceptor)).willReturn(options); + given(options.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); + + HibernateTransactionManager tm = new HibernateTransactionManager(sf); + tm.setEntityInterceptor(entityInterceptor); + TransactionTemplate tt = new TransactionTemplate(tm); + tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + Object result = tt.execute(new TransactionCallbackWithoutResult() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + } + }); + + assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(session).close(); + verify(tx).commit(); + } + + @Test + public void testTransactionCommitWithEntityInterceptorBeanName() throws Exception { + Interceptor entityInterceptor = mock(Interceptor.class); + Interceptor entityInterceptor2 = mock(Interceptor.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + SessionBuilder options = mock(SessionBuilder.class); + Transaction tx = mock(Transaction.class); + + given(sf.withOptions()).willReturn(options); + given(options.interceptor(entityInterceptor)).willReturn(options); + given(options.interceptor(entityInterceptor2)).willReturn(options); + given(options.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); + + BeanFactory beanFactory = mock(BeanFactory.class); + given(beanFactory.getBean("entityInterceptor", Interceptor.class)).willReturn( + entityInterceptor, entityInterceptor2); + + HibernateTransactionManager tm = new HibernateTransactionManager(sf); + tm.setEntityInterceptorBeanName("entityInterceptor"); + tm.setBeanFactory(beanFactory); + + TransactionTemplate tt = new TransactionTemplate(tm); + tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + for (int i = 0; i < 2; i++) { + tt.execute(new TransactionCallbackWithoutResult() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf)); + } + }); + } + + assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); + assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); + + verify(session, times(2)).close(); + verify(tx, times(2)).commit(); + } + + @Test public void testTransactionCommitWithReadOnly() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.setFlushMode(FlushMode.MANUAL); - sessionControl.setVoidCallable(1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.setReadOnly(true); - conControl.setVoidCallable(1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - con.isReadOnly(); - conControl.setReturnValue(true, 1); - con.setReadOnly(false); - conControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.isConnected()).willReturn(true); + given(con.isReadOnly()).willReturn(true); HibernateTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -782,48 +680,30 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + verify(session).setFlushMode(FlushMode.MANUAL); + verify(con).setReadOnly(true); + verify(tx).commit(); + verify(con).setReadOnly(false); + verify(session).close(); } + @Test public void testTransactionCommitWithFlushFailure() throws Exception { - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - tx.commit(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); SQLException sqlEx = new SQLException("argh", "27"); Exception rootCause = null; ConstraintViolationException jdbcEx = new ConstraintViolationException("mymsg", sqlEx, null); - txControl.setThrowable(jdbcEx, 1); rootCause = jdbcEx; - session.close(); - sessionControl.setReturnValue(null, 1); - tx.rollback(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.connection(); - sessionControl.setReturnValue(con, 2); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - conControl.replay(); + willThrow(jdbcEx).given(tx).commit(); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(sf); TransactionTemplate tt = new TransactionTemplate(tm); @@ -850,50 +730,25 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - conControl.verify(); + + verify(session).close(); + verify(tx).rollback(); } + @Test public void testTransactionCommitWithPreBound() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 2); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.connection(); - sessionControl.setReturnValue(con, 3); - con.getTransactionIsolation(); - conControl.setReturnValue(Connection.TRANSACTION_READ_COMMITTED); - con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); - conControl.setVoidCallable(1); - con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); - conControl.setVoidCallable(1); - tx.commit(); - txControl.setVoidCallable(1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - session.disconnect(); - sessionControl.setReturnValue(null, 1); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(session.beginTransaction()).willReturn(tx); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); + given(session.connection()).willReturn(con); + given(con.getTransactionIsolation()).willReturn(Connection.TRANSACTION_READ_COMMITTED); + given(session.isConnected()).willReturn(true); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setSessionFactory(sf); @@ -928,55 +783,29 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); + InOrder ordered = inOrder(session, con); + ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(con).setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + verify(tx).commit(); + verify(session).disconnect(); } + @Test public void testTransactionRollbackWithPreBound() throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl tx1Control = MockControl.createControl(Transaction.class); - final Transaction tx1 = (Transaction) tx1Control.getMock(); - MockControl tx2Control = MockControl.createControl(Transaction.class); - final Transaction tx2 = (Transaction) tx2Control.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + final SessionFactory sf = mock(SessionFactory.class); + final ImplementingSession session = mock(ImplementingSession.class); + final Transaction tx1 = mock(Transaction.class); + final Transaction tx2 = mock(Transaction.class); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 4); - session.beginTransaction(); - sessionControl.setReturnValue(tx1, 1); - tx1.rollback(); - tx1Control.setVoidCallable(1); - session.clear(); - sessionControl.setVoidCallable(1); - session.beginTransaction(); - sessionControl.setReturnValue(tx2, 1); - tx2.commit(); - tx2Control.setVoidCallable(1); - - session.isConnected(); - sessionControl.setReturnValue(true, 2); - session.connection(); - sessionControl.setReturnValue(con, 6); - con.isReadOnly(); - conControl.setReturnValue(false, 2); - session.disconnect(); - sessionControl.setReturnValue(null, 2); - - dsControl.replay(); - conControl.replay(); - sfControl.replay(); - sessionControl.replay(); - tx1Control.replay(); - tx2Control.replay(); + given(session.beginTransaction()).willReturn(tx1, tx2); + given(session.isOpen()).willReturn(true); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); + given(session.isConnected()).willReturn(true); + given(session.connection()).willReturn(con); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setSessionFactory(sf); @@ -1034,49 +863,27 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - sfControl.verify(); - sessionControl.verify(); - tx1Control.verify(); - tx2Control.verify(); + verify(tx1).rollback(); + verify(tx2).commit(); + InOrder ordered = inOrder(session); + ordered.verify(session).clear(); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); + ordered.verify(session).disconnect(); } + @Test public void testTransactionRollbackWithHibernateManagedSession() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl tx1Control = MockControl.createControl(Transaction.class); - final Transaction tx1 = (Transaction) tx1Control.getMock(); - MockControl tx2Control = MockControl.createControl(Transaction.class); - final Transaction tx2 = (Transaction) tx2Control.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + final Transaction tx1 = mock(Transaction.class); + final Transaction tx2 = mock(Transaction.class); - sf.getCurrentSession(); - sfControl.setReturnValue(session, 2); - session.getFlushMode(); - sessionControl.setReturnValue(FlushMode.AUTO, 4); - session.getTransaction(); - sessionControl.setReturnValue(tx1, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx1, 1); - tx1.isActive(); - tx1Control.setReturnValue(false, 1); - tx1.rollback(); - tx1Control.setVoidCallable(1); - session.getTransaction(); - sessionControl.setReturnValue(tx2, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx2, 1); - tx2.isActive(); - tx2Control.setReturnValue(false, 1); - tx2.commit(); - tx2Control.setVoidCallable(1); - - sfControl.replay(); - sessionControl.replay(); - tx1Control.replay(); - tx2Control.replay(); + given(sf.getCurrentSession()).willReturn(session); + given(session.isOpen()).willReturn(true); + given(session.getTransaction()).willReturn(tx1, tx2); + given(session.beginTransaction()).willReturn(tx1, tx2); + given(session.getFlushMode()).willReturn(FlushMode.MANUAL); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setSessionFactory(sf); @@ -1118,16 +925,19 @@ public class HibernateTransactionManagerTests extends TestCase { } }); - sfControl.verify(); - sessionControl.verify(); - tx1Control.verify(); - tx2Control.verify(); + verify(tx1).rollback(); + verify(tx2).commit(); + InOrder ordered = inOrder(session); + ordered.verify(session).setFlushMode(FlushMode.AUTO); + ordered.verify(session).setFlushMode(FlushMode.MANUAL); } + @Test public void testExistingTransactionWithPropagationNestedAndRollback() throws Exception { doTestExistingTransactionWithPropagationNestedAndRollback(false); } + @Test public void testExistingTransactionWithManualSavepointAndRollback() throws Exception { doTestExistingTransactionWithPropagationNestedAndRollback(true); } @@ -1135,60 +945,27 @@ public class HibernateTransactionManagerTests extends TestCase { private void doTestExistingTransactionWithPropagationNestedAndRollback(final boolean manualSavepoint) throws Exception { - MockControl dsControl = MockControl.createControl(DataSource.class); - final DataSource ds = (DataSource) dsControl.getMock(); - MockControl conControl = MockControl.createControl(Connection.class); - Connection con = (Connection) conControl.getMock(); - MockControl mdControl = MockControl.createControl(DatabaseMetaData.class); - DatabaseMetaData md = (DatabaseMetaData) mdControl.getMock(); - MockControl spControl = MockControl.createControl(Savepoint.class); - Savepoint sp = (Savepoint) spControl.getMock(); - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); - MockControl queryControl = MockControl.createControl(Query.class); - Query query = (Query) queryControl.getMock(); + final DataSource ds = mock(DataSource.class); + Connection con = mock(Connection.class); + DatabaseMetaData md = mock(DatabaseMetaData.class); + Savepoint sp = mock(Savepoint.class); + final SessionFactory sf = mock(SessionFactory.class); + ImplementingSession session = mock(ImplementingSession.class); + Transaction tx = mock(Transaction.class); + Query query = mock(Query.class); final List list = new ArrayList(); list.add("test"); - con.isReadOnly(); - conControl.setReturnValue(false, 1); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.connection(); - sessionControl.setReturnValue(con, 3); - md.supportsSavepoints(); - mdControl.setReturnValue(true, 1); - con.getMetaData(); - conControl.setReturnValue(md, 1); - con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1); - conControl.setReturnValue(sp, 1); - con.rollback(sp); - conControl.setVoidCallable(1); - session.createQuery("some query string"); - sessionControl.setReturnValue(query, 1); - query.list(); - queryControl.setReturnValue(list, 1); - session.isConnected(); - sessionControl.setReturnValue(true, 1); - session.close(); - sessionControl.setReturnValue(null, 1); - tx.commit(); - txControl.setVoidCallable(1); - - dsControl.replay(); - conControl.replay(); - mdControl.replay(); - spControl.replay(); - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); - queryControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); + given(session.connection()).willReturn(con); + given(session.isOpen()).willReturn(true); + given(md.supportsSavepoints()).willReturn(true); + given(con.getMetaData()).willReturn(md); + given(con.setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1)).willReturn(sp); + given(session.createQuery("some query string")).willReturn(query); + given(query.list()).willReturn(list); + given(session.isConnected()).willReturn(true); HibernateTransactionManager tm = new HibernateTransactionManager(); tm.setNestedTransactionAllowed(true); @@ -1228,16 +1005,14 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - dsControl.verify(); - conControl.verify(); - mdControl.verify(); - spControl.verify(); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - queryControl.verify(); + + verify(con).setSavepoint(ConnectionHolder.SAVEPOINT_NAME_PREFIX + 1); + verify(con).rollback(sp); + verify(session).close(); + verify(tx).commit(); } + @Test public void testTransactionCommitWithNonExistingDatabase() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean(); @@ -1279,6 +1054,7 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); } + @Test public void testTransactionCommitWithPreBoundSessionAndNonExistingDatabase() throws Exception { final DriverManagerDataSource ds = new DriverManagerDataSource(); LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean(); @@ -1328,6 +1104,7 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); } + @Test public void testTransactionCommitWithNonExistingDatabaseAndLazyConnection() throws Exception { DriverManagerDataSource dsTarget = new DriverManagerDataSource(); final LazyConnectionDataSourceProxy ds = new LazyConnectionDataSourceProxy(); @@ -1370,28 +1147,14 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); } + @Test public void testTransactionFlush() throws Exception { - MockControl sfControl = MockControl.createControl(SessionFactory.class); - final SessionFactory sf = (SessionFactory) sfControl.getMock(); - MockControl sessionControl = MockControl.createControl(ImplementingSession.class); - final ImplementingSession session = (ImplementingSession) sessionControl.getMock(); - MockControl txControl = MockControl.createControl(Transaction.class); - Transaction tx = (Transaction) txControl.getMock(); + final SessionFactory sf = mock(SessionFactory.class); + final Session session = mock(Session.class); + Transaction tx = mock(Transaction.class); - sf.openSession(); - sfControl.setReturnValue(session, 1); - session.beginTransaction(); - sessionControl.setReturnValue(tx, 1); - session.flush(); - sessionControl.setVoidCallable(1); - tx.commit(); - txControl.setVoidCallable(1); - session.close(); - sessionControl.setReturnValue(null, 1); - - sfControl.replay(); - sessionControl.replay(); - txControl.replay(); + given(sf.openSession()).willReturn(session); + given(session.beginTransaction()).willReturn(tx); HibernateTransactionManager tm = new HibernateTransactionManager(sf); tm.setPrepareConnection(false); @@ -1411,17 +1174,10 @@ public class HibernateTransactionManagerTests extends TestCase { assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf)); assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive()); - sfControl.verify(); - sessionControl.verify(); - txControl.verify(); - } - @Override - protected void tearDown() { - assertTrue(TransactionSynchronizationManager.getResourceMap().isEmpty()); - assertFalse(TransactionSynchronizationManager.isSynchronizationActive()); - assertFalse(TransactionSynchronizationManager.isCurrentTransactionReadOnly()); - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + verify(session).flush(); + verify(tx).commit(); + verify(session).close(); } From b979d8d548286864f3b7f51c0b18f5d339d624c8 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 27 Feb 2013 00:22:53 +0100 Subject: [PATCH 281/311] Polishing along with SPR-10301 --- .../HibernateTransactionManager.java | 1 + .../HibernateTransactionManagerTests.java | 22 ++++++------------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java b/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java index 896a91379f..abd06c801a 100644 --- a/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java +++ b/spring-orm/src/main/java/org/springframework/orm/hibernate3/HibernateTransactionManager.java @@ -887,6 +887,7 @@ public class HibernateTransactionManager extends AbstractPlatformTransactionMana (hasConnectionHolder() && getConnectionHolder().isRollbackOnly()); } + @Override public void flush() { try { this.sessionHolder.getSession().flush(); diff --git a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java index 534beea656..d4d12ba036 100644 --- a/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/hibernate3/HibernateTransactionManagerTests.java @@ -16,18 +16,6 @@ package org.springframework.orm.hibernate3; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; -import static org.mockito.BDDMockito.willThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; @@ -35,7 +23,6 @@ import java.sql.Savepoint; import java.util.ArrayList; import java.util.List; import java.util.Properties; - import javax.sql.DataSource; import org.hibernate.FlushMode; @@ -53,6 +40,7 @@ import org.hibernate.exception.GenericJDBCException; import org.junit.After; import org.junit.Test; import org.mockito.InOrder; + import org.springframework.beans.factory.BeanFactory; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.jdbc.datasource.ConnectionHolder; @@ -69,6 +57,9 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; +import static org.junit.Assert.*; +import static org.mockito.BDDMockito.*; + /** * @author Juergen Hoeller * @author Phillip Webb @@ -450,7 +441,7 @@ public class HibernateTransactionManagerTests { } @Test - public void testParticipatingTransactionWithWithRequiresNew() throws Exception { + public void testParticipatingTransactionWithRequiresNew() throws Exception { final SessionFactory sf = mock(SessionFactory.class); Session session1 = mock(Session.class); Session session2 = mock(Session.class); @@ -512,7 +503,7 @@ public class HibernateTransactionManagerTests { } @Test - public void testParticipatingTransactionWithWithNotSupported() throws Exception { + public void testParticipatingTransactionWithNotSupported() throws Exception { final SessionFactory sf = mock(SessionFactory.class); Session session = mock(Session.class); Connection con = mock(Connection.class); @@ -1399,4 +1390,5 @@ public class HibernateTransactionManagerTests { verify(tx).commit(); verify(session).close(); } + } From 3b60f64d5119d256d1e84f4f144f9418170d233f Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 27 Feb 2013 00:24:21 +0100 Subject: [PATCH 282/311] Fixed invalid EhCacheFactoryBean test for EhCache 2.4+ compatibility --- .../org/springframework/cache/ehcache/EhCacheSupportTests.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java index fcfe221642..6e8efcd816 100644 --- a/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java +++ b/spring-context-support/src/test/java/org/springframework/cache/ehcache/EhCacheSupportTests.java @@ -133,7 +133,6 @@ public class EhCacheSupportTests extends TestCase { cacheFb.setBeanName("undefinedCache2"); cacheFb.setMaxElementsInMemory(5); cacheFb.setOverflowToDisk(false); - cacheFb.setEternal(true); cacheFb.setTimeToLive(8); cacheFb.setTimeToIdle(7); cacheFb.setDiskPersistent(true); @@ -145,7 +144,6 @@ public class EhCacheSupportTests extends TestCase { assertEquals("undefinedCache2", cache.getName()); assertTrue("overridden maxElements is correct", config.getMaxElementsInMemory() == 5); assertFalse("overridden overflowToDisk is correct", config.isOverflowToDisk()); - assertTrue("overridden eternal is correct", config.isEternal()); assertTrue("default timeToLive is correct", config.getTimeToLiveSeconds() == 8); assertTrue("default timeToIdle is correct", config.getTimeToIdleSeconds() == 7); assertTrue("overridden diskPersistent is correct", config.isDiskPersistent()); From de069d06d852e6fa2e8e4ca9d442168729af6588 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 27 Feb 2013 00:26:27 +0100 Subject: [PATCH 283/311] Made "getJaxbContext()" method public Issue: SPR-10282 --- .../org/springframework/oxm/jaxb/Jaxb2Marshaller.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java index 3684aa3b9f..4ffd0c495d 100644 --- a/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java +++ b/spring-oxm/src/main/java/org/springframework/oxm/jaxb/Jaxb2Marshaller.java @@ -417,7 +417,10 @@ public class Jaxb2Marshaller } } - protected JAXBContext getJaxbContext() { + /** + * Return the JAXBContext used by this marshaller, lazily building it if necessary. + */ + public JAXBContext getJaxbContext() { if (this.jaxbContext != null) { return this.jaxbContext; } @@ -525,10 +528,8 @@ public class Jaxb2Marshaller public boolean supports(Class clazz) { - if (this.supportJaxbElementClass && JAXBElement.class.isAssignableFrom(clazz)) { - return true; - } - return supportsInternal(clazz, this.checkForXmlRootElement); + return ((this.supportJaxbElementClass && JAXBElement.class.isAssignableFrom(clazz)) || + supportsInternal(clazz, this.checkForXmlRootElement)); } public boolean supports(Type genericType) { From 1bae80a24159f1d106276d09845fdc7659a2c667 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Wed, 27 Feb 2013 00:31:05 +0100 Subject: [PATCH 284/311] Polishing --- .../factory/wiring/BeanConfigurerSupport.java | 14 ++++++-------- .../springframework/cache/annotation/Caching.java | 12 ++++-------- .../springframework/context/annotation/Bean.java | 6 +++--- 3 files changed, 13 insertions(+), 19 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java b/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java index 3413b457c0..81fa4242b2 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/wiring/BeanConfigurerSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,14 +30,13 @@ import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** - * Convenient base class for configurers that can perform Dependency Injection + * Convenient base class for bean configurers that can perform Dependency Injection * on objects (however they may be created). Typically subclassed by AspectJ aspects. * *

Subclasses may also need a custom metadata resolution strategy, in the - * {@link BeanWiringInfoResolver} interface. The default implementation looks - * for a bean with the same name as the fully-qualified class name. (This is - * the default name of the bean in a Spring XML file if the '{@code id}' - * attribute is not used.) + * {@link BeanWiringInfoResolver} interface. The default implementation looks for + * a bean with the same name as the fully-qualified class name. (This is the default + * name of the bean in a Spring XML file if the '{@code id}' attribute is not used.) * @author Rob Harrop * @author Rod Johnson @@ -113,8 +112,7 @@ public class BeanConfigurerSupport implements BeanFactoryAware, InitializingBean /** * Configure the bean instance. *

Subclasses can override this to provide custom configuration logic. - * Typically called by an aspect, for all bean instances matched by a - * pointcut. + * Typically called by an aspect, for all bean instances matched by a pointcut. * @param beanInstance the bean instance to configure (must not be {@code null}) */ public void configureBean(Object beanInstance) { diff --git a/spring-context/src/main/java/org/springframework/cache/annotation/Caching.java b/spring-context/src/main/java/org/springframework/cache/annotation/Caching.java index 7d3e77d319..6bad879b76 100644 --- a/spring-context/src/main/java/org/springframework/cache/annotation/Caching.java +++ b/spring-context/src/main/java/org/springframework/cache/annotation/Caching.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,12 +16,7 @@ package org.springframework.cache.annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; +import java.lang.annotation.*; /** * Group annotation for multiple cache annotations (of different or the same type). @@ -30,7 +25,7 @@ import java.lang.annotation.Target; * @author Chris Beams * @since 3.1 */ -@Target({ ElementType.METHOD, ElementType.TYPE }) +@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @@ -41,4 +36,5 @@ public @interface Caching { CachePut[] put() default {}; CacheEvict[] evict() default {}; + } diff --git a/spring-context/src/main/java/org/springframework/context/annotation/Bean.java b/spring-context/src/main/java/org/springframework/context/annotation/Bean.java index a0c8ab1159..679352decf 100644 --- a/spring-context/src/main/java/org/springframework/context/annotation/Bean.java +++ b/spring-context/src/main/java/org/springframework/context/annotation/Bean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -177,7 +177,7 @@ import org.springframework.beans.factory.support.AbstractBeanDefinition; * @see org.springframework.beans.factory.annotation.Autowired * @see org.springframework.beans.factory.annotation.Value */ -@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Bean { @@ -190,7 +190,7 @@ public @interface Bean { String[] name() default {}; /** - * Are dependencies to be injected via autowiring? + * Are dependencies to be injected via convention-based autowiring by name or type? */ Autowire autowire() default Autowire.NO; From 21a49ef4c56b7599a49b085e0d5190ff556a24c9 Mon Sep 17 00:00:00 2001 From: Rob Winch Date: Wed, 27 Feb 2013 14:28:00 -0600 Subject: [PATCH 285/311] Polish whitespace in *.aj Previously we had restored the whitespace for *.aj files in 6888a6f28 to avoid a but in aspectj. We have updated to the latest version of apsectj and restored the changes in commit 6888a6f28 which included a significant cleanup of whitespace. Issue: SPR-10208 --- build.gradle | 2 +- .../aspectj/AbstractBeanConfigurerAspect.aj | 10 +-- .../AbstractDependencyInjectionAspect.aj | 36 +++++----- ...nterfaceDrivenDependencyInjectionAspect.aj | 66 +++++++++---------- .../aspectj/AnnotationBeanConfigurerAspect.aj | 12 ++-- ...nterfaceDrivenDependencyInjectionAspect.aj | 34 +++++----- .../cache/aspectj/AbstractCacheAspect.aj | 2 +- .../AbstractMethodMockingControl.aj | 20 +++--- ...otationDrivenStaticEntityMockingControl.aj | 14 ++-- .../aspectj/JpaExceptionTranslatorAspect.aj | 21 ++++-- .../aspectj/AbstractAsyncExecutionAspect.aj | 2 +- .../aspectj/AbstractTransactionAspect.aj | 2 +- .../aspectj/AnnotationTransactionAspect.aj | 8 +-- 13 files changed, 123 insertions(+), 106 deletions(-) diff --git a/build.gradle b/build.gradle index 48c22671a7..bf5df93e85 100644 --- a/build.gradle +++ b/build.gradle @@ -12,7 +12,7 @@ configure(allprojects) { project -> group = "org.springframework" version = qualifyVersionIfNecessary(version) - ext.aspectjVersion = "1.7.1" + ext.aspectjVersion = "1.7.2" ext.easymockVersion = "2.5.2" ext.hsqldbVersion = "1.8.0.10" ext.junitVersion = "4.11" diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj index 85342e838b..033a083016 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractBeanConfigurerAspect.aj @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - + package org.springframework.beans.factory.aspectj; import org.aspectj.lang.annotation.SuppressAjWarnings; @@ -23,12 +23,12 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; * Abstract superaspect for AspectJ aspects that can perform Dependency * Injection on objects, however they may be created. Define the beanCreation() * pointcut in subaspects. - * + * *

Subaspects may also need a metadata resolution strategy, in the - * BeanWiringInfoResolver interface. The default implementation + * {@code BeanWiringInfoResolver} interface. The default implementation * looks for a bean with the same name as the FQN. This is the default name * of a bean in a Spring container if the id value is not supplied explicitly. - * + * * @author Rob Harrop * @author Rod Johnson * @author Adrian Colyer @@ -62,7 +62,7 @@ public abstract aspect AbstractBeanConfigurerAspect extends BeanConfigurerSuppor /** * The initialization of a new object. - * + * *

WARNING: Although this pointcut is non-abstract for backwards * compatibility reasons, it is meant to be overridden to select * initialization of any configurable bean. diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj index 23b012ecc7..fa8fc6441f 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractDependencyInjectionAspect.aj @@ -17,11 +17,12 @@ package org.springframework.beans.factory.aspectj; import org.aspectj.lang.annotation.SuppressAjWarnings; +import org.aspectj.lang.annotation.control.CodeGenerationHint; /** * Abstract base aspect that can perform Dependency * Injection on objects, however they may be created. - * + * * @author Ramnivas Laddad * @since 2.5.2 */ @@ -29,28 +30,29 @@ public abstract aspect AbstractDependencyInjectionAspect { /** * Select construction join points for objects to inject dependencies */ - public abstract pointcut beanConstruction(Object bean); + public abstract pointcut beanConstruction(Object bean); /** * Select deserialization join points for objects to inject dependencies */ public abstract pointcut beanDeserialization(Object bean); - + /** * Select join points in a configurable bean */ public abstract pointcut inConfigurableBean(); - + /** * Select join points in beans to be configured prior to construction? * By default, use post-construction injection matching the default in the Configurable annotation. */ public pointcut preConstructionConfiguration() : if(false); - + /** - * Select the most-specific initialization join point + * Select the most-specific initialization join point * (most concrete class) for the initialization of an instance. */ + @CodeGenerationHint(ifNameSuffix="6f1") public pointcut mostSpecificSubTypeConstruction() : if(thisJoinPoint.getSignature().getDeclaringType() == thisJoinPoint.getThis().getClass()); @@ -58,25 +60,25 @@ public abstract aspect AbstractDependencyInjectionAspect { * Select least specific super type that is marked for DI (so that injection occurs only once with pre-construction inejection */ public abstract pointcut leastSpecificSuperTypeConstruction(); - + /** * Configure the bean */ public abstract void configureBean(Object bean); - - private pointcut preConstructionCondition() : + + private pointcut preConstructionCondition() : leastSpecificSuperTypeConstruction() && preConstructionConfiguration(); - + private pointcut postConstructionCondition() : mostSpecificSubTypeConstruction() && !preConstructionConfiguration(); - + /** * Pre-construction configuration. */ @SuppressAjWarnings("adviceDidNotMatch") - before(Object bean) : - beanConstruction(bean) && preConstructionCondition() && inConfigurableBean() { + before(Object bean) : + beanConstruction(bean) && preConstructionCondition() && inConfigurableBean() { configureBean(bean); } @@ -84,18 +86,18 @@ public abstract aspect AbstractDependencyInjectionAspect { * Post-construction configuration. */ @SuppressAjWarnings("adviceDidNotMatch") - after(Object bean) returning : + after(Object bean) returning : beanConstruction(bean) && postConstructionCondition() && inConfigurableBean() { configureBean(bean); } - + /** * Post-deserialization configuration. */ @SuppressAjWarnings("adviceDidNotMatch") - after(Object bean) returning : + after(Object bean) returning : beanDeserialization(bean) && inConfigurableBean() { configureBean(bean); } - + } diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj index 8e8b634ef0..8270d6962d 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AbstractInterfaceDrivenDependencyInjectionAspect.aj @@ -26,36 +26,36 @@ import java.io.Serializable; * upon deserialization. Subaspects need to simply provide definition for the configureBean() method. This * method may be implemented without relying on Spring container if so desired. *

- *

+ *

* There are two cases that needs to be handled: *

    - *
  1. Normal object creation via the 'new' operator: this is - * taken care of by advising initialization() join points.
  2. + *
  3. Normal object creation via the '{@code new}' operator: this is + * taken care of by advising {@code initialization()} join points.
  4. *
  5. Object creation through deserialization: since no constructor is * invoked during deserialization, the aspect needs to advise a method that a * deserialization mechanism is going to invoke. Ideally, we should not * require user classes to implement any specific method. This implies that * we need to introduce the chosen method. We should also handle the cases * where the chosen method is already implemented in classes (in which case, - * the user's implementation for that method should take precedence over the + * the user's implementation for that method should take precedence over the * introduced implementation). There are a few choices for the chosen method: *
      *
    • readObject(ObjectOutputStream): Java requires that the method must be - * private

      . Since aspects cannot introduce a private member, + * {@code private}

      . Since aspects cannot introduce a private member, * while preserving its name, this option is ruled out.
    • - *
    • readResolve(): Java doesn't pose any restriction on an access specifier. - * Problem solved! There is one (minor) limitation of this approach in - * that if a user class already has this method, that method must be - * public. However, this shouldn't be a big burden, since - * use cases that need classes to implement readResolve() (custom enums, + *
    • readResolve(): Java doesn't pose any restriction on an access specifier. + * Problem solved! There is one (minor) limitation of this approach in + * that if a user class already has this method, that method must be + * {@code public}. However, this shouldn't be a big burden, since + * use cases that need classes to implement readResolve() (custom enums, * for example) are unlikely to be marked as @Configurable, and - * in any case asking to make that method public should not + * in any case asking to make that method {@code public} should not * pose any undue burden.
    • *
    - * The minor collaboration needed by user classes (i.e., that the - * implementation of readResolve(), if any, must be - * public) can be lifted as well if we were to use an - * experimental feature in AspectJ - the hasmethod() PCD.
  6. + * The minor collaboration needed by user classes (i.e., that the + * implementation of {@code readResolve()}, if any, must be + * {@code public}) can be lifted as well if we were to use an + * experimental feature in AspectJ - the {@code hasmethod()} PCD. *
*

@@ -63,7 +63,7 @@ import java.io.Serializable; * is to use a 'declare parents' statement another aspect (a subaspect of this aspect would be a logical choice) * that declares the classes that need to be configured by supplying the {@link ConfigurableObject} interface. *

- * + * * @author Ramnivas Laddad * @since 2.5.2 */ @@ -71,8 +71,8 @@ public abstract aspect AbstractInterfaceDrivenDependencyInjectionAspect extends /** * Select initialization join point as object construction */ - public pointcut beanConstruction(Object bean) : - initialization(ConfigurableObject+.new(..)) && this(bean); + public pointcut beanConstruction(Object bean) : + initialization(ConfigurableObject+.new(..)) && this(bean); /** * Select deserialization join point made available through ITDs for ConfigurableDeserializationSupport @@ -80,40 +80,40 @@ public abstract aspect AbstractInterfaceDrivenDependencyInjectionAspect extends public pointcut beanDeserialization(Object bean) : execution(Object ConfigurableDeserializationSupport+.readResolve()) && this(bean); - + public pointcut leastSpecificSuperTypeConstruction() : initialization(ConfigurableObject.new(..)); - - - + + + // Implementation to support re-injecting dependencies once an object is deserialized /** - * Declare any class implementing Serializable and ConfigurableObject as also implementing - * ConfigurableDeserializationSupport. This allows us to introduce the readResolve() + * Declare any class implementing Serializable and ConfigurableObject as also implementing + * ConfigurableDeserializationSupport. This allows us to introduce the readResolve() * method and select it with the beanDeserialization() pointcut. - * + * *

Here is an improved version that uses the hasmethod() pointcut and lifts * even the minor requirement on user classes: * *

declare parents: ConfigurableObject+ Serializable+
-	 *		            && !hasmethod(Object readResolve() throws ObjectStreamException) 
+	 *		            && !hasmethod(Object readResolve() throws ObjectStreamException)
 	 *		            implements ConfigurableDeserializationSupport;
 	 * 
*/ - declare parents: + declare parents: ConfigurableObject+ && Serializable+ implements ConfigurableDeserializationSupport; - + /** - * A marker interface to which the readResolve() is introduced. + * A marker interface to which the {@code readResolve()} is introduced. */ static interface ConfigurableDeserializationSupport extends Serializable { } - + /** - * Introduce the readResolve() method so that we can advise its + * Introduce the {@code readResolve()} method so that we can advise its * execution to configure the object. - * + * *

Note if a method with the same signature already exists in a - * Serializable class of ConfigurableObject type, + * {@code Serializable} class of ConfigurableObject type, * that implementation will take precedence (a good thing, since we are * merely interested in an opportunity to detect deserialization.) */ diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj index 4cdc292dbb..2f1e91ccd2 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/AnnotationBeanConfigurerAspect.aj @@ -18,6 +18,7 @@ package org.springframework.beans.factory.aspectj; import java.io.Serializable; +import org.aspectj.lang.annotation.control.CodeGenerationHint; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -32,7 +33,7 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; * annotation to identify which classes need autowiring. * *

The bean name to look up will be taken from the - * @Configurable annotation if specified, otherwise the + * {@code @Configurable} annotation if specified, otherwise the * default bean name to look up will be the FQN of the class being configured. * * @author Rod Johnson @@ -43,7 +44,7 @@ import org.springframework.beans.factory.wiring.BeanConfigurerSupport; * @see org.springframework.beans.factory.annotation.Configurable * @see org.springframework.beans.factory.annotation.AnnotationBeanWiringInfoResolver */ -public aspect AnnotationBeanConfigurerAspect +public aspect AnnotationBeanConfigurerAspect extends AbstractInterfaceDrivenDependencyInjectionAspect implements BeanFactoryAware, InitializingBean, DisposableBean { @@ -51,7 +52,7 @@ public aspect AnnotationBeanConfigurerAspect public pointcut inConfigurableBean() : @this(Configurable); - public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*); + public pointcut preConstructionConfiguration() : preConstructionConfigurationSupport(*); declare parents: @Configurable * implements ConfigurableObject; @@ -77,13 +78,14 @@ public aspect AnnotationBeanConfigurerAspect /* * An intermediary to match preConstructionConfiguration signature (that doesn't expose the annotation object) */ + @CodeGenerationHint(ifNameSuffix="bb0") private pointcut preConstructionConfigurationSupport(Configurable c) : @this(c) && if(c.preConstruction()); /* - * This declaration shouldn't be needed, + * This declaration shouldn't be needed, * except for an AspectJ bug (https://bugs.eclipse.org/bugs/show_bug.cgi?id=214559) */ - declare parents: @Configurable Serializable+ + declare parents: @Configurable Serializable+ implements ConfigurableDeserializationSupport; } diff --git a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj index 03f446ca78..b4a3d93d1d 100644 --- a/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/beans/factory/aspectj/GenericInterfaceDrivenDependencyInjectionAspect.aj @@ -17,24 +17,24 @@ package org.springframework.beans.factory.aspectj; /** * Generic-based dependency injection aspect. - *

- * This aspect allows users to implement efficient, type-safe dependency injection without + *

+ * This aspect allows users to implement efficient, type-safe dependency injection without * the use of the @Configurable annotation. - * - * The subaspect of this aspect doesn't need to include any AOP constructs. - * For example, here is a subaspect that configures the PricingStrategyClient objects. + * + * The subaspect of this aspect doesn't need to include any AOP constructs. + * For example, here is a subaspect that configures the {@code PricingStrategyClient} objects. *

- * aspect PricingStrategyDependencyInjectionAspect 
+ * aspect PricingStrategyDependencyInjectionAspect
  *        extends GenericInterfaceDrivenDependencyInjectionAspect {
  *     private PricingStrategy pricingStrategy;
- *     
- *     public void configure(PricingStrategyClient bean) { 
- *         bean.setPricingStrategy(pricingStrategy); 
+ *
+ *     public void configure(PricingStrategyClient bean) {
+ *         bean.setPricingStrategy(pricingStrategy);
+ *     }
+ *
+ *     public void setPricingStrategy(PricingStrategy pricingStrategy) {
+ *         this.pricingStrategy = pricingStrategy;
  *     }
- *     
- *     public void setPricingStrategy(PricingStrategy pricingStrategy) { 
- *         this.pricingStrategy = pricingStrategy; 
- *     } 
  * }
  * 
* @author Ramnivas Laddad @@ -42,13 +42,13 @@ package org.springframework.beans.factory.aspectj; */ public abstract aspect GenericInterfaceDrivenDependencyInjectionAspect extends AbstractInterfaceDrivenDependencyInjectionAspect { declare parents: I implements ConfigurableObject; - + public pointcut inConfigurableBean() : within(I+); - + public final void configureBean(Object bean) { configure((I)bean); } - - // Unfortunately, erasure used with generics won't allow to use the same named method + + // Unfortunately, erasure used with generics won't allow to use the same named method protected abstract void configure(I bean); } diff --git a/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj b/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj index dbe15b8fb3..ce68942d40 100644 --- a/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/cache/aspectj/AbstractCacheAspect.aj @@ -62,7 +62,7 @@ public abstract aspect AbstractCacheAspect extends CacheAspectSupport { } }; - return execute(aspectJInvoker, thisJoinPoint.getTarget(), method, thisJoinPoint.getArgs()); + return execute(aspectJInvoker, thisJoinPoint.getTarget(), method, thisJoinPoint.getArgs()); } /** diff --git a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj index 7ab3fcd0c3..972a324859 100644 --- a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj +++ b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AbstractMethodMockingControl.aj @@ -23,9 +23,9 @@ import java.util.List; /** * Abstract aspect to enable mocking of methods picked out by a pointcut. * Sub-aspects must define the mockStaticsTestMethod() pointcut to - * indicate call stacks when mocking should be triggered, and the + * indicate call stacks when mocking should be triggered, and the * methodToMock() pointcut to pick out a method invocations to mock. - * + * * @author Rod Johnson * @author Ramnivas Laddad */ @@ -42,7 +42,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth // Represents a list of expected calls to static entity methods // Public to allow inserted code to access: is this normal?? public class Expectations { - + // Represents an expected call to a static entity method private class Call { private final String signature; @@ -50,21 +50,21 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth private Object responseObject; // return value or throwable private CallResponse responseType = CallResponse.nothing; - + public Call(String name, Object[] args) { this.signature = name; this.args = args; } - + public boolean hasResponseSpecified() { return responseType != CallResponse.nothing; } - + public void setReturnVal(Object retVal) { this.responseObject = retVal; responseType = CallResponse.return_; } - + public void setThrow(Throwable throwable) { this.responseObject = throwable; responseType = CallResponse.throw_; @@ -89,7 +89,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth } } } - + private List calls = new LinkedList(); // Calls already verified @@ -101,7 +101,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth + " calls, received " + verified); } } - + /** * Validate the call and provide the expected return value * @param lastSig @@ -175,7 +175,7 @@ public abstract aspect AbstractMethodMockingControl percflow(mockStaticsTestMeth return expectations.respond(thisJoinPointStaticPart.toLongString(), thisJoinPoint.getArgs()); } } - + public void expectReturnInternal(Object retVal) { if (!recording) { throw new IllegalStateException("Not recording: Cannot set return value"); diff --git a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj index 031978ca91..816f6a1e42 100644 --- a/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj +++ b/spring-aspects/src/main/java/org/springframework/mock/staticmock/AnnotationDrivenStaticEntityMockingControl.aj @@ -18,16 +18,16 @@ package org.springframework.mock.staticmock; /** * Annotation-based aspect to use in test build to enable mocking static methods - * on JPA-annotated @Entity classes, as used by Roo for finders. + * on JPA-annotated {@code @Entity} classes, as used by Roo for finders. * - *

Mocking will occur in the call stack of any method in a class (typically a test class) - * that is annotated with the @MockStaticEntityMethods annotation. + *

Mocking will occur in the call stack of any method in a class (typically a test class) + * that is annotated with the @MockStaticEntityMethods annotation. * *

Also provides static methods to simplify the programming model for * entering playback mode and setting expected return values. * *

Usage: - *

    + *
      *
    1. Annotate a test class with @MockStaticEntityMethods. *
    2. In each test method, AnnotationDrivenStaticEntityMockingControl will begin in recording mode. * Invoke static methods on Entity classes, with each recording-mode invocation @@ -37,20 +37,20 @@ package org.springframework.mock.staticmock; *
    3. Call the code you wish to test that uses the static methods. Verification will * occur automatically. *
    - * + * * @author Rod Johnson * @author Ramnivas Laddad * @see MockStaticEntityMethods */ public aspect AnnotationDrivenStaticEntityMockingControl extends AbstractMethodMockingControl { - + /** * Stop recording mock calls and enter playback state */ public static void playback() { AnnotationDrivenStaticEntityMockingControl.aspectOf().playbackInternal(); } - + public static void expectReturn(Object retVal) { AnnotationDrivenStaticEntityMockingControl.aspectOf().expectReturnInternal(retVal); } diff --git a/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj b/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj index 6ff44249d0..3507b60e0e 100644 --- a/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj @@ -1,3 +1,16 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this + * file except in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under + * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ package org.springframework.orm.jpa.aspectj; import javax.persistence.EntityManager; @@ -10,13 +23,13 @@ import org.springframework.orm.jpa.EntityManagerFactoryUtils; public aspect JpaExceptionTranslatorAspect { pointcut entityManagerCall(): call(* EntityManager.*(..)) || call(* EntityManagerFactory.*(..)) || call(* EntityTransaction.*(..)) || call(* Query.*(..)); - - after() throwing(RuntimeException re): entityManagerCall() { + + after() throwing(RuntimeException re): entityManagerCall() { DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(re); if (dex != null) { throw dex; } else { throw re; - } - } + } + } } \ No newline at end of file diff --git a/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj b/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj index 6cb3ad60e3..660b35c136 100644 --- a/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/scheduling/aspectj/AbstractAsyncExecutionAspect.aj @@ -28,7 +28,7 @@ import org.springframework.core.task.AsyncTaskExecutor; /** * Abstract aspect that routes selected methods asynchronously. * - *

    This aspect needs to be injected with an implementation of + *

    This aspect needs to be injected with an implementation of * {@link Executor} to activate it for a specific thread pool. * Otherwise it will simply delegate all calls synchronously. * diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj index ec5e803a39..f9c70661ae 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AbstractTransactionAspect.aj @@ -23,7 +23,7 @@ import org.springframework.transaction.interceptor.TransactionAttributeSource; /** * Abstract superaspect for AspectJ transaction aspects. Concrete - * subaspects will implement the transactionalMethodExecution() + * subaspects will implement the {@code transactionalMethodExecution()} * pointcut using a strategy such as Java 5 annotations. * *

    Suitable for use inside or outside the Spring IoC container. diff --git a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj index 026704ac08..70a82b5f4e 100644 --- a/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/transaction/aspectj/AnnotationTransactionAspect.aj @@ -21,17 +21,17 @@ import org.springframework.transaction.annotation.Transactional; /** * Concrete AspectJ transaction aspect using Spring's @Transactional annotation. - * + * *

    When using this aspect, you must annotate the implementation class * (and/or methods within that class), not the interface (if any) that - * the class implements. AspectJ follows Java's rule that annotations on + * the class implements. AspectJ follows Java's rule that annotations on * interfaces are not inherited. * *

    An @Transactional annotation on a class specifies the default transaction * semantics for the execution of any public operation in the class. * *

    An @Transactional annotation on a method within the class overrides the - * default transaction semantics given by the class annotation (if present). + * default transaction semantics given by the class annotation (if present). * Any method may be annotated (regardless of visibility). * Annotating non-public methods directly is the only way * to get transaction demarcation for the execution of such operations. @@ -64,7 +64,7 @@ public aspect AnnotationTransactionAspect extends AbstractTransactionAspect { /** * Definition of pointcut from super aspect - matched join points * will have Spring transaction management applied. - */ + */ protected pointcut transactionalMethodExecution(Object txObject) : (executionOfAnyPublicMethodInAtTransactionalType() || executionOfTransactionalMethod() ) From 0f2e94f0fc0ed999fb47cee3ebf4c93c64763113 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Wed, 27 Feb 2013 13:42:04 -0800 Subject: [PATCH 286/311] Fix reference docs section on inner beans Inner beans are not prototype beans as, in contrast to what is documented in the section for prototype beans, the inner bean does get destruction callbacks applied. Issue: SPR-10311 --- src/reference/docbook/beans-dependencies.xml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/reference/docbook/beans-dependencies.xml b/src/reference/docbook/beans-dependencies.xml index 0723be50fc..7c09841290 100644 --- a/src/reference/docbook/beans-dependencies.xml +++ b/src/reference/docbook/beans-dependencies.xml @@ -727,8 +727,7 @@ public class ExampleBean { container ignores these values. It also ignores the scope flag. Inner beans are always anonymous and they are - always scoped as prototypes. It is + always created with the outer bean. It is not possible to inject inner beans into collaborating beans other than into the enclosing bean.

From 301628811f8ab4e85fa87c5945a6b20e3c200d14 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 28 Feb 2013 01:36:03 +0100 Subject: [PATCH 287/311] Update JdbcTestUtils re: deprecated queryForInt() JdbcTestUtils now invokes JdbcTemplate's queryForObject() method instead of the deprecated queryForInt() method. Issue: SPR-10257 --- .../org/springframework/test/jdbc/JdbcTestUtils.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java b/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java index e096df5caa..ba4fc8fbe0 100644 --- a/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java +++ b/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java @@ -42,6 +42,7 @@ import org.springframework.util.StringUtils; * @author Thomas Risberg * @author Sam Brannen * @author Juergen Hoeller + * @author Phillip Webb * @since 2.5.4 */ public class JdbcTestUtils { @@ -60,7 +61,7 @@ public class JdbcTestUtils { * @return the number of rows in the table */ public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName) { - return jdbcTemplate.queryForInt("SELECT COUNT(0) FROM " + tableName); + return jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, int.class); } /** @@ -82,7 +83,7 @@ public class JdbcTestUtils { if (StringUtils.hasText(whereClause)) { sql += " WHERE " + whereClause; } - return jdbcTemplate.queryForInt(sql); + return jdbcTemplate.queryForObject(sql, int.class); } /** @@ -114,7 +115,7 @@ public class JdbcTestUtils { *

As an alternative to hard-coded values, the {@code "?"} placeholder can * be used within the {@code WHERE} clause, binding to the given arguments. * @param jdbcTemplate the JdbcTemplate with which to perform JDBC operations - * @param tableName the name of the table to delete rows in + * @param tableName the name of the table to delete rows from * @param whereClause the {@code WHERE} clause to append to the query * @param args arguments to bind to the query (leaving it to the PreparedStatement * to guess the corresponding SQL type); may also contain {@link SqlParameterValue} @@ -125,7 +126,7 @@ public class JdbcTestUtils { public static int deleteFromTableWhere(JdbcTemplate jdbcTemplate, String tableName, String whereClause, Object... args) { String sql = "DELETE FROM " + tableName; - if(StringUtils.hasText(whereClause)) { + if (StringUtils.hasText(whereClause)) { sql += " WHERE " + whereClause; } int rowCount = (args != null && args.length > 0 ? jdbcTemplate.update(sql, args) From 9b72bf4691c443af062205e001858e984ae9c791 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 28 Feb 2013 01:39:15 +0100 Subject: [PATCH 288/311] Update @since tag for StreamUtils --- .../src/main/java/org/springframework/util/StreamUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-core/src/main/java/org/springframework/util/StreamUtils.java b/spring-core/src/main/java/org/springframework/util/StreamUtils.java index a3bb9c8947..cc3107d81f 100644 --- a/spring-core/src/main/java/org/springframework/util/StreamUtils.java +++ b/spring-core/src/main/java/org/springframework/util/StreamUtils.java @@ -37,7 +37,7 @@ import java.nio.charset.Charset; * * @author Juergen Hoeller * @author Phillip Webb - * @since 3.2 + * @since 3.2.2 * @see FileCopyUtils */ public abstract class StreamUtils { From c0e4387cbcb9ef0b62372ae8a7a0fbca567b955a Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 28 Feb 2013 01:42:04 +0100 Subject: [PATCH 289/311] Fix JIRA issue number in @Ignore comments Issue: SPR-10333 --- ...aEntityManagerFactoryWithAspectJWeavingIntegrationTests.java | 2 +- .../TopLinkMultiEntityManagerFactoryIntegrationTests.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java index ec94bba49f..a35fdac8ca 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/openjpa/OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests.java @@ -25,7 +25,7 @@ import org.junit.Ignore; * @author Ramnivas Laddad * @author Chris Beams */ -@Ignore("This test causes gradle to hang. See SPR-103333.") +@Ignore("This test causes gradle to hang. See SPR-10333.") public class OpenJpaEntityManagerFactoryWithAspectJWeavingIntegrationTests extends OpenJpaEntityManagerFactoryIntegrationTests { @Override diff --git a/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java b/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java index 13d9226bce..7b74313114 100644 --- a/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java +++ b/spring-orm/src/test/java/org/springframework/orm/jpa/toplink/TopLinkMultiEntityManagerFactoryIntegrationTests.java @@ -28,7 +28,7 @@ import org.springframework.orm.jpa.AbstractContainerEntityManagerFactoryIntegrat * @author Costin Leau * @author Chris Beams */ -@Ignore("This test causes gradle to hang. See SPR-103333.") +@Ignore("This test causes gradle to hang. See SPR-10333.") public class TopLinkMultiEntityManagerFactoryIntegrationTests extends AbstractContainerEntityManagerFactoryIntegrationTests { From 013c894c2511b62cef8d88cfa35f8412f6a89e62 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 28 Feb 2013 01:56:13 +0100 Subject: [PATCH 290/311] Update JdbcTestUtils re: deprecated queryForInt() JdbcTestUtils now invokes JdbcTemplate's queryForObject() method instead of the deprecated queryForInt() method. Issue: SPR-10257 --- .../java/org/springframework/test/jdbc/JdbcTestUtils.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java b/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java index ba4fc8fbe0..383b20dff9 100644 --- a/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java +++ b/spring-test/src/main/java/org/springframework/test/jdbc/JdbcTestUtils.java @@ -61,7 +61,7 @@ public class JdbcTestUtils { * @return the number of rows in the table */ public static int countRowsInTable(JdbcTemplate jdbcTemplate, String tableName) { - return jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, int.class); + return jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, Integer.class); } /** @@ -83,7 +83,7 @@ public class JdbcTestUtils { if (StringUtils.hasText(whereClause)) { sql += " WHERE " + whereClause; } - return jdbcTemplate.queryForObject(sql, int.class); + return jdbcTemplate.queryForObject(sql, Integer.class); } /** From 2a78b975984c7aee84cb31bb4a29978ae155d9bd Mon Sep 17 00:00:00 2001 From: Chris Beams Date: Thu, 28 Feb 2013 09:03:36 +0100 Subject: [PATCH 291/311] Polish whitespace in JpaExceptionTranslatorAspect.aj Issue: SPR-10208 --- .../aspectj/JpaExceptionTranslatorAspect.aj | 44 +++++++++++-------- 1 file changed, 25 insertions(+), 19 deletions(-) diff --git a/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj b/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj index 3507b60e0e..131c82beef 100644 --- a/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj +++ b/spring-aspects/src/main/java/org/springframework/orm/jpa/aspectj/JpaExceptionTranslatorAspect.aj @@ -1,16 +1,19 @@ /* * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under - * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language governing - * permissions and limitations under the License. + * + * 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.orm.jpa.aspectj; import javax.persistence.EntityManager; @@ -22,14 +25,17 @@ import org.springframework.dao.DataAccessException; import org.springframework.orm.jpa.EntityManagerFactoryUtils; public aspect JpaExceptionTranslatorAspect { - pointcut entityManagerCall(): call(* EntityManager.*(..)) || call(* EntityManagerFactory.*(..)) || call(* EntityTransaction.*(..)) || call(* Query.*(..)); + pointcut entityManagerCall(): + call(* EntityManager.*(..)) || call(* EntityManagerFactory.*(..)) || + call(* EntityTransaction.*(..)) || call(* Query.*(..)); - after() throwing(RuntimeException re): entityManagerCall() { - DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(re); - if (dex != null) { - throw dex; - } else { - throw re; - } - } + after() throwing(RuntimeException re): entityManagerCall() { + DataAccessException dex = EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(re); + if (dex != null) { + throw dex; + } + else { + throw re; + } + } } \ No newline at end of file From 4bdf38271443fdd8f4e25c56e4c2d7e24a4ae2b7 Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 28 Feb 2013 13:46:56 +0100 Subject: [PATCH 292/311] Update spring-test re: deprecated queryForInt() Now invoking JdbcTemplate's queryForObject() method instead of the deprecated queryForInt() method within the test suite. Issue: SPR-10257 --- .../spr9051/AbstractTransactionalAnnotatedConfigClassTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java index 54b55c8c44..59cef2c1db 100644 --- a/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java +++ b/spring-test/src/test/java/org/springframework/test/context/junit4/spr9051/AbstractTransactionalAnnotatedConfigClassTests.java @@ -76,7 +76,7 @@ public abstract class AbstractTransactionalAnnotatedConfigClassTests { } private int countRowsInTable(String tableName) { - return jdbcTemplate.queryForInt("SELECT COUNT(0) FROM " + tableName); + return jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + tableName, Integer.class); } private int createPerson(String name) { From 381f7fe6df6174c16488fef72d1d0825eadee4bc Mon Sep 17 00:00:00 2001 From: Sam Brannen Date: Thu, 28 Feb 2013 13:48:15 +0100 Subject: [PATCH 293/311] Suppress warnings for resource leaks --- .../test/context/web/ServletTestExecutionListener.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java b/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java index 01302bb110..b87c987dac 100644 --- a/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java +++ b/spring-test/src/main/java/org/springframework/test/context/web/ServletTestExecutionListener.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -126,6 +126,7 @@ public class ServletTestExecutionListener extends AbstractTestExecutionListener RequestContextHolder.setRequestAttributes(servletWebRequest); if (wac instanceof ConfigurableApplicationContext) { + @SuppressWarnings("resource") ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac; ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory(); bf.registerResolvableDependency(MockHttpServletResponse.class, response); From 18df9fed9257b8cb80c6d321bf4600caec21ec33 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 28 Feb 2013 15:37:10 -0800 Subject: [PATCH 294/311] Fixed minor typo Issue: SPR-10210 --- .../org/springframework/expression/spel/SpelReproTests.java | 2 +- .../java/org/springframework/expression/spel/spr10210/A.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java index 62e00b0eb3..e6e28eedd3 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java @@ -1741,7 +1741,7 @@ public class SpelReproTests extends ExpressionTestCase { public void SPR_10210() throws Exception { StandardEvaluationContext context = new StandardEvaluationContext(); context.setVariable("bridgeExample", new org.springframework.expression.spel.spr10210.D()); - Expression parseExpression = parser.parseExpression("#bridgeExample.bridgetMethod()"); + Expression parseExpression = parser.parseExpression("#bridgeExample.bridgeMethod()"); parseExpression.getValue(context); } diff --git a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java index 35f2f0de93..3098b293c7 100644 --- a/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java +++ b/spring-expression/src/test/java/org/springframework/expression/spel/spr10210/A.java @@ -21,7 +21,7 @@ import org.springframework.expression.spel.spr10210.infra.C; abstract class A extends B { - public void bridgetMethod() { + public void bridgeMethod() { } } From c4ba8ce1243012ea1f5e6946614787de1a20dd54 Mon Sep 17 00:00:00 2001 From: Tomasz Nurkiewicz Date: Wed, 27 Feb 2013 22:41:31 +0100 Subject: [PATCH 295/311] Fix incorrect closing tag in MVC docs --- src/reference/docbook/mvc.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/reference/docbook/mvc.xml b/src/reference/docbook/mvc.xml index fb7d5e96cb..a9e8489af3 100644 --- a/src/reference/docbook/mvc.xml +++ b/src/reference/docbook/mvc.xml @@ -2602,7 +2602,7 @@ deferredResult.setResult(data); ... - <web-app> + </web-app> The DispatcherServlet and any From 39c236baa8c3f189cc422f2814443fd9652876fb Mon Sep 17 00:00:00 2001 From: Carson McDonald Date: Thu, 28 Feb 2013 07:45:50 -0500 Subject: [PATCH 296/311] Fix minor javadoc typos --- .../jms/listener/endpoint/JmsMessageEndpointFactory.java | 6 +++--- .../jca/endpoint/GenericMessageEndpointFactory.java | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointFactory.java b/spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointFactory.java index 392d02b1fa..954dd4982e 100644 --- a/spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointFactory.java +++ b/spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsMessageEndpointFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -109,11 +109,11 @@ public class JmsMessageEndpointFactory extends AbstractMessageEndpointFactory { /** - * Internal exception thrown when a ResourceExeption has been encountered + * Internal exception thrown when a ResourceException has been encountered * during the endpoint invocation. *

Will only be used if the ResourceAdapter does not invoke the * endpoint's {@code beforeDelivery} and {@code afterDelivery} - * directly, leavng it up to the concrete endpoint to apply those - + * directly, leaving it up to the concrete endpoint to apply those - * and to handle any ResourceExceptions thrown from them. */ @SuppressWarnings("serial") diff --git a/spring-tx/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointFactory.java b/spring-tx/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointFactory.java index fac5eba990..61f8db5b4e 100644 --- a/spring-tx/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointFactory.java +++ b/spring-tx/src/main/java/org/springframework/jca/endpoint/GenericMessageEndpointFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -141,11 +141,11 @@ public class GenericMessageEndpointFactory extends AbstractMessageEndpointFactor /** - * Internal exception thrown when a ResourceExeption has been encountered + * Internal exception thrown when a ResourceException has been encountered * during the endpoint invocation. *

Will only be used if the ResourceAdapter does not invoke the * endpoint's {@code beforeDelivery} and {@code afterDelivery} - * directly, leavng it up to the concrete endpoint to apply those - + * directly, leaving it up to the concrete endpoint to apply those - * and to handle any ResourceExceptions thrown from them. */ @SuppressWarnings("serial") From e0c7571a41adb0d21e95ac16d72d1f792aa4bdd6 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 15:51:45 +0100 Subject: [PATCH 297/311] Refined predictBeanType's typesToMatch check for FactoryBeans GroovyScriptFactoryTests passes again now. Issue: SPR-10304 --- .../support/AbstractAutowireCapableBeanFactory.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index f0f519e2a1..3b4dfcd83d 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -582,11 +582,10 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; - Class predictedType = ibp.predictBeanType(beanClass, beanName); - if (predictedType != null && (typesToMatch.length > 1 || - (typesToMatch.length > 0 && !FactoryBean.class.equals(typesToMatch[0])) || - FactoryBean.class.isAssignableFrom(predictedType))) { - return predictedType; + Class predicted = ibp.predictBeanType(beanClass, beanName); + if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) || + FactoryBean.class.isAssignableFrom(predicted))) { + return predicted; } } } From 1716c171d8805049fc115942ebd96ecd793e926a Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 16:04:10 +0100 Subject: [PATCH 298/311] LazyConnectionDataSourceProxy catches setReadOnly exception analogous to DataSourceUtils Also mentioning JDBC 4's unwrap method for obtaining the native connection now. Issue: SPR-10312 --- .../LazyConnectionDataSourceProxy.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java index f6ddc15b34..5495aa68ce 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/LazyConnectionDataSourceProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,18 +66,17 @@ import org.springframework.core.Constants; * You will get the same effect with non-transactional reads, but lazy fetching * of JDBC Connections allows you to still perform reads in transactions. * - *

NOTE: This DataSource proxy needs to return wrapped Connections to - * handle lazy fetching of an actual JDBC Connection. Therefore, the returned - * Connections cannot be cast to a native JDBC Connection type like OracleConnection, - * or to a connection pool implementation type. Use a corresponding - * NativeJdbcExtractor to retrieve the native JDBC Connection. + *

NOTE: This DataSource proxy needs to return wrapped Connections + * (which implement the {@link ConnectionProxy} interface) in order to handle + * lazy fetching of an actual JDBC Connection. Therefore, the returned Connections + * cannot be cast to a native JDBC Connection type such as OracleConnection or + * to a connection pool implementation type. Use a corresponding + * {@link org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor} + * or JDBC 4's {@link Connection#unwrap} to retrieve the native JDBC Connection. * * @author Juergen Hoeller * @since 1.1.4 - * @see ConnectionProxy * @see DataSourceTransactionManager - * @see org.springframework.orm.hibernate3.HibernateTransactionManager - * @see org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor */ public class LazyConnectionDataSourceProxy extends DelegatingDataSource { @@ -407,7 +406,13 @@ public class LazyConnectionDataSourceProxy extends DelegatingDataSource { // Apply kept transaction settings, if any. if (this.readOnly) { - this.target.setReadOnly(this.readOnly); + try { + this.target.setReadOnly(this.readOnly); + } + catch (Exception ex) { + // "read-only not supported" -> ignore, it's just a hint anyway + logger.debug("Could not set JDBC Connection read-only", ex); + } } if (this.transactionIsolation != null && !this.transactionIsolation.equals(defaultTransactionIsolation())) { From 6a043e3ea190ef648bf2063020665fd45ab329d2 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 16:05:27 +0100 Subject: [PATCH 299/311] Mentioning JDBC 4's unwrap method for obtaining the native connection now --- .../jdbc/datasource/TransactionAwareDataSourceProxy.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java index 1321c81662..3bde77765d 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/datasource/TransactionAwareDataSourceProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -64,10 +64,10 @@ import org.springframework.util.Assert; *

NOTE: This DataSource proxy needs to return wrapped Connections * (which implement the {@link ConnectionProxy} interface) in order to handle * close calls properly. Therefore, the returned Connections cannot be cast - * to a native JDBC Connection type like OracleConnection or to a connection + * to a native JDBC Connection type such as OracleConnection or to a connection * pool implementation type. Use a corresponding * {@link org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor} - * to retrieve the native JDBC Connection. + * or JDBC 4's {@link Connection#unwrap} to retrieve the native JDBC Connection. * * @author Juergen Hoeller * @since 1.1 From c986a1efc12a8c0c1c0e797ea5c0d3023e0b0287 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 16:43:24 +0100 Subject: [PATCH 300/311] Cache target type per bean definition and allow for specifying it in advance Issue: SPR-10335 --- .../AbstractAutowireCapableBeanFactory.java | 23 ++++++++------ .../factory/support/RootBeanDefinition.java | 31 +++++++++++++++---- 2 files changed, 39 insertions(+), 15 deletions(-) diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java index 3b4dfcd83d..09faf0c3b2 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java @@ -572,17 +572,22 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac } @Override - protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class... typesToMatch) { - Class beanClass = (mbd.getFactoryMethodName() != null ? - getTypeForFactoryMethod(beanName, mbd, typesToMatch) : - resolveBeanClass(mbd, beanName, typesToMatch)); + protected Class predictBeanType(String beanName, RootBeanDefinition mbd, Class... typesToMatch) { + Class targetType = mbd.getTargetType(); + if (targetType == null) { + targetType = (mbd.getFactoryMethodName() != null ? getTypeForFactoryMethod(beanName, mbd, typesToMatch) : + resolveBeanClass(mbd, beanName, typesToMatch)); + if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) { + mbd.setTargetType(targetType); + } + } // Apply SmartInstantiationAwareBeanPostProcessors to predict the // eventual type after a before-instantiation shortcut. - if (beanClass != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { + if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; - Class predicted = ibp.predictBeanType(beanClass, beanName); + Class predicted = ibp.predictBeanType(targetType, beanName); if (predicted != null && (typesToMatch.length != 1 || !FactoryBean.class.equals(typesToMatch[0]) || FactoryBean.class.isAssignableFrom(predicted))) { return predicted; @@ -590,7 +595,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac } } } - return beanClass; + return targetType; } /** @@ -607,8 +612,8 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac * @return the type for the bean if determinable, or {@code null} else * @see #createBean */ - protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { - Class factoryClass; + protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class[] typesToMatch) { + Class factoryClass; boolean isStatic = true; String factoryBeanName = mbd.getFactoryBeanName(); diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java index 7eaba17a54..64d0555d49 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/RootBeanDefinition.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,8 +61,12 @@ public class RootBeanDefinition extends AbstractBeanDefinition { boolean allowCaching = true; + private volatile Class targetType; + boolean isFactoryMethodUnique = false; + final Object constructorArgumentLock = new Object(); + /** Package-visible field for caching the resolved constructor or factory method */ Object resolvedConstructorOrFactoryMethod; @@ -75,15 +79,13 @@ public class RootBeanDefinition extends AbstractBeanDefinition { /** Package-visible field for caching partly prepared constructor arguments */ Object[] preparedConstructorArguments; - final Object constructorArgumentLock = new Object(); - - /** Package-visible field that indicates a before-instantiation post-processor having kicked in */ - volatile Boolean beforeInstantiationResolved; + final Object postProcessingLock = new Object(); /** Package-visible field that indicates MergedBeanDefinitionPostProcessor having been applied */ boolean postProcessed = false; - final Object postProcessingLock = new Object(); + /** Package-visible field that indicates a before-instantiation post-processor having kicked in */ + volatile Boolean beforeInstantiationResolved; /** @@ -236,6 +238,8 @@ public class RootBeanDefinition extends AbstractBeanDefinition { if (original instanceof RootBeanDefinition) { RootBeanDefinition originalRbd = (RootBeanDefinition) original; this.decoratedDefinition = originalRbd.decoratedDefinition; + this.allowCaching = originalRbd.allowCaching; + this.targetType = originalRbd.targetType; this.isFactoryMethodUnique = originalRbd.isFactoryMethodUnique; } } @@ -251,6 +255,21 @@ public class RootBeanDefinition extends AbstractBeanDefinition { } } + /** + * Specify the target type of this bean definition, if known in advance. + */ + public void setTargetType(Class targetType) { + this.targetType = targetType; + } + + /** + * Return the target type of this bean definition, if known + * (either specified in advance or resolved on first instantiation). + */ + public Class getTargetType() { + return this.targetType; + } + /** * Specify a factory method name that refers to a non-overloaded method. */ From b27fc0ef30df4b3633bfa8b5960f9da35d212b48 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Thu, 28 Feb 2013 17:48:12 -0800 Subject: [PATCH 301/311] Do not use Servlet 3.0 API in doOptions() Refactor FrameworkServlet.doOptions() to capture the "Allow" header by using a HttpServletResponseWrapper. Prior to this commit the HttpServletResponse.getHeader() method was used which is only available in Servlet 3.0 environments. Issue: SPR-10341 --- .../web/servlet/FrameworkServlet.java | 17 +++++++++++++---- .../web/servlet/DispatcherServletTests.java | 5 ++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java index 3dca4eda94..a3f3c37547 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java @@ -26,6 +26,7 @@ import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; import org.springframework.beans.BeanUtils; import org.springframework.context.ApplicationContext; @@ -866,10 +867,18 @@ public abstract class FrameworkServlet extends HttpServletBean { return; } } - super.doOptions(request, response); - String allowedMethods = response.getHeader("Allow"); - allowedMethods += ", " + RequestMethod.PATCH.name(); - response.setHeader("Allow", allowedMethods); + + // Use response wrapper for Servlet 2.5 compatibility where + // the getHeader() method does not exist + super.doOptions(request, new HttpServletResponseWrapper(response) { + @Override + public void setHeader(String name, String value) { + if("Allow".equals(name)) { + value = (StringUtils.hasLength(value) ? value + ", " : "") + RequestMethod.PATCH.name(); + } + super.setHeader(name, value); + } + }); } /** diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java index b73e69ae6f..667fb643b4 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/DispatcherServletTests.java @@ -61,6 +61,8 @@ import org.springframework.web.util.WebUtils; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; /** * @author Rod Johnson @@ -857,9 +859,10 @@ public class DispatcherServletTests extends TestCase { public void testAllowedOptionsIncludesPatchMethod() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "OPTIONS", "/foo"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = spy(new MockHttpServletResponse()); DispatcherServlet servlet = new DispatcherServlet(); servlet.service(request, response); + verify(response, never()).getHeader(anyString()); // SPR-10341 assertThat(response.getHeader("Allow"), equalTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH")); } From 5d727b2d8e6896392a5b55c83ec9ad8e985e97ce Mon Sep 17 00:00:00 2001 From: Jakub Narloch Date: Fri, 1 Mar 2013 11:10:22 -0800 Subject: [PATCH 302/311] Add Castor XSD information to reference docs Update the Spring OXM reference documentation to include changes introduced in CastorMarshaller, specifically around CastorMarshaller XSD configuration. Issue: SPR-8509 --- src/reference/docbook/oxm.xml | 83 +++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/src/reference/docbook/oxm.xml b/src/reference/docbook/oxm.xml index 00ae396620..1a7cbac17c 100644 --- a/src/reference/docbook/oxm.xml +++ b/src/reference/docbook/oxm.xml @@ -332,6 +332,9 @@ public class Application { xmlbeans-marshaller + + castor-marshaller + jibx-marshaller @@ -475,6 +478,86 @@ public class Application { ]]> +

+ XML Schema-based Configuration + + The castor-marshaller tag configures a + org.springframework.oxm.castor.CastorMarshaller. + Here is an example: + + + + ]]> + + + The marshaller instance can be configured in two ways, by specifying either the location of + a mapping file (through the mapping-location property), or by + identifying Java POJOs (through the target-class or + target-package properties) for which there exist corresponding + XML descriptor classes. The latter way is usually used in conjunction with XML code generation + from XML schemas. + + + + Available attributes are: + + + + + + + + Attribute + Description + Required + + + + + + id + + the id of the marshaller + no + + + + encoding + + the encoding to use for unmarshalling from XML + no + + + + target-class + + a Java class name for a POJO for which an XML class descriptor is available (as + generated through code generation) + + no + + + + target-package + + a Java package name that identifies a package that contains POJOs and their + corresponding Castor + XML descriptor classes (as generated through code generation from XML schemas) + + no + + + + mapping-location + + location of a Castor XML mapping file + no + + + + + +
From 2bd584ca751f4ea805f59948494f47b9dffd3315 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 21:49:11 +0100 Subject: [PATCH 303/311] Added "createTemporaryLob" flag to DefaultLobHandler, using JDBC 4.0's createBlob/Clob mechanism Issue: SPR-10339 --- .../jdbc/support/lob/DefaultLobHandler.java | 75 +++++--- .../jdbc/support/lob/LobHandler.java | 26 ++- .../jdbc/support/lob/TemporaryLobCreator.java | 167 ++++++++++++++++++ 3 files changed, 237 insertions(+), 31 deletions(-) create mode 100644 spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/TemporaryLobCreator.java diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/DefaultLobHandler.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/DefaultLobHandler.java index 6964172e96..e570be24f0 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/DefaultLobHandler.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/DefaultLobHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,18 +32,20 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** - * Default implementation of the {@link LobHandler} interface. Invokes - * the direct accessor methods that {@code java.sql.ResultSet} + * Default implementation of the {@link LobHandler} interface. + * Invokes the direct accessor methods that {@code java.sql.ResultSet} * and {@code java.sql.PreparedStatement} offer. * *

This LobHandler should work for any JDBC driver that is JDBC compliant * in terms of the spec's suggestions regarding simple BLOB and CLOB handling. - * This does not apply to Oracle 9i, and only to a limited degree to Oracle 10g! - * As a consequence, use {@link OracleLobHandler} for accessing Oracle BLOBs/CLOBs. + * This does not apply to Oracle 9i's drivers at all; as of Oracle 10g, + * it does work but may still come with LOB size limitations. Consider using + * recent Oracle drivers even when working against an older database server. + * See the {@link LobHandler} javadoc for the full set of recommendations. * *

Some JDBC drivers require values with a BLOB/CLOB target column to be - * explicitly set through the JDBC {@code setBlob} / {@code setClob} - * API: for example, PostgreSQL's driver. Switch the {@link #setWrapAsLob "wrapAsLob"} + * explicitly set through the JDBC {@code setBlob} / {@code setClob} API: + * for example, PostgreSQL's driver. Switch the {@link #setWrapAsLob "wrapAsLob"} * property to "true" when operating against such a driver. * *

On JDBC 4.0, this LobHandler also supports streaming the BLOB/CLOB content @@ -51,11 +53,15 @@ import org.apache.commons.logging.LogFactory; * argument directly. Consider switching the {@link #setStreamAsLob "streamAsLob"} * property to "true" when operating against a fully compliant JDBC 4.0 driver. * - *

See the {@link LobHandler} javadoc for a summary of recommendations. + *

Finally, primarily as a direct equivalent to {@link OracleLobHandler}, + * this LobHandler also supports the creation of temporary BLOB/CLOB objects. + * Consider switching the {@link #setCreateTemporaryLob "createTemporaryLob"} + * property to "true" when "streamAsLob" happens to run into LOB size limitations. + * + *

See the {@link LobHandler} interface javadoc for a summary of recommendations. * * @author Juergen Hoeller * @since 04.12.2003 - * @see #setStreamAsLob * @see java.sql.ResultSet#getBytes * @see java.sql.ResultSet#getBinaryStream * @see java.sql.ResultSet#getString @@ -75,15 +81,18 @@ public class DefaultLobHandler extends AbstractLobHandler { private boolean streamAsLob = false; + private boolean createTemporaryLob = false; + /** * Specify whether to submit a byte array / String to the JDBC driver * wrapped in a JDBC Blob / Clob object, using the JDBC {@code setBlob} / * {@code setClob} method with a Blob / Clob argument. *

Default is "false", using the common JDBC 2.0 {@code setBinaryStream} - * / {@code setCharacterStream} method for setting the content. - * Switch this to "true" for explicit Blob / Clob wrapping against - * JDBC drivers that are known to require such wrapping (e.g. PostgreSQL's). + * / {@code setCharacterStream} method for setting the content. Switch this + * to "true" for explicit Blob / Clob wrapping against JDBC drivers that + * are known to require such wrapping (e.g. PostgreSQL's for access to OID + * columns, whereas BYTEA columns need to be accessed the standard way). *

This setting affects byte array / String arguments as well as stream * arguments, unless {@link #setStreamAsLob "streamAsLob"} overrides this * handling to use JDBC 4.0's new explicit streaming support (if available). @@ -100,7 +109,7 @@ public class DefaultLobHandler extends AbstractLobHandler { * {@code setClob} method with a stream argument. *

Default is "false", using the common JDBC 2.0 {@code setBinaryStream} * / {@code setCharacterStream} method for setting the content. - * Switch this to "true" for explicit JDBC 4.0 usage, provided that your + * Switch this to "true" for explicit JDBC 4.0 streaming, provided that your * JDBC driver actually supports those JDBC 4.0 operations (e.g. Derby's). *

This setting affects stream arguments as well as byte array / String * arguments, requiring JDBC 4.0 support. For supporting LOB content against @@ -112,6 +121,23 @@ public class DefaultLobHandler extends AbstractLobHandler { this.streamAsLob = streamAsLob; } + /** + * Specify whether to copy a byte array / String into a temporary JDBC + * Blob / Clob object created through the JDBC 4.0 {@code createBlob} / + * {@code createClob} methods. + *

Default is "false", using the common JDBC 2.0 {@code setBinaryStream} + * / {@code setCharacterStream} method for setting the content. Switch this + * to "true" for explicit Blob / Clob creation using JDBC 4.0. + *

This setting affects stream arguments as well as byte array / String + * arguments, requiring JDBC 4.0 support. For supporting LOB content against + * JDBC 3.0, check out the {@link #setWrapAsLob "wrapAsLob"} setting. + * @see java.sql.Connection#createBlob() + * @see java.sql.Connection#createClob() + */ + public void setCreateTemporaryLob(boolean createTemporaryLob) { + this.createTemporaryLob = createTemporaryLob; + } + public byte[] getBlobAsBytes(ResultSet rs, int columnIndex) throws SQLException { logger.debug("Returning BLOB as bytes"); @@ -169,12 +195,12 @@ public class DefaultLobHandler extends AbstractLobHandler { } public LobCreator getLobCreator() { - return new DefaultLobCreator(); + return (this.createTemporaryLob ? new TemporaryLobCreator() : new DefaultLobCreator()); } /** - * Default LobCreator implementation as inner class. + * Default LobCreator implementation as an inner class. * Can be subclassed in DefaultLobHandler extensions. */ protected class DefaultLobCreator implements LobCreator { @@ -268,15 +294,10 @@ public class DefaultLobHandler extends AbstractLobHandler { PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength) throws SQLException { - if (streamAsLob || wrapAsLob) { + if (streamAsLob) { if (asciiStream != null) { try { - if (streamAsLob) { - ps.setClob(paramIndex, new InputStreamReader(asciiStream, "US-ASCII"), contentLength); - } - else { - ps.setClob(paramIndex, new PassThroughClob(asciiStream, contentLength)); - } + ps.setClob(paramIndex, new InputStreamReader(asciiStream, "US-ASCII"), contentLength); } catch (UnsupportedEncodingException ex) { throw new SQLException("US-ASCII encoding not supported: " + ex); @@ -286,6 +307,14 @@ public class DefaultLobHandler extends AbstractLobHandler { ps.setClob(paramIndex, (Clob) null); } } + else if (wrapAsLob) { + if (asciiStream != null) { + ps.setClob(paramIndex, new PassThroughClob(asciiStream, contentLength)); + } + else { + ps.setClob(paramIndex, (Clob) null); + } + } else { ps.setAsciiStream(paramIndex, asciiStream, contentLength); } @@ -325,7 +354,7 @@ public class DefaultLobHandler extends AbstractLobHandler { } public void close() { - // nothing to do here + // nothing to do when not creating temporary LOBs } } diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/LobHandler.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/LobHandler.java index 251a63a0e8..07e1847e4f 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/LobHandler.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/LobHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import java.sql.SQLException; /** * Abstraction for handling large binary fields and large text fields in * specific databases, no matter if represented as simple types or Large OBjects. - * Its main purpose is to isolate Oracle's peculiar handling of LOBs in + * Its main purpose is to isolate Oracle 9i's peculiar handling of LOBs in * {@link OracleLobHandler}; most other databases should be able to work * with the provided {@link DefaultLobHandler}. * @@ -45,8 +45,10 @@ import java.sql.SQLException; * proprietary BLOB/CLOB API, and additionally doesn't accept large streams for * PreparedStatement's corresponding setter methods. Therefore, you need to use * {@link OracleLobHandler} there, which uses Oracle's BLOB/CLOB API for both types - * of access. The Oracle 10g JDBC driver should basically work with - * {@link DefaultLobHandler} as well, with some limitations in terms of LOB sizes. + * of access. The Oracle 10g+ JDBC driver will work with {@link DefaultLobHandler} + * as well, with some limitations in terms of LOB sizes depending on DBMS setup; + * as of Oracle 11g (or actually, using the 11g driver even against older databases), + * there should be no need to use {@link OracleLobHandler} at all anymore. * *

Of course, you need to declare different field types for each database. * In Oracle, any binary content needs to go into a BLOB, and all character content @@ -57,12 +59,20 @@ import java.sql.SQLException; * *

Summarizing the recommended options (for actual LOB fields): *

    - *
  • JDBC 4.0 driver: {@link DefaultLobHandler} with {@code streamAsLob=true}. - *
  • PostgreSQL: {@link DefaultLobHandler} with {@code wrapAsLob=true}. - *
  • Oracle 9i/10g: {@link OracleLobHandler} with a connection-pool-specific + *
  • JDBC 4.0 driver (including Oracle 11g driver): Use {@link DefaultLobHandler}, + * potentially with {@code streamAsLob=true} if your database driver requires that + * hint when populating a LOB field. Fall back to {@code createTemporaryLob=true} + * if you happen to run into LOB size limitations with your (Oracle) database setup. + *
  • Oracle 10g driver: Use {@link DefaultLobHandler} with standard setup. + * On Oracle 10.1, set the "SetBigStringTryClob" connection property; as of Oracle 10.2, + * DefaultLobHandler should work with standard setup out of the box. Alternatively, + * consider using the proprietary {@link OracleLobHandler} (see below). + *
  • Oracle 9i driver: Use {@link OracleLobHandler} with a connection-pool-specific * {@link OracleLobHandler#setNativeJdbcExtractor NativeJdbcExtractor}. + *
  • PostgreSQL: Configure {@link DefaultLobHandler} with {@code wrapAsLob=true}, + * and use that LobHandler to access OID columns (but not BYTEA) in your database tables. *
  • For all other database drivers (and for non-LOB fields that might potentially - * turn into LOBs on some databases): a plain {@link DefaultLobHandler}. + * turn into LOBs on some databases): Simply use a plain {@link DefaultLobHandler}. *
* * @author Juergen Hoeller diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/TemporaryLobCreator.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/TemporaryLobCreator.java new file mode 100644 index 0000000000..f8c52660cb --- /dev/null +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/TemporaryLobCreator.java @@ -0,0 +1,167 @@ +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.jdbc.support.lob; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.LinkedHashSet; +import java.util.Set; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.util.FileCopyUtils; + +/** + * {@link LobCreator} implementation based on temporary LOBs, + * using JDBC 4.0's {@link java.sql.Connection#createBlob()} / + * {@link java.sql.Connection#createClob()} mechanism. + * + *

Used by DefaultLobHandler's {@link DefaultLobHandler#setCreateTemporaryLob} mode. + * Can also be used directly to reuse the tracking and freeing of temporary LOBs. + * + * @author Juergen Hoeller + * @since 3.2.2 + * @see DefaultLobHandler#setCreateTemporaryLob + * @see java.sql.Connection#createBlob() + * @see java.sql.Connection#createClob() + */ +public class TemporaryLobCreator implements LobCreator { + + protected static final Log logger = LogFactory.getLog(TemporaryLobCreator.class); + + private final Set temporaryBlobs = new LinkedHashSet(1); + + private final Set temporaryClobs = new LinkedHashSet(1); + + + public void setBlobAsBytes(PreparedStatement ps, int paramIndex, byte[] content) + throws SQLException { + + Blob blob = ps.getConnection().createBlob(); + blob.setBytes(1, content); + + this.temporaryBlobs.add(blob); + ps.setBlob(paramIndex, blob); + + if (logger.isDebugEnabled()) { + logger.debug(content != null ? "Copied bytes into temporary BLOB with length " + content.length : + "Set BLOB to null"); + } + } + + public void setBlobAsBinaryStream( + PreparedStatement ps, int paramIndex, InputStream binaryStream, int contentLength) + throws SQLException { + + Blob blob = ps.getConnection().createBlob(); + try { + FileCopyUtils.copy(binaryStream, blob.setBinaryStream(1)); + } + catch (IOException ex) { + throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); + } + + this.temporaryBlobs.add(blob); + ps.setBlob(paramIndex, blob); + + if (logger.isDebugEnabled()) { + logger.debug(binaryStream != null ? + "Copied binary stream into temporary BLOB with length " + contentLength : + "Set BLOB to null"); + } + } + + public void setClobAsString(PreparedStatement ps, int paramIndex, String content) + throws SQLException { + + Clob clob = ps.getConnection().createClob(); + clob.setString(1, content); + + this.temporaryClobs.add(clob); + ps.setClob(paramIndex, clob); + + if (logger.isDebugEnabled()) { + logger.debug(content != null ? "Copied string into temporary CLOB with length " + content.length() : + "Set CLOB to null"); + } + } + + public void setClobAsAsciiStream( + PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength) + throws SQLException { + + Clob clob = ps.getConnection().createClob(); + try { + FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1)); + } + catch (IOException ex) { + throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); + } + + this.temporaryClobs.add(clob); + ps.setClob(paramIndex, clob); + + if (logger.isDebugEnabled()) { + logger.debug(asciiStream != null ? + "Copied ASCII stream into temporary CLOB with length " + contentLength : + "Set CLOB to null"); + } + } + + public void setClobAsCharacterStream( + PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength) + throws SQLException { + + Clob clob = ps.getConnection().createClob(); + try { + FileCopyUtils.copy(characterStream, clob.setCharacterStream(1)); + } + catch (IOException ex) { + throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex); + } + + this.temporaryClobs.add(clob); + ps.setClob(paramIndex, clob); + + if (logger.isDebugEnabled()) { + logger.debug(characterStream != null ? + "Copied character stream into temporary CLOB with length " + contentLength : + "Set CLOB to null"); + } + } + + public void close() { + try { + for (Blob blob : this.temporaryBlobs) { + blob.free(); + } + for (Clob clob : this.temporaryClobs) { + clob.free(); + } + } + catch (SQLException ex) { + logger.error("Could not free LOB", ex); + } + } +} From 99c7f25b053daaf20cf850807cd3f8fea244971b Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 21:50:30 +0100 Subject: [PATCH 304/311] Deprecated OracleLobHandler in favor of DefaultLobHandler for the Oracle 10g driver and higher Issue: SPR-10339 --- .../jdbc/support/lob/OracleLobHandler.java | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/OracleLobHandler.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/OracleLobHandler.java index 5399cf9c91..2b239b3504 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/OracleLobHandler.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/OracleLobHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,14 +49,23 @@ import org.springframework.util.FileCopyUtils; * Note that this LobHandler requires Oracle JDBC driver 9i or higher! * *

While most databases are able to work with {@link DefaultLobHandler}, - * Oracle just accepts Blob/Clob instances created via its own proprietary - * BLOB/CLOB API, and additionally doesn't accept large streams for - * PreparedStatement's corresponding setter methods. Therefore, you need - * to use a strategy like this LobHandler implementation. + * Oracle 9i (or more specifically, the Oracle 9i JDBC driver) just accepts + * Blob/Clob instances created via its own proprietary BLOB/CLOB API, + * and additionally doesn't accept large streams for PreparedStatement's + * corresponding setter methods. Therefore, you need to use a strategy like + * this LobHandler implementation, or upgrade to the Oracle 10g/11g driver + * (which still supports access to Oracle 9i databases). + * + *

NOTE: As of Oracle 10.2, {@link DefaultLobHandler} should work equally + * well out of the box. On Oracle 11g, JDBC 4.0 based options such as + * {@link DefaultLobHandler#setStreamAsLob} and {@link DefaultLobHandler#setCreateTemporaryLob} + * are available as well, rendering this proprietary OracleLobHandler obsolete. + * Also, consider upgrading to a new driver even when accessing an older database. + * See the {@link LobHandler} interface javadoc for a summary of recommendations. * *

Needs to work on a native JDBC Connection, to be able to cast it to * {@code oracle.jdbc.OracleConnection}. If you pass in Connections from a - * connection pool (the usual case in a J2EE environment), you need to set an + * connection pool (the usual case in a Java EE environment), you need to set an * appropriate {@link org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractor} * to allow for automatic retrieval of the underlying native JDBC Connection. * LobHandler and NativeJdbcExtractor are separate concerns, therefore they @@ -72,8 +81,15 @@ import org.springframework.util.FileCopyUtils; * @author Juergen Hoeller * @author Thomas Risberg * @since 04.12.2003 + * @see DefaultLobHandler * @see #setNativeJdbcExtractor + * @deprecated in favor of {@link DefaultLobHandler} for the Oracle 10g driver and + * higher. Consider using the 10g/11g driver even against an Oracle 9i database! + * {@link DefaultLobHandler#setCreateTemporaryLob} is the direct equivalent of this + * OracleLobHandler's implementation strategy, just using standard JDBC 4.0 API. + * That said, in most cases, regular DefaultLobHandler setup will work fine as well. */ +@Deprecated public class OracleLobHandler extends AbstractLobHandler { private static final String BLOB_CLASS_NAME = "oracle.sql.BLOB"; @@ -143,7 +159,7 @@ public class OracleLobHandler extends AbstractLobHandler { } /** - * Set whether to agressively release any resources used by the LOB. If set to {@code true} + * Set whether to aggressively release any resources used by the LOB. If set to {@code true} * then you can only read the LOB values once. Any subsequent reads will fail since the resources * have been closed. *

Setting this property to {@code true} can be useful when your queries generates large @@ -283,7 +299,7 @@ public class OracleLobHandler extends AbstractLobHandler { ((BLOB) lob).open(BLOB.MODE_READONLY); */ Method open = lob.getClass().getMethod("open", int.class); - open.invoke(lob, modeReadOnlyConstants.get(lob.getClass())); + open.invoke(lob, this.modeReadOnlyConstants.get(lob.getClass())); } } catch (InvocationTargetException ex) { @@ -366,7 +382,7 @@ public class OracleLobHandler extends AbstractLobHandler { */ protected class OracleLobCreator implements LobCreator { - private final List createdLobs = new LinkedList(); + private final List temporaryLobs = new LinkedList(); public void setBlobAsBytes(PreparedStatement ps, int paramIndex, final byte[] content) throws SQLException { @@ -495,7 +511,7 @@ public class OracleLobHandler extends AbstractLobHandler { Object lob = prepareLob(con, clob ? clobClass : blobClass); callback.populateLob(lob); lob.getClass().getMethod("close", (Class[]) null).invoke(lob, (Object[]) null); - this.createdLobs.add(lob); + this.temporaryLobs.add(lob); if (logger.isDebugEnabled()) { logger.debug("Created new Oracle " + (clob ? "CLOB" : "BLOB")); } @@ -556,7 +572,7 @@ public class OracleLobHandler extends AbstractLobHandler { */ public void close() { try { - for (Iterator it = this.createdLobs.iterator(); it.hasNext();) { + for (Iterator it = this.temporaryLobs.iterator(); it.hasNext();) { /* BLOB blob = (BLOB) it.next(); blob.freeTemporary(); From d3c0dd1c7e207045b5b530a6139db269e0c2dbd6 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 21:53:40 +0100 Subject: [PATCH 305/311] Minor javadoc updates --- ...tLobCreatingPreparedStatementCallback.java | 8 +++--- .../jdbc/support/lob/AbstractLobHandler.java | 4 +-- .../WebLogicNativeJdbcExtractor.java | 4 +-- .../WebSphereNativeJdbcExtractor.java | 25 +++++++++---------- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java b/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java index 7ef0b32583..c106ad57f4 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/core/support/AbstractLobCreatingPreparedStatementCallback.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,15 +23,16 @@ import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.PreparedStatementCallback; import org.springframework.jdbc.support.lob.LobCreator; import org.springframework.jdbc.support.lob.LobHandler; +import org.springframework.util.Assert; /** - * Abstract PreparedStatementCallback implementation that manages a LobCreator. + * Abstract {@link PreparedStatementCallback} implementation that manages a {@link LobCreator}. * Typically used as inner class, with access to surrounding method arguments. * *

Delegates to the {@code setValues} template method for setting values * on the PreparedStatement, using a given LobCreator for BLOB/CLOB arguments. * - *

A usage example with JdbcTemplate: + *

A usage example with {@link org.springframework.jdbc.core.JdbcTemplate}: * *

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);  // reusable object
  * LobHandler lobHandler = new DefaultLobHandler();  // reusable object
@@ -62,6 +63,7 @@ public abstract class AbstractLobCreatingPreparedStatementCallback implements Pr
 	 * @param lobHandler the LobHandler to create LobCreators with
 	 */
 	public AbstractLobCreatingPreparedStatementCallback(LobHandler lobHandler) {
+		Assert.notNull(lobHandler, "LobHandler must not be null");
 		this.lobHandler = lobHandler;
 	}
 
diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/AbstractLobHandler.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/AbstractLobHandler.java
index 737a582459..4da40d61fa 100644
--- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/AbstractLobHandler.java
+++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/lob/AbstractLobHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2002-2005 the original author or authors.
+ * Copyright 2002-2013 the original author or authors.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -22,7 +22,7 @@ import java.sql.ResultSet;
 import java.sql.SQLException;
 
 /**
- * Abstract base class for LobHandler implementations.
+ * Abstract base class for {@link LobHandler} implementations.
  *
  * 

Implements all accessor methods for column names through a column lookup * and delegating to the corresponding accessor that takes a column index. diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebLogicNativeJdbcExtractor.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebLogicNativeJdbcExtractor.java index e967966aee..09129320e5 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebLogicNativeJdbcExtractor.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebLogicNativeJdbcExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.springframework.util.ReflectionUtils; /** * Implementation of the {@link NativeJdbcExtractor} interface for WebLogic, - * supporting WebLogic Server 8.1 and higher. + * supporting WebLogic Server 9.0 and higher. * *

Returns the underlying native Connection to application code instead * of WebLogic's wrapper implementation; unwraps the Connection for native diff --git a/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebSphereNativeJdbcExtractor.java b/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebSphereNativeJdbcExtractor.java index d40a575c7a..b225ea19d2 100644 --- a/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebSphereNativeJdbcExtractor.java +++ b/spring-jdbc/src/main/java/org/springframework/jdbc/support/nativejdbc/WebSphereNativeJdbcExtractor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2012 the original author or authors. + * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,7 +24,7 @@ import org.springframework.util.ReflectionUtils; /** * Implementation of the {@link NativeJdbcExtractor} interface for WebSphere, - * supporting WebSphere Application Server 5.1 and higher. + * supporting WebSphere Application Server 6.1 and higher. * *

Returns the underlying native Connection to application code instead * of WebSphere's wrapper implementation; unwraps the Connection for @@ -40,14 +40,14 @@ import org.springframework.util.ReflectionUtils; */ public class WebSphereNativeJdbcExtractor extends NativeJdbcExtractorAdapter { - private static final String JDBC_ADAPTER_CONNECTION_NAME_5 = "com.ibm.ws.rsadapter.jdbc.WSJdbcConnection"; + private static final String JDBC_ADAPTER_CONNECTION_NAME = "com.ibm.ws.rsadapter.jdbc.WSJdbcConnection"; - private static final String JDBC_ADAPTER_UTIL_NAME_5 = "com.ibm.ws.rsadapter.jdbc.WSJdbcUtil"; + private static final String JDBC_ADAPTER_UTIL_NAME = "com.ibm.ws.rsadapter.jdbc.WSJdbcUtil"; - private Class webSphere5ConnectionClass; + private Class webSphereConnectionClass; - private Method webSphere5NativeConnectionMethod; + private Method webSphereNativeConnectionMethod; /** @@ -56,10 +56,10 @@ public class WebSphereNativeJdbcExtractor extends NativeJdbcExtractorAdapter { */ public WebSphereNativeJdbcExtractor() { try { - this.webSphere5ConnectionClass = getClass().getClassLoader().loadClass(JDBC_ADAPTER_CONNECTION_NAME_5); - Class jdbcAdapterUtilClass = getClass().getClassLoader().loadClass(JDBC_ADAPTER_UTIL_NAME_5); - this.webSphere5NativeConnectionMethod = - jdbcAdapterUtilClass.getMethod("getNativeConnection", new Class[] {this.webSphere5ConnectionClass}); + this.webSphereConnectionClass = getClass().getClassLoader().loadClass(JDBC_ADAPTER_CONNECTION_NAME); + Class jdbcAdapterUtilClass = getClass().getClassLoader().loadClass(JDBC_ADAPTER_UTIL_NAME); + this.webSphereNativeConnectionMethod = + jdbcAdapterUtilClass.getMethod("getNativeConnection", new Class[] {this.webSphereConnectionClass}); } catch (Exception ex) { throw new IllegalStateException( @@ -97,9 +97,8 @@ public class WebSphereNativeJdbcExtractor extends NativeJdbcExtractorAdapter { */ @Override protected Connection doGetNativeConnection(Connection con) throws SQLException { - if (this.webSphere5ConnectionClass.isAssignableFrom(con.getClass())) { - return (Connection) ReflectionUtils.invokeJdbcMethod( - this.webSphere5NativeConnectionMethod, null, new Object[] {con}); + if (this.webSphereConnectionClass.isAssignableFrom(con.getClass())) { + return (Connection) ReflectionUtils.invokeJdbcMethod(this.webSphereNativeConnectionMethod, null, con); } return con; } From 4cc30fe54164326e1eb41fb029a3d3f3fcd55303 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Fri, 1 Mar 2013 21:54:24 +0100 Subject: [PATCH 306/311] DefaultLobHandler etc --- src/dist/changelog.txt | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/dist/changelog.txt b/src/dist/changelog.txt index 7002f57645..1e6da7b4ef 100644 --- a/src/dist/changelog.txt +++ b/src/dist/changelog.txt @@ -3,12 +3,13 @@ SPRING FRAMEWORK CHANGELOG http://www.springsource.org -Changes in version 3.2.2 (2013-03-07) +Changes in version 3.2.2 (2013-03-11) -------------------------------------- * official support for Hibernate 4.2 (SPR-10255) * fixed missing inter-dependencies in module POMs (SPR-10218) * marked spring-web module as 'distributable' in order for session replication to work on Tomcat (SPR-10219) +* DefaultListableBeanFactory caches target type per bean definition and allows for specifying it in advance (SPR-10335) * ConfigurationClassPostProcessor consistently uses ClassLoader, not loading core JDK annotations via ASM (SPR-10249) * ConfigurationClassPostProcessor detects covariant return type mismatch, avoiding infinite recursion (SPR-10261) * ConfigurationClassPostProcessor allows for overriding of scoped-proxy bean definitions (SPR-10265) @@ -21,10 +22,15 @@ Changes in version 3.2.2 (2013-03-07) * @Scheduled provides String variants of fixedDelay, fixedRate, initialDelay for placeholder support (SPR-8067) * refined CronSequenceGenerator's rounding up of seconds to address second-specific cron expressions (SPR-9459) * @Transactional in AspectJ mode works with CallbackPreferringPlatformTransactionManager (WebSphere) as well (SPR-9268) +* LazyConnectionDataSourceProxy catches setReadOnly exception analogous to DataSourceUtils (SPR-10312) * SQLErrorCodeSQLExceptionTranslator tries to find SQLException with actual error code among causes (SPR-10260) +* added "createTemporaryLob" flag to DefaultLobHandler, using JDBC 4.0's createBlob/Clob mechanism (SPR-10339) +* deprecated OracleLobHandler in favor of DefaultLobHandler for the Oracle 10g driver and higher (SPR-10339) * deprecated (NamedParameter)JdbcTemplate's queryForInt/Long operations in favor of queryForObject (SPR-10257) * added useful query variants without parameters to NamedParameterJdbcTemplate, for convenience in DAOs (SPR-10256) * "packagesToScan" feature for Hibernate 3 and Hibernate 4 detects annotated packages as well (SPR-7748, SPR-10288) +* HibernateTransactionManager for Hibernate 4 supports "entityInterceptor(BeanName)" property (SPR-10301) +* DefaultJdoDialect supports the JDO 2.2+ isolation level feature out of the box (SPR-10323) * DefaultMessageListenerContainer invokes specified ExceptionListener for recovery exceptions as well (SPR-10230) * DefaultMessageListenerContainer logs recovery failures at error level and exposes "isRecovering()" method (SPR-10230) * added "mappedClass" property to Jaxb2Marshaller, introducing support for partial unmarshalling (SPR-10282) From 33e723b4a870946fbba89d68b17db4efbea2084e Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 15 Feb 2013 12:25:25 -0500 Subject: [PATCH 307/311] Fix AntPathMatcher rule for combining with extensions Before this fix AntPathMatcher had a special rule for combining patterns with wildcards and extensions as follows: "/*.*" + "/*.html" => "/*.html" This change ensures this rule never applies if the first pattern contains URI variables. Issue: SPR-10062 --- .../main/java/org/springframework/util/AntPathMatcher.java | 6 ++++-- .../java/org/springframework/util/AntPathMatcherTests.java | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java b/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java index 0ae86e0879..e7fefa175d 100644 --- a/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java +++ b/spring-core/src/main/java/org/springframework/util/AntPathMatcher.java @@ -317,7 +317,9 @@ public class AntPathMatcher implements PathMatcher { else if (!StringUtils.hasText(pattern2)) { return pattern1; } - else if (!pattern1.equals(pattern2) && !pattern1.contains("{") && match(pattern1, pattern2)) { + + boolean pattern1ContainsUriVar = pattern1.indexOf('{') != -1; + if (!pattern1.equals(pattern2) && !pattern1ContainsUriVar && match(pattern1, pattern2)) { // /* + /hotel -> /hotel ; "/*.*" + "/*.html" -> /*.html // However /user + /user -> /usr/user ; /{foo} + /bar -> /{foo}/bar return pattern2; @@ -344,7 +346,7 @@ public class AntPathMatcher implements PathMatcher { } else { int dotPos1 = pattern1.indexOf('.'); - if (dotPos1 == -1) { + if (dotPos1 == -1 || pattern1ContainsUriVar) { // simply concatenate the two patterns if (pattern1.endsWith("/") || pattern2.startsWith("/")) { return pattern1 + pattern2; diff --git a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java index 0a34e1c470..05a98f405d 100644 --- a/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java +++ b/spring-core/src/test/java/org/springframework/util/AntPathMatcherTests.java @@ -412,6 +412,7 @@ public class AntPathMatcherTests { assertEquals("/*.html", pathMatcher.combine("/*.*", "/*.html")); assertEquals("/{foo}/bar", pathMatcher.combine("/{foo}", "/bar")); // SPR-8858 assertEquals("/user/user", pathMatcher.combine("/user", "/user")); // SPR-7970 + assertEquals("/{foo:.*[^0-9].*}/edit/", pathMatcher.combine("/{foo:.*[^0-9].*}", "/edit/")); // SPR-10062 } @Test From 3abe05c65e40755e209971888e3d5e6ea38b2487 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 1 Mar 2013 15:00:20 -0500 Subject: [PATCH 308/311] Update @RequestParam javadoc Issue: SPR-10180 --- .../springframework/web/bind/annotation/RequestParam.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java index 43032ba598..b1395b4985 100644 --- a/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java +++ b/spring-web/src/main/java/org/springframework/web/bind/annotation/RequestParam.java @@ -68,8 +68,9 @@ public @interface RequestParam { boolean required() default true; /** - * The default value to use as a fallback. Supplying a default value implicitly - * sets {@link #required()} to false. + * The default value to use as a fallback when the request parameter value + * is not provided or empty. Supplying a default value implicitly sets + * {@link #required()} to false. */ String defaultValue() default ValueConstants.DEFAULT_NONE; From c611083415845bcb9758c0f92c4749a712b049f0 Mon Sep 17 00:00:00 2001 From: Rossen Stoyanchev Date: Fri, 1 Mar 2013 15:16:08 -0500 Subject: [PATCH 309/311] Catch IAE when parsing content type Issue: SPR-10308 --- .../method/RequestMappingInfoHandlerMapping.java | 7 ++++++- .../RequestMappingInfoHandlerMappingTests.java | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java index cc242bf756..89fcb4e9e1 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java @@ -205,7 +205,12 @@ public abstract class RequestMappingInfoHandlerMapping extends AbstractHandlerMe if (!consumableMediaTypes.isEmpty()) { MediaType contentType = null; if (StringUtils.hasLength(request.getContentType())) { - contentType = MediaType.parseMediaType(request.getContentType()); + try { + contentType = MediaType.parseMediaType(request.getContentType()); + } + catch (IllegalArgumentException ex) { + throw new HttpMediaTypeNotSupportedException(ex.getMessage()); + } } throw new HttpMediaTypeNotSupportedException(contentType, new ArrayList(consumableMediaTypes)); } diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java index 0998bf59f0..099197c07d 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java @@ -180,6 +180,19 @@ public class RequestMappingInfoHandlerMappingTests { } } + @Test + public void testMediaTypeNotValue() throws Exception { + try { + MockHttpServletRequest request = new MockHttpServletRequest("PUT", "/person/1"); + request.setContentType("bogus"); + this.handlerMapping.getHandler(request); + fail("HttpMediaTypeNotSupportedException expected"); + } + catch (HttpMediaTypeNotSupportedException ex) { + assertEquals("Invalid media type \"bogus\": does not contain '/'", ex.getMessage()); + } + } + @Test public void mediaTypeNotAccepted() throws Exception { testMediaTypeNotAccepted("/persons"); From fbac428e231118538c7273f04a4ac0bbdae47d68 Mon Sep 17 00:00:00 2001 From: Wesley Hall Date: Thu, 21 Feb 2013 14:05:29 +0000 Subject: [PATCH 310/311] Fix DefaultMockMvcBuilder fluent API generic type Changed upper bound of generic parameter for DefaultMockMvcBuilder from MockMvcBuilder to DefaultMockMvcBuilder to allow for ongoing method chaining in the fluent API style. Issue: SPR-10277 --- .../servlet/setup/DefaultMockMvcBuilder.java | 2 +- .../test/web/servlet/setup/Spr10277Tests.java | 43 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 spring-test-mvc/src/test/java/org/springframework/test/web/servlet/setup/Spr10277Tests.java diff --git a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java index a44f43a816..7e8b7afd63 100644 --- a/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java +++ b/spring-test-mvc/src/main/java/org/springframework/test/web/servlet/setup/DefaultMockMvcBuilder.java @@ -42,7 +42,7 @@ import org.springframework.web.servlet.DispatcherServlet; * @author Rob Winch * @since 3.2 */ -public class DefaultMockMvcBuilder extends MockMvcBuilderSupport +public class DefaultMockMvcBuilder extends MockMvcBuilderSupport implements MockMvcBuilder { private final WebApplicationContext webAppContext; diff --git a/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/setup/Spr10277Tests.java b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/setup/Spr10277Tests.java new file mode 100644 index 0000000000..101285c520 --- /dev/null +++ b/spring-test-mvc/src/test/java/org/springframework/test/web/servlet/setup/Spr10277Tests.java @@ -0,0 +1,43 @@ +package org.springframework.test.web.servlet.setup; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.filter.CharacterEncodingFilter; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +/** + * Test for SPR-10277 (Multiple method chaining when building MockMvc). + * + * @author Wesley Hall + */ +@RunWith(SpringJUnit4ClassRunner.class) +@WebAppConfiguration +@ContextConfiguration +public class Spr10277Tests { + + @Autowired + private WebApplicationContext wac; + + @Test + public void chainMultiple() { + MockMvcBuilders + .webAppContextSetup(wac) + .addFilter(new CharacterEncodingFilter() ) + .defaultRequest(get("/").contextPath("/mywebapp")) + .build(); + } + + @Configuration + @EnableWebMvc + static class WebConfig extends WebMvcConfigurerAdapter { + } +} From ba03d5b0c7d7211f910c5bc48c0895fe86614104 Mon Sep 17 00:00:00 2001 From: Stevo Slavic Date: Fri, 1 Mar 2013 00:17:15 +0100 Subject: [PATCH 311/311] Fix FreeMarker form checbox macro generated names In Spring 3.2 a fix was implemented for all Spring Freemarker form macros so that generated form input fields have valid bracketless IDs. In the fix a regression was introduced manifesting in formCheckbox macro no longer generating appropriate names for checkbox and hidden input field. This change fixes mentioned regression issue. Issue: SPR-8732 --- .../web/servlet/view/freemarker/spring.ftl | 4 +-- .../view/freemarker/FreeMarkerMacroTests.java | 31 ++++++++++++------- .../web/servlet/view/freemarker/test.ftl | 3 ++ 3 files changed, 25 insertions(+), 13 deletions(-) diff --git a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/freemarker/spring.ftl b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/freemarker/spring.ftl index 43b29af322..bfb41221f7 100644 --- a/spring-webmvc/src/main/java/org/springframework/web/servlet/view/freemarker/spring.ftl +++ b/spring-webmvc/src/main/java/org/springframework/web/servlet/view/freemarker/spring.ftl @@ -309,8 +309,8 @@ <@bind path /> <#assign id="${status.expression?replace('[','')?replace(']','')}"> <#assign isSelected = status.value?? && status.value?string=="true"> - - checked="checked" ${attributes}/> + + checked="checked" ${attributes}/> <#-- diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java index 17a4c4f50c..9e4f320ef6 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/FreeMarkerMacroTests.java @@ -107,7 +107,7 @@ public class FreeMarkerMacroTests { fv.setApplicationContext(wac); fv.setExposeSpringMacroHelpers(true); - Map model = new HashMap(); + Map model = new HashMap(); model.put("tb", new TestBean("juergen", 99)); fv.render(model, request, response); } @@ -126,7 +126,7 @@ public class FreeMarkerMacroTests { fv.setApplicationContext(wac); fv.setExposeSpringMacroHelpers(true); - Map model = new HashMap(); + Map model = new HashMap(); model.put(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, helperTool); try { @@ -265,6 +265,13 @@ public class FreeMarkerMacroTests { assertEquals("", getMacroOutput("FORM17")); } + @Test + public void testForm18() throws Exception { + String output = getMacroOutput("FORM18"); + assertTrue("Wrong output: " + output, output.startsWith("")); + assertTrue("Wrong output: " + output, output.contains("")); + } + private String getMacroOutput(String name) throws Exception { String macro = fetchMacro(name); @@ -274,30 +281,32 @@ public class FreeMarkerMacroTests { FileCopyUtils.copy("<#import \"spring.ftl\" as spring />\n" + macro, new FileWriter(resource.getPath())); DummyMacroRequestContext rc = new DummyMacroRequestContext(request); - Map msgMap = new HashMap(); + Map msgMap = new HashMap(); msgMap.put("hello", "Howdy"); msgMap.put("world", "Mundo"); rc.setMessageMap(msgMap); - Map themeMsgMap = new HashMap(); + Map themeMsgMap = new HashMap(); themeMsgMap.put("hello", "Howdy!"); themeMsgMap.put("world", "Mundo!"); rc.setThemeMessageMap(themeMsgMap); rc.setContextPath("/springtest"); - TestBean tb = new TestBean("Darren", 99); - tb.setSpouse(new TestBean("Fred")); - tb.setJedi(true); - request.setAttribute("command", tb); + TestBean darren = new TestBean("Darren", 99); + TestBean fred = new TestBean("Fred"); + fred.setJedi(true); + darren.setSpouse(fred); + darren.setJedi(true); + request.setAttribute("command", darren); - HashMap names = new HashMap(); + Map names = new HashMap(); names.put("Darren", "Darren Davison"); names.put("John", "John Doe"); names.put("Fred", "Fred Bloggs"); names.put("Rob&Harrop", "Rob Harrop"); Configuration config = fc.getConfiguration(); - Map model = new HashMap(); - model.put("command", tb); + Map model = new HashMap(); + model.put("command", darren); model.put("springMacroRequestContext", rc); model.put("msgArgs", new Object[] { "World" }); model.put("nameOptionMap", names); diff --git a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/test.ftl b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/test.ftl index 8440b4f945..b1e0156186 100644 --- a/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/test.ftl +++ b/spring-webmvc/src/test/java/org/springframework/web/servlet/view/freemarker/test.ftl @@ -89,3 +89,6 @@ FORM16 FORM17 <@spring.formInput "command.spouses[0].name", ""/> + +FORM18 +<@spring.formCheckbox "command.spouses[0].jedi" />